'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 { ArrowRightLeft, Clock, Truck, CheckCircle2, ShieldCheck, XCircle } from "lucide-react"
import { formatDateTime, formatNumber } from "@/lib/format"
import { useTransfers, type TransferOrderDTO } from "@/hooks/useTransfers"
import { Modal } from "@/components/ui/modal"
import { InputField } from "@/components/ui/FormFields"
import { toast } from "sonner"
import i18n from "@/lib/i18n";

const statusMap: Record<string, { label: string; tone: StatusTone }> = {
  draft: { label: i18n.t('app.admin.warehouse.transfers.page.text_1'), tone: "neutral" },
  pending_approval: { label: i18n.t('app.admin.warehouse.transfers.page.text_2'), tone: "warning" },
  approved: { label: i18n.t('app.admin.warehouse.transfers.page.text_3'), tone: "info" },
  in_transit: { label: i18n.t('app.admin.warehouse.transfers.page.text_4'), tone: "primary" },
  completed: { label: i18n.t('app.admin.warehouse.transfers.page.text_5'), tone: "success" },
  cancelled: { label: i18n.t('app.admin.warehouse.transfers.page.text_6'), tone: "danger" },
  rejected: { label: i18n.t('app.admin.warehouse.transfers.page.text_7'), tone: "danger" },
}

