'use client';

import { useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { MobileLayout } from '../../../../../components/mobile-layout';
import api from '../../../../../lib/api-client';
import { useSupplierDirectory } from '../../../../../hooks/use-supplier-directory';
import { ArrowLeft, Phone, Package, School, AlertCircle } from 'lucide-react';
import { smartRound } from '../../../../../lib/utils';

const PER_PAGE = 15;

interface DeliveriesResponse {
  data: any[];
  pagination: {
    page: number;
    per_page: number;
    total: number;
  };
}

const asText = (value: any): string => {
  if (value === null || value === undefined) return '';
  if (typeof value === 'string') return value;
  if (typeof value === 'number') return String(value);
  if (typeof value === 'object') {
    try {
      return String((value as any).name ?? (value as any).code ?? (value as any).id ?? '');
    } catch (_) {
      return '';
    }
  }
  try {
    return String(value);
  } catch (_) {
    return '';
  }
};

export default function SupplierDeliveriesPage({ params }: { params: { id: string } }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const supplierId = Number(params.id);
  const [page, setPage] = useState(1);

  const { suppliers } = useSupplierDirectory();
  
  // Try to find supplier in directory by ID first
  let directorySupplier = suppliers.find((s) => Number(s.id) === supplierId);
  
  // If not found by ID, try to find by name (for allocation finder cases)
  const fallbackName = searchParams.get('name');
  if (!directorySupplier && fallbackName) {
    const normalizedFallbackName = fallbackName.toUpperCase().replace(/\s+/g, ' ').trim();
    directorySupplier = suppliers.find(
      (s) => s.name?.toUpperCase().replace(/\s+/g, ' ').trim() === normalizedFallbackName
    );
  }

  const fallbackRegion = searchParams.get('region');
  const fallbackCode = searchParams.get('code');
  const fallbackPhone = searchParams.get('phone');
  const fallbackContact = searchParams.get('contact');
  const source = searchParams.get('source'); // Track if from allocation-finder

  const supplierName = directorySupplier?.name ?? fallbackName ?? `Supplier ${supplierId}`;
  const supplierRegion = directorySupplier?.region ?? fallbackRegion ?? '';
  const supplierCode = directorySupplier?.code ?? fallbackCode ?? '';
  const supplierPhone = directorySupplier?.phone ?? fallbackPhone ?? '';
  const contactPerson = fallbackContact ?? '';

  const { data, isLoading, isFetching, isError } = useQuery<DeliveriesResponse>({
    queryKey: ['supplier-deliveries', directorySupplier?.id ?? supplierId, page, PER_PAGE],
    enabled: !!(directorySupplier?.id ?? supplierId),
    placeholderData: keepPreviousData,
    staleTime: 10_000,
    queryFn: async () => {
      const response = await api.get('/deliveries', {
        params: {
          supplier_id: directorySupplier?.id ?? supplierId,
          page,
          per_page: PER_PAGE,
        },
      });
      return response.data;
    },
  });

  const deliveries = data?.data ?? [];
  const pagination = data?.pagination ?? { page, per_page: PER_PAGE, total: 0 };
  const totalPages = Math.max(1, Math.ceil((pagination.total ?? 0) / PER_PAGE));
  const currentPage = Math.min(page, totalPages);

  const totalQuantity = useMemo(() => {
    return deliveries.reduce((sum: number, d: any) => sum + (Number(d?.actual_quantity ?? 0) || 0), 0);
  }, [deliveries]);

  const handlePrev = () => setPage((prev) => Math.max(1, prev - 1));
  const handleNext = () => setPage((prev) => Math.min(totalPages, prev + 1));

  const renderDeliveryCard = (delivery: any) => {
    const school = asText(delivery.school_name) || 'School';
    const commodity = asText(delivery.commodity_name) || 'Commodity';
    const date = delivery.delivery_date ? new Date(delivery.delivery_date).toLocaleDateString() : 'Date';
    const quantity = smartRound(delivery.actual_quantity ?? 0);

    return (
      <Link
        key={delivery.id}
        href={`/field-staff/my-deliveries/${delivery.id}`}
        className="block rounded-2xl bg-white p-4 shadow-sm transition-all active:scale-[0.99]"
      >
        <div className="flex items-start gap-3">
          <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-100 to-cyan-100">
            <Package className="h-6 w-6 text-emerald-600" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center justify-between gap-2">
              <p className="truncate font-semibold text-slate-900">{school}</p>
              <span className="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-600">{date}</span>
            </div>
            <p className="text-sm text-slate-500">{commodity}</p>
            <div className="mt-2 inline-flex items-center gap-2 rounded-full bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-700">
              <span>{quantity}</span>
              <span className="text-[10px] font-medium uppercase text-emerald-600">units</span>
            </div>
            {delivery.notes && (
              <p className="mt-2 line-clamp-2 text-xs text-slate-500">{asText(delivery.notes)}</p>
            )}
          </div>
        </div>
      </Link>
    );
  };

  const headerSubtitle = [supplierRegion, supplierCode].filter(Boolean).join(' • ');

  return (
    <MobileLayout>
      <div className="min-h-screen bg-slate-50 pb-24">
        {/* 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" aria-label="Go back">
            <ArrowLeft className="h-5 w-5 text-slate-600" />
          </button>
          <div>
            <h1 className="text-lg font-bold text-slate-900">{supplierName}</h1>
            {headerSubtitle && <p className="text-xs text-slate-500">{headerSubtitle}</p>}
          </div>
          {supplierPhone && (
            <button
              onClick={() => (window.location.href = `tel:${supplierPhone}`)}
              className="ml-auto rounded-full bg-emerald-50 p-2 text-emerald-600 hover:bg-emerald-100"
              aria-label="Call supplier"
            >
              <Phone className="h-5 w-5" />
            </button>
          )}
        </div>

        {/* Supplier summary */}
        <div className="px-4 pt-4">
          <div className="overflow-hidden rounded-2xl bg-gradient-to-br from-emerald-500 via-teal-600 to-cyan-500 p-4 text-white shadow-lg">
            <p className="text-sm opacity-80">Supplier</p>
            <h2 className="text-2xl font-bold leading-tight">{supplierName}</h2>
            {contactPerson && contactPerson !== supplierName && (
              <p className="mt-1 text-sm text-white/90">Contact: {contactPerson}</p>
            )}
            {headerSubtitle && <p className="mt-1 text-sm text-white/80">{headerSubtitle}</p>}
            {supplierPhone && (
              <div className="mt-3 inline-flex items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-sm font-medium">
                <Phone className="h-4 w-4" />
                {supplierPhone}
              </div>
            )}
          </div>
        </div>

        {/* Stats */}
        <div className="mt-3 grid grid-cols-2 gap-2 px-4">
          <div className="rounded-2xl bg-white p-4 shadow-sm">
            <p className="text-xs text-slate-500">Deliveries</p>
            <p className="text-2xl font-bold text-slate-900">{pagination.total ?? deliveries.length}</p>
            {isFetching && <p className="text-[11px] text-emerald-600">Syncing…</p>}
          </div>
          <div className="rounded-2xl bg-white p-4 shadow-sm">
            <p className="text-xs text-slate-500">Total Quantity</p>
            <p className="text-2xl font-bold text-slate-900">{smartRound(totalQuantity)}</p>
            <p className="text-[11px] text-slate-400">units</p>
          </div>
        </div>

        {/* Deliveries list */}
        <div className="mt-4 space-y-3 px-4">
          {isLoading ? (
            <div className="flex flex-col items-center justify-center rounded-2xl border border-slate-200 bg-white p-8">
              <div className="h-8 w-8 animate-spin rounded-full border-4 border-emerald-200 border-t-emerald-600"></div>
              <p className="mt-3 text-sm text-slate-500">Loading deliveries…</p>
            </div>
          ) : isError ? (
            <div className="rounded-2xl border border-amber-200 bg-amber-50 p-6 text-center">
              <AlertCircle className="mx-auto h-10 w-10 text-amber-500" />
              <p className="mt-2 font-semibold text-amber-800">Could not load deliveries</p>
              <p className="text-sm text-amber-700">Please try again or check your connection.</p>
            </div>
          ) : deliveries.length === 0 ? (
            <div className="rounded-2xl border border-slate-200 bg-white p-6 text-center">
              <School className="mx-auto h-10 w-10 text-slate-300" />
              <p className="mt-2 font-semibold text-slate-800">No deliveries recorded for this supplier yet</p>
              <p className="text-sm text-slate-500">Record a delivery to see it here.</p>
            </div>
          ) : (
            deliveries.map(renderDeliveryCard)
          )}
        </div>

        {/* Pagination */}
        {deliveries.length > 0 && (
          <div className="mt-5 px-4 pb-8">
            <div className="flex items-center justify-between rounded-2xl border border-slate-200 bg-white px-4 py-3 shadow-sm">
              <div className="text-xs text-slate-500">Page {currentPage} of {totalPages}</div>
              <div className="flex items-center gap-2">
                <button
                  onClick={handlePrev}
                  disabled={currentPage <= 1}
                  className="rounded-lg border border-slate-200 px-3 py-2 text-xs font-medium text-slate-600 transition-colors disabled:cursor-not-allowed disabled:opacity-50 hover:bg-slate-50"
                >
                  Previous
                </button>
                <button
                  onClick={handleNext}
                  disabled={currentPage >= totalPages}
                  className="rounded-lg bg-emerald-500 px-3 py-2 text-xs font-medium text-white transition-colors disabled:cursor-not-allowed disabled:opacity-50 hover:bg-emerald-600"
                >
                  Next
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </MobileLayout>
  );
}
