import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { Modal } from '../../../../components/ui/modal';
import api from '../../../../lib/api-client';
import { DataTable, Column } from '../../../../components/ui/data-table';
import { smartRound } from '../../../../lib/utils';
import { Loader2, Package, Calendar, User, Clock, MapPin, Building2, Truck } from 'lucide-react';

interface PlanDetailsModalProps {
  isOpen: boolean;
  onClose: () => void;
  plan: any | null; // using any for flexibility, but ideally PlanRow
}

export function PlanDetailsModal({ isOpen, onClose, plan }: PlanDetailsModalProps) {
  const planId = plan?.id;

  const { data: deliveries, isLoading } = useQuery({
    queryKey: ['plan-deliveries', planId],
    queryFn: async () => {
      if (!planId) return [];
      // Fetch deliveries specific to this supply plan
      // Assuming the backend filters by supply_plan_id matching the plan row ID
      const response = await api.get('/deliveries', {
        params: {
          supply_plan_id: planId,
          per_page: 100 // Get all relevant ones
        }
      });
      return response.data?.data ?? [];
    },
    enabled: !!planId && isOpen,
  });

  const columns: Column<any>[] = [
    { 
      key: 'delivery_date', 
      label: 'Date', 
      render: (row) => (
        <div className="flex items-center gap-2 text-slate-700">
           <Calendar className="h-3.5 w-3.5 text-slate-400" />
           <span>{row.delivery_date}</span>
        </div>
      )
    },
    { 
      key: 'created_at', 
      label: 'Time Logged', 
      render: (row) => {
        if (!row.created_at) return '-';
        const time = new Date(row.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        return (
          <div className="flex items-center gap-2 text-slate-500">
            <Clock className="h-3.5 w-3.5" />
            <span className="text-xs">{time}</span>
          </div>
        );
      }
    },
    { 
      key: 'user_name', 
      label: 'Field Officer',
      render: (row) => (
        <div className="flex flex-col">
          <span className="font-medium text-slate-900">{row.user_name}</span>
          <span className="text-xs text-slate-500">{row.user_role ?? 'Staff'}</span>
        </div>
      )
    },
    { 
      key: 'supplier_name', 
      label: 'Supplier',
      render: (row) => (
        <div className="flex items-center gap-2">
           <Truck className="h-3.5 w-3.5 text-brand/60" />
           <span className="text-slate-700 truncate max-w-[150px]" title={row.supplier_name}>
             {row.supplier_name || 'Unknown'}
           </span>
        </div>
      )
    },
    { 
      key: 'actual_quantity', 
      label: 'Qty',
      className: 'text-right',
      render: (row) => <span className="font-bold text-slate-900">{smartRound(row.actual_quantity)}</span>
    },
    {
      key: 'status',
      label: 'Status',
      render: (row) => {
        const isOk = !row.is_flagged && row.review_status !== 'PENDING_REVIEW';
        return (
          <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ${
            isOk ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'
          }`}>
            {isOk ? 'Verified' : 'Review Needed'}
          </span>
        );
      }
    }
  ];

  if (!plan) return null;

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="Delivery History" size="xl">
      <div className="space-y-6">
        {/* Header Summary */}
        <div className="rounded-xl bg-slate-50 p-4 border border-slate-100">
          <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
            <div>
              <p className="text-xs font-semibold uppercase tracking-wider text-slate-500">School</p>
              <div className="mt-1 flex items-center gap-2">
                <Building2 className="h-4 w-4 text-slate-400" />
                <p className="font-medium text-slate-900">{plan.school_name}</p>
              </div>
            </div>
            <div>
              <p className="text-xs font-semibold uppercase tracking-wider text-slate-500">Commodity</p>
              <div className="mt-1 flex items-center gap-2">
                <Package className="h-4 w-4 text-slate-400" />
                <p className="font-medium text-slate-900">{plan.commodity_name}</p>
              </div>
            </div>
            <div>
               <p className="text-xs font-semibold uppercase tracking-wider text-slate-500">Progress</p>
               <div className="mt-1 flex items-baseline gap-2">
                 <span className="text-lg font-bold text-brand">{smartRound((plan.planned_quantity - (plan.remaining_quantity ?? plan.planned_quantity)))}</span>
                 <span className="text-sm text-slate-400">/ {smartRound(plan.planned_quantity)} delivered</span>
               </div>
            </div>
          </div>
        </div>

        {/* Deliveries Table */}
        <div className="min-h-[300px]">
          {isLoading ? (
            <div className="flex h-40 w-full items-center justify-center">
              <Loader2 className="h-8 w-8 animate-spin text-brand" />
            </div>
          ) : deliveries && deliveries.length > 0 ? (
            <div className="rounded-xl border border-slate-200 overflow-hidden">
               <DataTable 
                 columns={columns} 
                 data={deliveries} 
                 searchable={false}
                 pageSize={5}
               />
            </div>
          ) : (
             <div className="flex h-48 flex-col items-center justify-center rounded-xl border border-dashed border-slate-200 bg-slate-50/50">
               <Package className="h-10 w-10 text-slate-300 mb-2" />
               <p className="text-slate-500 font-medium">No deliveries recorded yet</p>
               <p className="text-xs text-slate-400">Wait for field staff to sync data</p>
             </div>
          )}
        </div>
      </div>
    </Modal>
  );
}
