'use client'

import { useEffect, useState } from "react"
import { PageHeader } from "@/components/ui/page-header"
import { KpiCard } from "@/components/ui/kpi-card"
import { SectionCard } from "@/components/ui/section-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { PackageSearch, FileCheck2, Fingerprint, ShieldCheck, CheckCircle2, PackageCheck, PenLine } from "lucide-react"
import { formatDateTime, formatNumber } from "@/lib/format"
import { useDeliveries, type DeliveryOrderDTO } from "@/hooks/useDeliveries"
import { Modal } from "@/components/ui/modal"
import { InputField, SelectField } from "@/components/ui/FormFields"
import { toast } from "sonner"
import i18n from "@/lib/i18n";

const statusMap: Record<string, { label: string; tone: StatusTone }> = {
  pending: { label: i18n.t('app.admin.warehouse.deliveries.page.text_1'), tone: "warning" },
  prepared: { label: i18n.t('app.admin.warehouse.deliveries.page.text_2'), tone: "primary" },
  ready_for_pickup: { label: i18n.t('app.admin.warehouse.deliveries.page.text_3'), tone: "info" },
  otp_verified: { label: i18n.t('app.admin.warehouse.deliveries.page.text_4'), tone: "success" },
  handed_over: { label: i18n.t('app.admin.warehouse.deliveries.page.text_5'), tone: "success" },
  completed: { label: i18n.t('app.admin.warehouse.deliveries.page.text_6'), tone: "neutral" },
  cancelled: { label: i18n.t('app.admin.warehouse.deliveries.page.text_7'), tone: "danger" },
  failed: { label: i18n.t('app.admin.warehouse.deliveries.page.text_8'), tone: "danger" },
}

