'use client';

import { MobileLayout } from '../../../../../components/mobile-layout';
import { useQuery } from '@tanstack/react-query';
import api from '../../../../../lib/api-client';
import { useRouter } from 'next/navigation';
import { ArrowLeft, MapPin, Calendar, Package, Truck, User, FileText, Lightbulb, ArrowRight, AlertTriangle } from 'lucide-react';
import { smartRound } from '../../../../../lib/utils';

function IntelligentNoteRenderer({ text }: { text: string }) {
  if (!text) return null;

  // Pattern 1: Unit Decomposition
  // "Received: 31 x Bags (10kg). Converted to 310.00 x Kg (Contract Standard)."
  const unitRegex = /Received: (.+)\. Converted to (.+) \(Contract Standard\)\.?/i;
  
  // Pattern 2: Discrepancy Verification
  // "Verify: Quantity entered as 31 (Breakdown sums to 310.00)."
  const verifyRegex = /Verify: Quantity entered as (.+) \(Breakdown sums to (.+)\)\.?/i;

  const lines = text.split('\n\n').filter(Boolean);

  return (
    <div className="space-y-3 mt-1">
      {lines.map((line, idx) => {
        const unitMatch = line.match(unitRegex);
        if (unitMatch) {
          return (
             <div key={idx} className="rounded-xl border border-slate-100 bg-slate-50 p-2.5">
               <p className="text-[10px] font-bold uppercase tracking-wide text-slate-400 mb-1.5">Intelligent Unit Conversion</p>
               <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
                 <div className="rounded-lg bg-white px-2 py-1 shadow-sm border border-slate-100 text-xs font-medium text-slate-700">
                   {unitMatch[1]}
                 </div>
                 <ArrowRight className="hidden sm:block h-3.5 w-3.5 text-slate-400" />
                 <div className="sm:hidden text-center text-xs text-slate-400">↓</div>
                 <div className="rounded-lg bg-emerald-50 px-2 py-1 border border-emerald-100 text-xs font-bold text-emerald-700">
                   {unitMatch[2]}
                 </div>
               </div>
             </div>
          );
        }

        const verifyMatch = line.match(verifyRegex);
        if (verifyMatch) {
          return (
            <div key={idx} className="rounded-xl border border-amber-200 bg-amber-50 p-2.5">
               <div className="flex items-start gap-2">
                 <AlertTriangle className="h-4 w-4 text-amber-600 mt-0.5" />
                 <div>
                   <p className="text-xs font-bold text-amber-800">Verified Discrepancy</p>
                   <p className="text-xs text-amber-700 mt-0.5">
                     User manually override: Entered <strong>{verifyMatch[1]}</strong> but calculated <strong>{verifyMatch[2]}</strong>.
                   </p>
                 </div>
               </div>
            </div>
          );
        }

        return <p key={idx} className="text-sm text-slate-700">{line}</p>;
      })}
    </div>
  );
}

