'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 { Shield, CheckCircle2, LockOpen, XCircle, FileKey, ArrowRightLeft } from "lucide-react"
import { formatDateTime, formatNumber } from "@/lib/format"
import { useCustody, type CustodyDTO } from "@/hooks/useCustody"
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 }> = {
  pending_confirmation: { label: i18n.t('app.admin.warehouse.custody.page.text_1'), tone: "warning" },
  active: { label: i18n.t('app.admin.warehouse.custody.page.text_2'), tone: "success" },
  released: { label: i18n.t('app.admin.warehouse.custody.page.text_3'), tone: "neutral" },
  transferred: { label: i18n.t('app.admin.warehouse.custody.page.text_4'), tone: "info" },
  revoked: { label: i18n.t('app.admin.warehouse.custody.page.text_5'), tone: "danger" },
}

export default function CustodyPage() {
  const { items: custodyRecords, isLoading, fetchItems, confirmCustody, releaseCustody, transferCustody, revokeCustody } = useCustody()
  
  const [selectedCustody, setSelectedCustody] = useState<CustodyDTO | null>(null)
  const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false)
  const [isReleaseModalOpen, setIsReleaseModalOpen] = useState(false)
  const [isTransferModalOpen, setIsTransferModalOpen] = useState(false)
  const [isRevokeModalOpen, setIsRevokeModalOpen] = useState(false)
  const [actionReason, setActionReason] = useState("")
  const [actionNotes, setActionNotes] = useState("")
  const [newVaultId, setNewVaultId] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)

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

  const pendingCount = custodyRecords.filter(c => c.status === 'pending_confirmation').length
  const activeCount = custodyRecords.filter(c => c.status === 'active').length
  const releasedCount = custodyRecords.filter(c => c.status === 'released').length

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

  const columns: Column<CustodyDTO>[] = [
    {
      key: "id",
      header: i18n.t('app.admin.warehouse.custody.page.text_6'),
      cell: (row) => <span className="font-mono text-xs text-muted-foreground">{row.id.split('-')[0].toUpperCase()}</span>,
    },
    {
      key: "client",
      header: i18n.t('app.admin.warehouse.custody.page.text_7'),
      cell: (row) => <span className="text-sm font-medium">{row.client_user_id.split('-')[0].toUpperCase()}</span>,
    },
    {
      key: "bar_id",
      header: i18n.t('app.admin.warehouse.custody.page.text_8'),
      cell: (row) => <span className="font-mono text-xs">{row.bar_id.split('-')[0].toUpperCase()}</span>,
    },
    {
      key: "custody_grams",
      header: i18n.t('app.admin.warehouse.custody.page.text_9'),
      cell: (row) => <span className="text-sm font-semibold">{formatNumber(row.custody_grams)} {i18n.t('app.admin.warehouse.custody.page.text_39')}</span>,
    },
    {
      key: "status",
      header: i18n.t('app.admin.warehouse.custody.page.text_10'),
      cell: (row) => {
        const s = statusMap[row.status] || { label: row.status, tone: "neutral" }
        return <StatusBadge tone={s.tone}>{s.label}</StatusBadge>
      },
    },
    {
      key: "custody_start",
      header: i18n.t('app.admin.warehouse.custody.page.text_11'),
      cell: (row) => <span className="text-xs text-muted-foreground">{formatDateTime(row.custody_start)}</span>,
    },
    {
      key: "actions",
      header: i18n.t('app.admin.warehouse.custody.page.text_12'),
      cell: (row) => (
        <div className="flex items-center gap-2">
          {row.status === 'pending_confirmation' && (
            <>
              <button onClick={() => { setSelectedCustody(row); setActionNotes(""); setIsConfirmModalOpen(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.custody.page.text_13')}>
                <CheckCircle2 className="w-3 h-3" /> {i18n.t('app.admin.warehouse.custody.page.text_40')}</button>
              <button onClick={() => { setSelectedCustody(row); setActionReason(""); setIsRevokeModalOpen(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.custody.page.text_14')}>
                <XCircle className="w-3 h-3" /> {i18n.t('app.admin.warehouse.custody.page.text_41')}</button>
            </>
          )}
          {row.status === 'active' && (
            <>
              <button onClick={() => { setSelectedCustody(row); setActionReason(""); setActionNotes(""); setIsReleaseModalOpen(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" title={i18n.t('app.admin.warehouse.custody.page.text_15')}>
                <LockOpen className="w-3 h-3" /> {i18n.t('app.admin.warehouse.custody.page.text_42')}</button>
              <button onClick={() => { setSelectedCustody(row); setActionReason(""); setActionNotes(""); setNewVaultId(""); setIsTransferModalOpen(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.custody.page.text_16')}>
                <ArrowRightLeft className="w-3 h-3" /> {i18n.t('app.admin.warehouse.custody.page.text_43')}</button>
            </>
          )}
        </div>
      )
    }
  ]

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

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard title={i18n.t('app.admin.warehouse.custody.page.text_19')} value={custodyRecords.length} icon={FileKey} tone="primary" />
        <KpiCard title={i18n.t('app.admin.warehouse.custody.page.text_20')} value={activeCount} icon={Shield} tone="success" />
        <KpiCard title={i18n.t('app.admin.warehouse.custody.page.text_21')} value={pendingCount} icon={CheckCircle2} tone="warning" />
        <KpiCard title={i18n.t('app.admin.warehouse.custody.page.text_22')} value={releasedCount} icon={LockOpen} tone="neutral" />
      </div>

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

      <Modal open={isConfirmModalOpen} onClose={() => setIsConfirmModalOpen(false)} title={i18n.t('app.admin.warehouse.custody.page.text_24')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => confirmCustody(selectedCustody!.id, actionNotes), setIsConfirmModalOpen, i18n.t('app.admin.warehouse.custody.page.text_25')); }} className="space-y-4">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.custody.page.text_44')}</p>
          <InputField id="confirm_notes" name="confirm_notes" label={i18n.t('app.admin.warehouse.custody.page.text_26')} value={actionNotes} onChange={(e) => setActionNotes(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsConfirmModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.custody.page.text_45')}</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.custody.page.text_46')}</button></div>
        </form>
      </Modal>

      <Modal open={isReleaseModalOpen} onClose={() => setIsReleaseModalOpen(false)} title={i18n.t('app.admin.warehouse.custody.page.text_27')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => releaseCustody(selectedCustody!.id, actionReason, actionNotes), setIsReleaseModalOpen, i18n.t('app.admin.warehouse.custody.page.text_28')); }} className="space-y-4">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.custody.page.text_47')}</p>
          <InputField id="release_reason" name="release_reason" label={i18n.t('app.admin.warehouse.custody.page.text_29')} required value={actionReason} onChange={(e) => setActionReason(e.target.value)} />
          <InputField id="release_notes" name="release_notes" label={i18n.t('app.admin.warehouse.custody.page.text_30')} value={actionNotes} onChange={(e) => setActionNotes(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsReleaseModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.custody.page.text_48')}</button><button type="submit" disabled={isSubmitting || !actionReason} className="px-4 py-2 text-sm bg-amber-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.custody.page.text_49')}</button></div>
        </form>
      </Modal>

      <Modal open={isTransferModalOpen} onClose={() => setIsTransferModalOpen(false)} title={i18n.t('app.admin.warehouse.custody.page.text_31')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => transferCustody(selectedCustody!.id, newVaultId, actionReason, actionNotes), setIsTransferModalOpen, i18n.t('app.admin.warehouse.custody.page.text_32')); }} className="space-y-4">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.custody.page.text_50')}</p>
          <InputField id="new_vault_id" name="new_vault_id" label={i18n.t('app.admin.warehouse.custody.page.text_33')} required value={newVaultId} onChange={(e) => setNewVaultId(e.target.value)} />
          <InputField id="transfer_reason" name="transfer_reason" label={i18n.t('app.admin.warehouse.custody.page.text_34')} value={actionReason} onChange={(e) => setActionReason(e.target.value)} />
          <InputField id="transfer_notes" name="transfer_notes" label={i18n.t('app.admin.warehouse.custody.page.text_35')} value={actionNotes} onChange={(e) => setActionNotes(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsTransferModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.custody.page.text_51')}</button><button type="submit" disabled={isSubmitting || !newVaultId} className="px-4 py-2 text-sm bg-blue-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.custody.page.text_52')}</button></div>
        </form>
      </Modal>

      <Modal open={isRevokeModalOpen} onClose={() => setIsRevokeModalOpen(false)} title={i18n.t('app.admin.warehouse.custody.page.text_36')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => revokeCustody(selectedCustody!.id, actionReason), setIsRevokeModalOpen, i18n.t('app.admin.warehouse.custody.page.text_37')); }} className="space-y-4">
          <InputField id="revoke_reason" name="revoke_reason" label={i18n.t('app.admin.warehouse.custody.page.text_38')} required value={actionReason} onChange={(e) => setActionReason(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsRevokeModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.custody.page.text_53')}</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.custody.page.text_54')}</button></div>
        </form>
      </Modal>

    </div>
  )
}