export default function DeliveriesPage() {
  const { items: deliveries, isLoading, fetchItems, prepareDelivery, readyForPickup, verifyIdentity, verifyOtp, handOver, completeDelivery, addProtocolSignature, fetchSignatures } = useDeliveries()
  
  const [selectedDelivery, setSelectedDelivery] = useState<DeliveryOrderDTO | null>(null)
  
  // Modals state
  const [isPrepareModalOpen, setIsPrepareModalOpen] = useState(false)
  const [isReadyModalOpen, setIsReadyModalOpen] = useState(false)
  const [isIdentityModalOpen, setIsIdentityModalOpen] = useState(false)
  const [isOtpModalOpen, setIsOtpModalOpen] = useState(false)
  const [isHandoverModalOpen, setIsHandoverModalOpen] = useState(false)
  const [isCompleteModalOpen, setIsCompleteModalOpen] = useState(false)
  const [isSignaturesModalOpen, setIsSignaturesModalOpen] = useState(false)

  // Form states
  const [actionNotes, setActionNotes] = useState("")
  const [docType, setDocType] = useState("national_id")
  const [docNumber, setDocNumber] = useState("")
  const [otpCode, setOtpCode] = useState("")
  const [signatoryRole, setSignatoryRole] = useState("client")
  const [signatoryName, setSignatoryName] = useState("")
  const [signaturesList, setSignaturesList] = useState<any[]>([])
  const [isSignaturesLoading, setIsSignaturesLoading] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)

  useEffect(() => {
    fetchItems()
  }, [fetchItems])

  const pendingCount = deliveries.filter(d => d.status === 'pending').length
  const readyCount = deliveries.filter(d => d.status === 'ready_for_pickup').length
  const handedOverCount = deliveries.filter(d => d.status === 'handed_over' || d.status === 'completed').length

  const handleAction = async (actionFn: () => Promise<boolean>, modalSetter: (val: boolean) => void, successMsg: string) => {
    if (!selectedDelivery) return
    setIsSubmitting(true)
    const success = await actionFn()
    setIsSubmitting(false)
    if (success) {
      toast.success(successMsg)
      modalSetter(false)
      setSelectedDelivery(null)
      // reset forms
      setActionNotes("")
      setDocNumber("")
      setOtpCode("")
      setSignatoryName("")
    }
  }

  const loadSignatures = async (orderId: string) => {
    setIsSignaturesLoading(true)
    const data = await fetchSignatures(orderId)
    setSignaturesList(data)
    setIsSignaturesLoading(false)
  }

  const columns: Column<DeliveryOrderDTO>[] = [
    {
      key: "order_number",
      header: i18n.t('app.admin.warehouse.deliveries.page.text_9'),
      cell: (row) => <span className="font-mono text-sm font-medium">{row.order_number}</span>,
    },
    {
      key: "client",
      header: i18n.t('app.admin.warehouse.deliveries.page.text_10'),
      cell: (row) => <span className="text-sm">{row.client_name || row.client_user_id.split('-')[0]}</span>,
    },
    {
      key: "grams",
      header: i18n.t('app.admin.warehouse.deliveries.page.text_11'),
      cell: (row) => <span className="text-sm font-semibold">{formatNumber(row.grams)} {i18n.t('app.admin.warehouse.deliveries.page.text_52')}</span>,
    },
    {
      key: "status",
      header: i18n.t('app.admin.warehouse.deliveries.page.text_12'),
      cell: (row) => {
        const s = statusMap[row.status] || { label: row.status, tone: "neutral" }
        return <StatusBadge tone={s.tone}>{s.label}</StatusBadge>
      },
    },
    {
      key: "created_at",
      header: i18n.t('app.admin.warehouse.deliveries.page.text_13'),
      cell: (row) => <span className="text-xs text-muted-foreground">{formatDateTime(row.created_at)}</span>,
    },
    {
      key: "actions",
      header: i18n.t('app.admin.warehouse.deliveries.page.text_14'),
      cell: (row) => (
        <div className="flex items-center gap-2">
          {row.status === 'pending' && (
            <button onClick={() => { setSelectedDelivery(row); setIsPrepareModalOpen(true); }} className="text-xs px-2 py-1 bg-primary/10 text-primary hover:bg-primary/20 rounded transition-colors flex items-center gap-1">
              <PackageSearch className="w-3 h-3" /> {i18n.t('app.admin.warehouse.deliveries.page.text_53')}</button>
          )}
          {row.status === 'prepared' && (
            <button onClick={() => { setSelectedDelivery(row); setIsReadyModalOpen(true); }} className="text-xs px-2 py-1 bg-info/10 text-info hover:bg-info/20 rounded transition-colors flex items-center gap-1">
              <PackageCheck className="w-3 h-3" /> {i18n.t('app.admin.warehouse.deliveries.page.text_54')}</button>
          )}
          {row.status === 'ready_for_pickup' && !row.identity_verified_at && (
            <button onClick={() => { setSelectedDelivery(row); setIsIdentityModalOpen(true); }} className="text-xs px-2 py-1 bg-amber-500/10 text-amber-600 hover:bg-amber-500/20 rounded transition-colors flex items-center gap-1">
              <Fingerprint className="w-3 h-3" /> {i18n.t('app.admin.warehouse.deliveries.page.text_55')}</button>
          )}
          {row.status === 'ready_for_pickup' && row.identity_verified_at && !row.otp_verified_at && (
            <button onClick={() => { setSelectedDelivery(row); setIsOtpModalOpen(true); }} className="text-xs px-2 py-1 bg-indigo-500/10 text-indigo-600 hover:bg-indigo-500/20 rounded transition-colors flex items-center gap-1">
              <ShieldCheck className="w-3 h-3" /> OTP
            </button>
          )}
          {row.status === 'otp_verified' && (
            <button onClick={() => { setSelectedDelivery(row); setIsHandoverModalOpen(true); }} className="text-xs px-2 py-1 bg-emerald-500/10 text-emerald-600 hover:bg-emerald-500/20 rounded transition-colors flex items-center gap-1">
              <FileCheck2 className="w-3 h-3" /> {i18n.t('app.admin.warehouse.deliveries.page.text_56')}</button>
          )}
          {row.status === 'handed_over' && (
            <>
              <button onClick={() => { setSelectedDelivery(row); setIsCompleteModalOpen(true); }} className="text-xs px-2 py-1 bg-emerald-500/10 text-emerald-600 hover:bg-emerald-500/20 rounded transition-colors flex items-center gap-1">
                <CheckCircle2 className="w-3 h-3" /> {i18n.t('app.admin.warehouse.deliveries.page.text_57')}</button>
            </>
          )}
          {['ready_for_pickup', 'otp_verified', 'handed_over', 'completed'].includes(row.status) && (
            <button onClick={() => { setSelectedDelivery(row); loadSignatures(row.id); setIsSignaturesModalOpen(true); }} className="text-xs px-2 py-1 bg-gray-500/10 text-gray-600 hover:bg-gray-500/20 rounded transition-colors flex items-center gap-1" title={i18n.t('app.admin.warehouse.deliveries.page.text_15')}>
              <PenLine className="w-3 h-3" /> {i18n.t('app.admin.warehouse.deliveries.page.text_58')}</button>
          )}
        </div>
      )
    }
  ]

  return (
    <div className="flex flex-col gap-6">
      <PageHeader 
        title={i18n.t('app.admin.warehouse.deliveries.page.text_16')} 
        description={i18n.t('app.admin.warehouse.deliveries.page.text_17')}
      />

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard title={i18n.t('app.admin.warehouse.deliveries.page.text_18')} value={deliveries.length} icon={PackageSearch} tone="primary" />
        <KpiCard title={i18n.t('app.admin.warehouse.deliveries.page.text_19')} value={pendingCount} icon={PackageSearch} tone="warning" />
        <KpiCard title={i18n.t('app.admin.warehouse.deliveries.page.text_20')} value={readyCount} icon={PackageCheck} tone="info" />
        <KpiCard title={i18n.t('app.admin.warehouse.deliveries.page.text_21')} value={handedOverCount} icon={CheckCircle2} tone="success" />
      </div>

      <SectionCard title={i18n.t('app.admin.warehouse.deliveries.page.text_22')}>
        <DataTable columns={columns} data={deliveries} rowKey={(row) => row.id} isLoading={isLoading} />
      </SectionCard>

      {/* Modals */}
      <Modal open={isPrepareModalOpen} onClose={() => setIsPrepareModalOpen(false)} title={i18n.t('app.admin.warehouse.deliveries.page.text_23')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.deliveries.page.text_59')}</p>
          <InputField id="prep_notes" name="prep_notes" label={i18n.t('app.admin.warehouse.deliveries.page.text_24')} value={actionNotes} onChange={(e) => setActionNotes(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button onClick={() => setIsPrepareModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.deliveries.page.text_60')}</button><button onClick={() => handleAction(() => prepareDelivery(selectedDelivery!.id, actionNotes), setIsPrepareModalOpen, i18n.t('app.admin.warehouse.deliveries.page.text_25'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-primary text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.deliveries.page.text_61')}</button></div>
        </div>
      </Modal>

      <Modal open={isReadyModalOpen} onClose={() => setIsReadyModalOpen(false)} title={i18n.t('app.admin.warehouse.deliveries.page.text_26')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.deliveries.page.text_62')}</p>
          <div className="flex justify-end gap-3 pt-4"><button onClick={() => setIsReadyModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.deliveries.page.text_63')}</button><button onClick={() => handleAction(() => readyForPickup(selectedDelivery!.id), setIsReadyModalOpen, i18n.t('app.admin.warehouse.deliveries.page.text_27'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-info text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.deliveries.page.text_64')}</button></div>
        </div>
      </Modal>

      <Modal open={isIdentityModalOpen} onClose={() => setIsIdentityModalOpen(false)} title={i18n.t('app.admin.warehouse.deliveries.page.text_28')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => verifyIdentity(selectedDelivery!.id, docType, docNumber, actionNotes), setIsIdentityModalOpen, i18n.t('app.admin.warehouse.deliveries.page.text_29')); }} className="space-y-4">
          <SelectField id="docType" name="docType" label={i18n.t('app.admin.warehouse.deliveries.page.text_30')} value={docType} onChange={(e) => setDocType(e.target.value)} options={[{value: 'national_id', label: i18n.t('app.admin.warehouse.deliveries.page.text_31')}, {value: 'iqama', label: i18n.t('app.admin.warehouse.deliveries.page.text_32')}, {value: 'passport', label: i18n.t('app.admin.warehouse.deliveries.page.text_33')}]} />
          <InputField id="docNum" name="docNum" label={i18n.t('app.admin.warehouse.deliveries.page.text_34')} required value={docNumber} onChange={(e) => setDocNumber(e.target.value)} />
          <InputField id="id_notes" name="id_notes" label={i18n.t('app.admin.warehouse.deliveries.page.text_35')} value={actionNotes} onChange={(e) => setActionNotes(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsIdentityModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.deliveries.page.text_65')}</button><button type="submit" disabled={isSubmitting || !docNumber} className="px-4 py-2 text-sm bg-amber-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.deliveries.page.text_66')}</button></div>
        </form>
      </Modal>

      <Modal open={isOtpModalOpen} onClose={() => setIsOtpModalOpen(false)} title={i18n.t('app.admin.warehouse.deliveries.page.text_36')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => verifyOtp(selectedDelivery!.id, otpCode), setIsOtpModalOpen, i18n.t('app.admin.warehouse.deliveries.page.text_37')); }} className="space-y-4">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.deliveries.page.text_67')}</p>
          <InputField id="otp_code" name="otp_code" label={i18n.t('app.admin.warehouse.deliveries.page.text_38')} required value={otpCode} onChange={(e) => setOtpCode(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsOtpModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.deliveries.page.text_68')}</button><button type="submit" disabled={isSubmitting || !otpCode} className="px-4 py-2 text-sm bg-indigo-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.deliveries.page.text_69')}</button></div>
        </form>
      </Modal>

      <Modal open={isHandoverModalOpen} onClose={() => setIsHandoverModalOpen(false)} title={i18n.t('app.admin.warehouse.deliveries.page.text_39')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => handOver(selectedDelivery!.id, actionNotes), setIsHandoverModalOpen, i18n.t('app.admin.warehouse.deliveries.page.text_40')); }} className="space-y-4">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.deliveries.page.text_70')}</p>
          <InputField id="ho_notes" name="ho_notes" label={i18n.t('app.admin.warehouse.deliveries.page.text_41')} value={actionNotes} onChange={(e) => setActionNotes(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsHandoverModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.deliveries.page.text_71')}</button><button type="submit" disabled={isSubmitting} className="px-4 py-2 text-sm bg-emerald-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.deliveries.page.text_72')}</button></div>
        </form>
      </Modal>

      <Modal open={isCompleteModalOpen} onClose={() => setIsCompleteModalOpen(false)} title={i18n.t('app.admin.warehouse.deliveries.page.text_42')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.deliveries.page.text_73')}</p>
          <div className="flex justify-end gap-3 pt-4"><button onClick={() => setIsCompleteModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.deliveries.page.text_74')}</button><button onClick={() => handleAction(() => completeDelivery(selectedDelivery!.id, actionNotes), setIsCompleteModalOpen, i18n.t('app.admin.warehouse.deliveries.page.text_43'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-emerald-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.deliveries.page.text_75')}</button></div>
        </div>
      </Modal>

      <Modal open={isSignaturesModalOpen} onClose={() => setIsSignaturesModalOpen(false)} title={i18n.t('app.admin.warehouse.deliveries.page.text_44')} size="md">
        <div className="space-y-6 pt-2">
          {/* List existing signatures */}
          <div>
            <h4 className="text-sm font-semibold mb-3">{i18n.t('app.admin.warehouse.deliveries.page.text_76')}</h4>
            {isSignaturesLoading ? (
              <div className="flex justify-center items-center py-4">
                <div className="animate-spin w-5 h-5 border-2 border-primary border-t-transparent rounded-full" />
              </div>
            ) : signaturesList.length === 0 ? (
              <div className="text-center py-4 text-xs text-muted-foreground">{i18n.t('app.admin.warehouse.deliveries.page.text_77')}</div>
            ) : (
              <div className="space-y-2">
                {signaturesList.map((sig: any) => (
                  <div key={sig.id} className="flex justify-between items-center p-3 rounded-lg border border-border bg-muted/30">
                    <div>
                      <div className="text-sm font-medium">{sig.signatory_name}</div>
                      <div className="text-xs text-muted-foreground">{sig.signatory_role === 'client' ? i18n.t('app.admin.warehouse.deliveries.page.text_45') : sig.signatory_role === 'employee' ? i18n.t('app.admin.warehouse.deliveries.page.text_46') : sig.signatory_role}</div>
                    </div>
                    <div className="text-xs text-muted-foreground">{formatDateTime(sig.signed_at)}</div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Add new signature form */}
          {selectedDelivery && !['completed', 'cancelled', 'failed'].includes(selectedDelivery.status) && (
            <div className="pt-4 border-t border-border">
              <h4 className="text-sm font-semibold mb-3">{i18n.t('app.admin.warehouse.deliveries.page.text_78')}</h4>
              <form onSubmit={async (e) => { 
                e.preventDefault();
                setIsSubmitting(true);
                const success = await addProtocolSignature(selectedDelivery!.id, signatoryRole, signatoryName);
                setIsSubmitting(false);
                if (success) {
                  toast.success(i18n.t('app.admin.warehouse.deliveries.page.text_47'));
                  setSignatoryName("");
                  loadSignatures(selectedDelivery!.id);
                }
              }} className="space-y-4">
                <SelectField id="sig_role" name="sig_role" label={i18n.t('app.admin.warehouse.deliveries.page.text_48')} value={signatoryRole} onChange={(e) => setSignatoryRole(e.target.value)} options={[{value: 'client', label: i18n.t('app.admin.warehouse.deliveries.page.text_49')}, {value: 'employee', label: i18n.t('app.admin.warehouse.deliveries.page.text_50')}]} />
                <InputField id="sig_name" name="sig_name" label={i18n.t('app.admin.warehouse.deliveries.page.text_51')} required value={signatoryName} onChange={(e) => setSignatoryName(e.target.value)} />
                <div className="flex justify-end gap-3 pt-2">
                  <button type="submit" disabled={isSubmitting || !signatoryName} className="px-4 py-2 text-sm bg-primary text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.deliveries.page.text_79')}</button>
                </div>
              </form>
            </div>
          )}
        </div>
      </Modal>

    </div>
  )
}