export default function DeliveryDetailsPage({ params }: { params: { id: string } }) {
  const router = useRouter();
  const { id } = params;

  const { data: delivery, isLoading, isError } = useQuery({
    queryKey: ['delivery', id],
    queryFn: async () => {
      const response = await api.get(`/deliveries/${id}`);
      return response.data;
    },
  });

  if (isLoading) {
    return (
      <MobileLayout>
        <div className="flex h-screen items-center justify-center">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-brand border-t-transparent"></div>
        </div>
      </MobileLayout>
    );
  }

  if (isError || !delivery) {
    return (
      <MobileLayout>
        <div className="p-4 text-center">
          <p className="text-red-500">Failed to load delivery details.</p>
          <button onClick={() => router.back()} className="mt-4 text-brand underline">
            Go back
          </button>
        </div>
      </MobileLayout>
    );
  }

  return (
    <MobileLayout>
      <div className="min-h-screen bg-slate-50 pb-20">
        {/* Header */}
        <div className="sticky top-0 z-10 flex items-center gap-3 bg-white px-4 py-3 shadow-sm">
          <button onClick={() => router.back()} className="rounded-full p-2 hover:bg-slate-100">
            <ArrowLeft className="h-5 w-5 text-slate-600" />
          </button>
          <h1 className="text-lg font-bold text-slate-900">Delivery Details</h1>
        </div>

        <div className="p-4 space-y-6">
          {/* Main Status Card */}
          <div className="rounded-2xl bg-white p-6 shadow-sm border border-slate-100 text-center">
            <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-green-100">
              <Package className="h-8 w-8 text-green-600" />
            </div>
            <h2 className="text-3xl font-bold text-slate-900">{smartRound(delivery.actual_quantity)}</h2>
            <p className="text-sm font-medium text-slate-500 uppercase tracking-wide">{delivery.commodity_name}</p>
            <div className="mt-4 inline-flex items-center rounded-full bg-green-50 px-3 py-1 text-xs font-medium text-green-700 border border-green-100">
              Successfully Recorded
            </div>
          </div>

          {/* Details Grid */}
          <div className="rounded-2xl bg-white shadow-sm border border-slate-100 overflow-hidden">
            <div className="divide-y divide-slate-100">
              
              {/* School */}
              <div className="flex items-start gap-4 p-4">
                <div className="rounded-lg bg-blue-50 p-2">
                  <MapPin className="h-5 w-5 text-blue-600" />
                </div>
                <div>
                  <p className="text-xs font-medium text-slate-500 uppercase">School</p>
                  <p className="font-semibold text-slate-900">{delivery.school_name}</p>
                  <p className="text-sm text-slate-500">{delivery.school_region}</p>
                </div>
              </div>

              {/* Quantities Breakdown */}
              <div className="bg-slate-50/50 p-4">
                <p className="mb-3 text-xs font-bold uppercase tracking-wide text-slate-400">Balance Impact</p>
                <div className="grid grid-cols-3 gap-2 text-center">
                  <div className="rounded-lg bg-white p-2 shadow-sm border border-slate-100">
                    <p className="text-[10px] font-medium uppercase text-slate-400">Expected</p>
                    <p className="text-lg font-bold text-slate-700">{smartRound(delivery.expected_quantity_before)}</p>
                  </div>
                  <div className="flex items-center justify-center text-slate-300 font-bold">-</div>
                  <div className="rounded-lg bg-white p-2 shadow-sm border border-slate-100">
                    <p className="text-[10px] font-medium uppercase text-slate-400">Actual</p>
                    <p className="text-lg font-bold text-brand">{smartRound(delivery.actual_quantity)}</p>
                  </div>
                </div>
                <div className="mt-2 flex items-center justify-center gap-2">
                  <span className="text-slate-300 font-bold">=</span>
                  <div className="flex items-center gap-2 rounded-lg bg-white px-3 py-1 shadow-sm border border-slate-100">
                    <p className="text-[10px] font-medium uppercase text-slate-400">Remaining</p>
                    <p className="text-lg font-bold text-slate-900">{smartRound(delivery.remaining_quantity_after)}</p>
                  </div>
                </div>
                <div className="mt-3 text-center">
                   <p className="text-xs text-slate-400">Total Allocated for Period: <span className="font-medium text-slate-600">{smartRound(delivery.total_allocated)}</span></p>
                </div>
              </div>

              {/* Date */}
              <div className="flex items-start gap-4 p-4">
                <div className="rounded-lg bg-orange-50 p-2">
                  <Calendar className="h-5 w-5 text-orange-600" />
                </div>
                <div>
                  <p className="text-xs font-medium text-slate-500 uppercase">Delivery Date</p>
                  <p className="font-semibold text-slate-900">{new Date(delivery.delivery_date).toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</p>
                </div>
              </div>

              {/* Supplier */}
              <div className="flex items-start gap-4 p-4">
                <div className="rounded-lg bg-purple-50 p-2">
                  <Truck className="h-5 w-5 text-purple-600" />
                </div>
                <div>
                  <p className="text-xs font-medium text-slate-500 uppercase">Supplier</p>
                  <p className="font-semibold text-slate-900">{delivery.supplier_name || 'N/A'}</p>
                </div>
              </div>

              {/* Recorded By */}
              <div className="flex items-start gap-4 p-4">
                <div className="rounded-lg bg-slate-100 p-2">
                  <User className="h-5 w-5 text-slate-600" />
                </div>
                <div>
                  <p className="text-xs font-medium text-slate-500 uppercase">Recorded By</p>
                  <p className="font-semibold text-slate-900">{delivery.user_name}</p>
                </div>
              </div>

              {/* Notes */}
              {delivery.notes && (
                <div className="flex items-start gap-4 p-4">
                  <div className="rounded-lg bg-yellow-50 p-2">
                    <FileText className="h-5 w-5 text-yellow-600" />
                  </div>
                  <div className="flex-1">
                    <p className="text-xs font-medium text-slate-500 uppercase">Notes</p>
                    <IntelligentNoteRenderer text={delivery.notes} />
                  </div>
                </div>
              )}

            </div>
          </div>

          {/* Metadata */}
          <div className="text-center text-xs text-slate-400">
            <p>Reference ID: #{delivery.id}</p>
            <p>Recorded on: {new Date(delivery.created_at).toLocaleString()}</p>
          </div>
        </div>
      </div>
    </MobileLayout>
  );
}
