'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 { Receipt, Plus, Send, CheckCircle2, ShieldAlert, XCircle, Undo2 } from "lucide-react"
import { formatDateTime, formatNumber } from "@/lib/format"
import { usePayments, type PaymentDTO } from "@/hooks/usePayments"
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 }> = {
  draft: { label: i18n.t('app.admin.ledger.payments.page.text_1'), tone: "neutral" },
  pending_review: { label: i18n.t('app.admin.ledger.payments.page.text_2'), tone: "warning" },
  approved: { label: i18n.t('app.admin.ledger.payments.page.text_3'), tone: "info" },
  posted: { label: i18n.t('app.admin.ledger.payments.page.text_4'), tone: "success" },
  cancelled: { label: i18n.t('app.admin.ledger.payments.page.text_5'), tone: "danger" },
  reversed: { label: i18n.t('app.admin.ledger.payments.page.text_6'), tone: "danger" },
}

export default function PaymentsPage() {
  const { items: payments, isLoading, fetchItems, createItem, submitForReview, approvePayment, cancelPayment, postPayment, reversePayment } = usePayments()
  
  const [selectedPayment, setSelectedPayment] = useState<PaymentDTO | null>(null)
  
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
  const [isSubmitModalOpen, setIsSubmitModalOpen] = useState(false)
  const [isApproveModalOpen, setIsApproveModalOpen] = useState(false)
  const [isCancelModalOpen, setIsCancelModalOpen] = useState(false)
  const [isPostModalOpen, setIsPostModalOpen] = useState(false)
  const [isReverseModalOpen, setIsReverseModalOpen] = useState(false)

  // Form states
  const [paymentType, setPaymentType] = useState("payable")
  const [payerType, setPayerType] = useState("system")
  const [payeeType, setPayeeType] = useState("client")
  const [payeeId, setPayeeId] = useState("")
  const [amount, setAmount] = useState<number | undefined>(undefined)
  const [currency, setCurrency] = useState("SAR")
  const [paymentMethod, setPaymentMethod] = useState("bank_transfer")
  const [referenceNo, setReferenceNo] = useState("")
  const [description, setDescription] = useState("")

  const [actionNotes, setActionNotes] = useState("")
  const [actionReason, setActionReason] = useState("")
  
  const [isSubmitting, setIsSubmitting] = useState(false)

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

  const draftCount = payments.filter(p => p.status === 'draft').length
  const pendingCount = payments.filter(p => p.status === 'pending_review').length
  const approvedCount = payments.filter(p => p.status === 'approved').length
  const postedCount = payments.filter(p => p.status === 'posted').length

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

  const handleCreatePayment = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true)
    const success = await createItem({
      payment_type: paymentType,
      payer_type: payerType,
      payee_type: payeeType,
      payee_id: payeeId || undefined,
      amount: amount || 0,
      currency,
      payment_method: paymentMethod,
      reference_no: referenceNo || undefined,
      description: description || undefined
    })
    setIsSubmitting(false)
    if (success) {
      toast.success(i18n.t('app.admin.ledger.payments.page.text_7'))
      setIsCreateModalOpen(false)
      setPayeeId("")
      setAmount(undefined)
      setReferenceNo("")
      setDescription("")
    }
  }

  const columns: Column<PaymentDTO>[] = [
    {
      key: "payment_no",
      header: i18n.t('app.admin.ledger.payments.page.text_8'),
      cell: (row) => <span className="font-mono text-sm font-medium">{row.payment_no}</span>,
    },
    {
      key: "type",
      header: i18n.t('app.admin.ledger.payments.page.text_9'),
      cell: (row) => <span className="text-sm font-medium">{row.payment_type === 'payable' ? i18n.t('app.admin.ledger.payments.page.text_10') : i18n.t('app.admin.ledger.payments.page.text_11')}</span>,
    },
    {
      key: "amount",
      header: i18n.t('app.admin.ledger.payments.page.text_12'),
      cell: (row) => <span className="font-mono font-medium">{formatNumber(row.amount)} {row.currency}</span>,
    },
    {
      key: "method",
      header: i18n.t('app.admin.ledger.payments.page.text_13'),
      cell: (row) => <span className="text-sm text-muted-foreground capitalize">{row.payment_method.replace('_', ' ')}</span>,
    },
    {
      key: "status",
      header: i18n.t('app.admin.ledger.payments.page.text_14'),
      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.ledger.payments.page.text_15'),
      cell: (row) => <span className="text-xs text-muted-foreground">{formatDateTime(row.created_at)}</span>,
    },
    {
      key: "actions",
      header: i18n.t('app.admin.ledger.payments.page.text_16'),
      cell: (row) => (
        <div className="flex items-center gap-2">
          {row.status === 'draft' && (
            <>
              <button onClick={() => { setSelectedPayment(row); setIsSubmitModalOpen(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">
                <Send className="w-3 h-3" /> {i18n.t('app.admin.ledger.payments.page.text_57')}</button>
              <button onClick={() => { setSelectedPayment(row); setIsCancelModalOpen(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.ledger.payments.page.text_17')}>
                <XCircle className="w-3 h-3" />
              </button>
            </>
          )}
          {row.status === 'pending_review' && (
            <button onClick={() => { setSelectedPayment(row); setIsApproveModalOpen(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">
              <CheckCircle2 className="w-3 h-3" /> {i18n.t('app.admin.ledger.payments.page.text_58')}</button>
          )}
          {row.status === 'approved' && (
            <button onClick={() => { setSelectedPayment(row); setIsPostModalOpen(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">
              <ShieldAlert className="w-3 h-3" /> {i18n.t('app.admin.ledger.payments.page.text_59')}</button>
          )}
          {row.status === 'posted' && (
            <button onClick={() => { setSelectedPayment(row); setIsReverseModalOpen(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">
              <Undo2 className="w-3 h-3" /> {i18n.t('app.admin.ledger.payments.page.text_60')}</button>
          )}
        </div>
      )
    }
  ]

  return (
    <div className="flex flex-col gap-6">
      <div className="flex justify-between items-start">
        <PageHeader 
          title={i18n.t('app.admin.ledger.payments.page.text_18')} 
          description={i18n.t('app.admin.ledger.payments.page.text_19')}
        />
        <button onClick={() => setIsCreateModalOpen(true)} className="bg-primary text-white px-4 py-2 rounded-md text-sm font-medium flex items-center gap-2 hover:bg-primary/90 transition-colors">
          <Plus className="w-4 h-4" /> {i18n.t('app.admin.ledger.payments.page.text_61')}</button>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard title={i18n.t('app.admin.ledger.payments.page.text_20')} value={draftCount} icon={Receipt} tone="neutral" />
        <KpiCard title={i18n.t('app.admin.ledger.payments.page.text_21')} value={pendingCount} icon={Send} tone="warning" />
        <KpiCard title={i18n.t('app.admin.ledger.payments.page.text_22')} value={approvedCount} icon={CheckCircle2} tone="info" />
        <KpiCard title={i18n.t('app.admin.ledger.payments.page.text_23')} value={postedCount} icon={ShieldAlert} tone="success" />
      </div>

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

      {/* Modals */}
      <Modal open={isCreateModalOpen} onClose={() => setIsCreateModalOpen(false)} title={i18n.t('app.admin.ledger.payments.page.text_25')} size="md">
        <form onSubmit={handleCreatePayment} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <SelectField id="p_type" name="p_type" label={i18n.t('app.admin.ledger.payments.page.text_26')} value={paymentType} onChange={(e) => setPaymentType(e.target.value)} options={[{value:'payable', label:i18n.t('app.admin.ledger.payments.page.text_27')}, {value:'receivable', label:i18n.t('app.admin.ledger.payments.page.text_28')}]} />
            <SelectField id="payee_type" name="payee_type" label={i18n.t('app.admin.ledger.payments.page.text_29')} value={payeeType} onChange={(e) => setPayeeType(e.target.value)} options={[{value:'client', label:i18n.t('app.admin.ledger.payments.page.text_30')}, {value:'supplier', label:i18n.t('app.admin.ledger.payments.page.text_31')}, {value:'system', label:i18n.t('app.admin.ledger.payments.page.text_32')}]} />
            <InputField id="payee_id" name="payee_id" label={i18n.t('app.admin.ledger.payments.page.text_33')} value={payeeId} onChange={(e) => setPayeeId(e.target.value)} />
            <InputField id="amount" name="amount" label={i18n.t('app.admin.ledger.payments.page.text_34')} type="number" step="0.01" required value={amount || ''} onChange={(e) => setAmount(parseFloat(e.target.value))} />
            <SelectField id="currency" name="currency" label={i18n.t('app.admin.ledger.payments.page.text_35')} value={currency} onChange={(e) => setCurrency(e.target.value)} options={[{value:'SAR', label:'SAR'}, {value:'USD', label:'USD'}]} />
            <SelectField id="payment_method" name="payment_method" label={i18n.t('app.admin.ledger.payments.page.text_36')} value={paymentMethod} onChange={(e) => setPaymentMethod(e.target.value)} options={[{value:'bank_transfer', label:i18n.t('app.admin.ledger.payments.page.text_37')}, {value:'cash', label:i18n.t('app.admin.ledger.payments.page.text_38')}, {value:'cheque', label:i18n.t('app.admin.ledger.payments.page.text_39')}, {value:'card', label:i18n.t('app.admin.ledger.payments.page.text_40')}]} />
          </div>
          <InputField id="ref_no" name="ref_no" label={i18n.t('app.admin.ledger.payments.page.text_41')} value={referenceNo} onChange={(e) => setReferenceNo(e.target.value)} />
          <InputField id="desc" name="desc" label={i18n.t('app.admin.ledger.payments.page.text_42')} value={description} onChange={(e) => setDescription(e.target.value)} />
          
          <div className="flex justify-end gap-3 pt-4">
            <button type="button" onClick={() => setIsCreateModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.ledger.payments.page.text_62')}</button>
            <button type="submit" disabled={isSubmitting || !amount} className="px-4 py-2 text-sm bg-primary text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.ledger.payments.page.text_63')}</button>
          </div>
        </form>
      </Modal>

      <Modal open={isSubmitModalOpen} onClose={() => setIsSubmitModalOpen(false)} title={i18n.t('app.admin.ledger.payments.page.text_43')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => submitForReview(selectedPayment!.id, actionNotes), setIsSubmitModalOpen, i18n.t('app.admin.ledger.payments.page.text_44')); }} className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.ledger.payments.page.text_64')}</p>
          <InputField id="submit_notes" name="submit_notes" label={i18n.t('app.admin.ledger.payments.page.text_45')} value={actionNotes} onChange={(e) => setActionNotes(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsSubmitModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.ledger.payments.page.text_65')}</button><button type="submit" disabled={isSubmitting} className="px-4 py-2 text-sm bg-info text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.ledger.payments.page.text_66')}</button></div>
        </form>
      </Modal>

      <Modal open={isApproveModalOpen} onClose={() => setIsApproveModalOpen(false)} title={i18n.t('app.admin.ledger.payments.page.text_46')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => approvePayment(selectedPayment!.id, actionNotes), setIsApproveModalOpen, i18n.t('app.admin.ledger.payments.page.text_47')); }} className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.ledger.payments.page.text_67')}</p>
          <InputField id="approve_notes" name="approve_notes" label={i18n.t('app.admin.ledger.payments.page.text_48')} value={actionNotes} onChange={(e) => setActionNotes(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsApproveModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.ledger.payments.page.text_68')}</button><button type="submit" disabled={isSubmitting} className="px-4 py-2 text-sm bg-primary text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.ledger.payments.page.text_69')}</button></div>
        </form>
      </Modal>

      <Modal open={isPostModalOpen} onClose={() => setIsPostModalOpen(false)} title={i18n.t('app.admin.ledger.payments.page.text_49')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.ledger.payments.page.text_70')}{selectedPayment?.payment_no}{i18n.t('app.admin.ledger.payments.page.text_71')}</p>
          <div className="flex justify-end gap-3 pt-4"><button onClick={() => setIsPostModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.ledger.payments.page.text_72')}</button><button onClick={() => handleAction(() => postPayment(selectedPayment!.id), setIsPostModalOpen, i18n.t('app.admin.ledger.payments.page.text_50'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-emerald-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.ledger.payments.page.text_73')}</button></div>
        </div>
      </Modal>

      <Modal open={isCancelModalOpen} onClose={() => setIsCancelModalOpen(false)} title={i18n.t('app.admin.ledger.payments.page.text_51')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => cancelPayment(selectedPayment!.id, actionReason), setIsCancelModalOpen, i18n.t('app.admin.ledger.payments.page.text_52')); }} className="space-y-4">
          <InputField id="cancel_reason" name="cancel_reason" label={i18n.t('app.admin.ledger.payments.page.text_53')} required value={actionReason} onChange={(e) => setActionReason(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsCancelModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.ledger.payments.page.text_74')}</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.ledger.payments.page.text_75')}</button></div>
        </form>
      </Modal>

      <Modal open={isReverseModalOpen} onClose={() => setIsReverseModalOpen(false)} title={i18n.t('app.admin.ledger.payments.page.text_54')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => reversePayment(selectedPayment!.id, actionReason), setIsReverseModalOpen, i18n.t('app.admin.ledger.payments.page.text_55')); }} className="space-y-4">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.ledger.payments.page.text_76')}</p>
          <InputField id="reverse_reason" name="reverse_reason" label={i18n.t('app.admin.ledger.payments.page.text_56')} required value={actionReason} onChange={(e) => setActionReason(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsReverseModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.ledger.payments.page.text_77')}</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.ledger.payments.page.text_78')}</button></div>
        </form>
      </Modal>

    </div>
  )
}