export default function TransfersPage() {
  const { items: transfers, isLoading, fetchItems, approveTransfer, rejectTransfer, dispatchTransfer, completeTransfer } = useTransfers()
  
  const [selectedTransfer, setSelectedTransfer] = useState<TransferOrderDTO | null>(null)
  const [isApproveModalOpen, setIsApproveModalOpen] = useState(false)
  const [isRejectModalOpen, setIsRejectModalOpen] = useState(false)
  const [isDispatchModalOpen, setIsDispatchModalOpen] = useState(false)
  const [isCompleteModalOpen, setIsCompleteModalOpen] = useState(false)
  const [actionReason, setActionReason] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)

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

  const pendingCount = transfers.filter(t => t.status === 'pending_approval').length
  const inTransitCount = transfers.filter(t => t.status === 'in_transit').length
  const completedCount = transfers.filter(t => t.status === 'completed').length

  const handleAction = async (actionFn: () => Promise<boolean>, modalSetter: (val: boolean) => void, successMsg: string) => {
    if (!selectedTransfer) return
    setIsSubmitting(true)
    const success = await actionFn()
    setIsSubmitting(false)
    if (success) {
      toast.success(successMsg)
      modalSetter(false)
      setSelectedTransfer(null)
      setActionReason("")
    }
  }

  const columns: Column<TransferOrderDTO>[] = [
    {
      key: "order_number",
      header: i18n.t('app.admin.warehouse.transfers.page.text_8'),
      cell: (row) => <span className="font-mono text-sm font-medium">{row.order_number}</span>,
    },
    {
      key: "from_vault",
      header: i18n.t('app.admin.warehouse.transfers.page.text_9'),
      cell: (row) => <span className="text-sm">{row.from_vault_name || '—'}</span>,
    },
    {
      key: "to_vault",
      header: i18n.t('app.admin.warehouse.transfers.page.text_10'),
      cell: (row) => <span className="text-sm">{row.to_vault_name || '—'}</span>,
    },
    {
      key: "total_bars",
      header: i18n.t('app.admin.warehouse.transfers.page.text_11'),
      cell: (row) => <span className="text-sm font-semibold">{row.total_bars}</span>,
    },
    {
      key: "total_weight",
      header: i18n.t('app.admin.warehouse.transfers.page.text_12'),
      cell: (row) => <span className="text-sm">{formatNumber(row.total_weight)} {i18n.t('app.admin.warehouse.transfers.page.text_36')}</span>,
    },
    {
      key: "status",
      header: i18n.t('app.admin.warehouse.transfers.page.text_13'),
      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.transfers.page.text_14'),
      cell: (row) => <span className="text-xs text-muted-foreground">{formatDateTime(row.created_at)}</span>,
    },
    {
      key: "actions",
      header: i18n.t('app.admin.warehouse.transfers.page.text_15'),
      cell: (row) => (
        <div className="flex items-center gap-2">
          {row.status === 'pending_approval' && (
            <>
              <button onClick={() => { setSelectedTransfer(row); setIsApproveModalOpen(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" title={i18n.t('app.admin.warehouse.transfers.page.text_16')}>
                <ShieldCheck className="w-3 h-3" /> {i18n.t('app.admin.warehouse.transfers.page.text_37')}</button>
              <button onClick={() => { setSelectedTransfer(row); setActionReason(""); setIsRejectModalOpen(true); }} className="text-xs px-2 py-1 bg-red-500/10 text-red-600 hover:bg-red-500/20 rounded transition-colors flex items-center gap-1" title={i18n.t('app.admin.warehouse.transfers.page.text_17')}>
                <XCircle className="w-3 h-3" /> {i18n.t('app.admin.warehouse.transfers.page.text_38')}</button>
            </>
          )}
          {row.status === 'approved' && (
            <button onClick={() => { setSelectedTransfer(row); setIsDispatchModalOpen(true); }} className="text-xs px-2 py-1 bg-blue-500/10 text-blue-600 hover:bg-blue-500/20 rounded transition-colors flex items-center gap-1" title={i18n.t('app.admin.warehouse.transfers.page.text_18')}>
              <Truck className="w-3 h-3" /> {i18n.t('app.admin.warehouse.transfers.page.text_39')}</button>
          )}
          {row.status === 'in_transit' && (
            <button onClick={() => { setSelectedTransfer(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" title={i18n.t('app.admin.warehouse.transfers.page.text_19')}>
              <CheckCircle2 className="w-3 h-3" /> {i18n.t('app.admin.warehouse.transfers.page.text_40')}</button>
          )}
        </div>
      )
    }
  ]

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

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard title={i18n.t('app.admin.warehouse.transfers.page.text_22')} value={transfers.length} icon={ArrowRightLeft} tone="primary" />
        <KpiCard title={i18n.t('app.admin.warehouse.transfers.page.text_23')} value={pendingCount} icon={Clock} tone="warning" />
        <KpiCard title={i18n.t('app.admin.warehouse.transfers.page.text_24')} value={inTransitCount} icon={Truck} tone="info" />
        <KpiCard title={i18n.t('app.admin.warehouse.transfers.page.text_25')} value={completedCount} icon={CheckCircle2} tone="success" />
      </div>

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

      <Modal open={isApproveModalOpen} onClose={() => setIsApproveModalOpen(false)} title={i18n.t('app.admin.warehouse.transfers.page.text_27')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.transfers.page.text_41')}<strong>{selectedTransfer?.order_number}</strong>{i18n.t('app.admin.warehouse.transfers.page.text_42')}</p>
          <div className="flex justify-end gap-3 pt-4"><button onClick={() => setIsApproveModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.transfers.page.text_43')}</button><button onClick={() => handleAction(() => approveTransfer(selectedTransfer!.id), setIsApproveModalOpen, i18n.t('app.admin.warehouse.transfers.page.text_28'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-emerald-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.transfers.page.text_44')}</button></div>
        </div>
      </Modal>

      <Modal open={isRejectModalOpen} onClose={() => setIsRejectModalOpen(false)} title={i18n.t('app.admin.warehouse.transfers.page.text_29')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => rejectTransfer(selectedTransfer!.id, actionReason), setIsRejectModalOpen, i18n.t('app.admin.warehouse.transfers.page.text_30')); }} className="space-y-4">
          <InputField id="reject_reason" name="reject_reason" label={i18n.t('app.admin.warehouse.transfers.page.text_31')} required value={actionReason} onChange={(e) => setActionReason(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsRejectModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.transfers.page.text_45')}</button><button type="submit" disabled={isSubmitting || !actionReason} className="px-4 py-2 text-sm bg-red-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.transfers.page.text_46')}</button></div>
        </form>
      </Modal>

      <Modal open={isDispatchModalOpen} onClose={() => setIsDispatchModalOpen(false)} title={i18n.t('app.admin.warehouse.transfers.page.text_32')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.transfers.page.text_47')}</p>
          <div className="flex justify-end gap-3 pt-4"><button onClick={() => setIsDispatchModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.transfers.page.text_48')}</button><button onClick={() => handleAction(() => dispatchTransfer(selectedTransfer!.id), setIsDispatchModalOpen, i18n.t('app.admin.warehouse.transfers.page.text_33'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-blue-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.transfers.page.text_49')}</button></div>
        </div>
      </Modal>

      <Modal open={isCompleteModalOpen} onClose={() => setIsCompleteModalOpen(false)} title={i18n.t('app.admin.warehouse.transfers.page.text_34')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.transfers.page.text_50')}</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.transfers.page.text_51')}</button><button onClick={() => handleAction(() => completeTransfer(selectedTransfer!.id), setIsCompleteModalOpen, i18n.t('app.admin.warehouse.transfers.page.text_35'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-emerald-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.transfers.page.text_52')}</button></div>
        </div>
      </Modal>

    </div>
  )
}
