'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 { ClipboardList, Play, ScanBarcode, CheckCircle2, FileCheck2, XCircle } from "lucide-react"
import { formatDateTime, formatNumber } from "@/lib/format"
import { useStockCounts, type StockCountSessionDTO } from "@/hooks/useStockCounts"
import { Modal } from "@/components/ui/modal"
import { InputField, SelectField } from "@/components/ui/FormFields"
import { toast } from "sonner"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import i18n from "@/lib/i18n";

const statusMap: Record<string, { label: string; tone: StatusTone }> = {
  scheduled: { label: i18n.t('app.admin.warehouse.stock-counts.page.text_1'), tone: "neutral" },
  in_progress: { label: i18n.t('app.admin.warehouse.stock-counts.page.text_2'), tone: "primary" },
  completed: { label: i18n.t('app.admin.warehouse.stock-counts.page.text_3'), tone: "info" },
  approved: { label: i18n.t('app.admin.warehouse.stock-counts.page.text_4'), tone: "success" },
  cancelled: { label: i18n.t('app.admin.warehouse.stock-counts.page.text_5'), tone: "danger" },
}

export default function StockCountsPage() {
  const { items: sessions, isLoading, fetchItems, startSession, completeSession, approveSession, cancelSession, recordItem, sessionItems, fetchSessionItems } = useStockCounts()
  
  const [selectedSession, setSelectedSession] = useState<StockCountSessionDTO | null>(null)
  
  // Modals state
  const [isStartModalOpen, setIsStartModalOpen] = useState(false)
  const [isRecordModalOpen, setIsRecordModalOpen] = useState(false)
  const [isCompleteModalOpen, setIsCompleteModalOpen] = useState(false)
  const [isApproveModalOpen, setIsApproveModalOpen] = useState(false)
  const [isCancelModalOpen, setIsCancelModalOpen] = useState(false)

  // Record item form state
  const [recordBarId, setRecordBarId] = useState("")
  const [recordSerial, setRecordSerial] = useState("")
  const [recordWeight, setRecordWeight] = useState<number | undefined>(undefined)
  const [recordStatus, setRecordStatus] = useState("found")
  const [recordNotes, setRecordNotes] = useState("")

  const [cancelReason, setCancelReason] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)

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

  const scheduledCount = sessions.filter(s => s.status === 'scheduled').length
  const inProgressCount = sessions.filter(s => s.status === 'in_progress').length
  const varianceCount = sessions.reduce((acc, s) => acc + (s.variance_bars > 0 ? 1 : 0), 0)

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

  const handleRecordItem = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedSession) return
    setIsSubmitting(true)
    const success = await recordItem(selectedSession.id, {
      bar_id: recordBarId || undefined,
      serial_number: recordSerial || undefined,
      actual_weight: recordWeight,
      status: recordStatus,
      notes: recordNotes
    })
    setIsSubmitting(false)
    if (success) {
      toast.success(i18n.t('app.admin.warehouse.stock-counts.page.text_6'))
      setRecordBarId("")
      setRecordSerial("")
      setRecordWeight(undefined)
      setRecordNotes("")
    }
  }

  const columns: Column<StockCountSessionDTO>[] = [
    {
      key: "session_number",
      header: i18n.t('app.admin.warehouse.stock-counts.page.text_7'),
      cell: (row) => <span className="font-mono text-sm font-medium">{row.session_number}</span>,
    },
    {
      key: "vault",
      header: i18n.t('app.admin.warehouse.stock-counts.page.text_8'),
      cell: (row) => <span className="text-sm">{row.vault_id.split('-')[0].toUpperCase()}</span>,
    },
    {
      key: "progress",
      header: i18n.t('app.admin.warehouse.stock-counts.page.text_9'),
      cell: (row) => <span className="text-sm">{row.counted_bars} / {row.expected_bars}</span>,
    },
    {
      key: "variance",
      header: i18n.t('app.admin.warehouse.stock-counts.page.text_10'),
      cell: (row) => <span className={`text-sm font-semibold ${row.variance_bars > 0 ? 'text-red-500' : 'text-emerald-500'}`}>{row.variance_bars} {i18n.t('app.admin.warehouse.stock-counts.page.text_38')}{formatNumber(row.variance_weight)} {i18n.t('app.admin.warehouse.stock-counts.page.text_39')}</span>,
    },
    {
      key: "status",
      header: i18n.t('app.admin.warehouse.stock-counts.page.text_11'),
      cell: (row) => {
        const s = statusMap[row.status] || { label: row.status, tone: "neutral" }
        return <StatusBadge tone={s.tone}>{s.label}</StatusBadge>
      },
    },
    {
      key: "scheduled_at",
      header: i18n.t('app.admin.warehouse.stock-counts.page.text_12'),
      cell: (row) => <span className="text-xs text-muted-foreground">{row.scheduled_at ? formatDateTime(row.scheduled_at) : '—'}</span>,
    },
    {
      key: "actions",
      header: i18n.t('app.admin.warehouse.stock-counts.page.text_13'),
      cell: (row) => (
        <div className="flex items-center gap-2">
          {row.status === 'scheduled' && (
            <button onClick={() => { setSelectedSession(row); setIsStartModalOpen(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">
              <Play className="w-3 h-3" /> {i18n.t('app.admin.warehouse.stock-counts.page.text_40')}</button>
          )}
          {row.status === 'in_progress' && (
            <>
              <button onClick={() => { setSelectedSession(row); fetchSessionItems(row.id); setIsRecordModalOpen(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">
                <ScanBarcode className="w-3 h-3" /> {i18n.t('app.admin.warehouse.stock-counts.page.text_41')}</button>
              <button onClick={() => { setSelectedSession(row); setIsCompleteModalOpen(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">
                <CheckCircle2 className="w-3 h-3" /> {i18n.t('app.admin.warehouse.stock-counts.page.text_42')}</button>
            </>
          )}
          {row.status === 'completed' && (
            <button onClick={() => { setSelectedSession(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">
              <FileCheck2 className="w-3 h-3" /> {i18n.t('app.admin.warehouse.stock-counts.page.text_43')}</button>
          )}
          {['scheduled', 'in_progress'].includes(row.status) && (
            <button onClick={() => { setSelectedSession(row); setCancelReason(""); 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.warehouse.stock-counts.page.text_14')}>
              <XCircle className="w-3 h-3" />
            </button>
          )}
        </div>
      )
    }
  ]

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

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard title={i18n.t('app.admin.warehouse.stock-counts.page.text_17')} value={sessions.length} icon={ClipboardList} tone="primary" />
        <KpiCard title={i18n.t('app.admin.warehouse.stock-counts.page.text_18')} value={scheduledCount} icon={ClipboardList} tone="neutral" />
        <KpiCard title={i18n.t('app.admin.warehouse.stock-counts.page.text_19')} value={inProgressCount} icon={Play} tone="warning" />
        <KpiCard title={i18n.t('app.admin.warehouse.stock-counts.page.text_20')} value={varianceCount} icon={XCircle} tone="danger" />
      </div>

      <SectionCard title={i18n.t('app.admin.warehouse.stock-counts.page.text_21')}>
        <DataTable columns={columns} data={sessions} rowKey={(row) => row.id} isLoading={isLoading} />
      </SectionCard>

      {/* Modals */}
      <Modal open={isStartModalOpen} onClose={() => setIsStartModalOpen(false)} title={i18n.t('app.admin.warehouse.stock-counts.page.text_22')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.stock-counts.page.text_44')}</p>
          <div className="flex justify-end gap-3 pt-4"><button onClick={() => setIsStartModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.stock-counts.page.text_45')}</button><button onClick={() => handleAction(() => startSession(selectedSession!.id), setIsStartModalOpen, i18n.t('app.admin.warehouse.stock-counts.page.text_23'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-primary text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.stock-counts.page.text_46')}</button></div>
        </div>
      </Modal>

      <Modal open={isRecordModalOpen} onClose={() => setIsRecordModalOpen(false)} title={i18n.t('app.admin.warehouse.stock-counts.page.text_record', { session_number: selectedSession?.session_number })} size="md">
        <div className="space-y-6">
          <div className="bg-muted p-4 rounded-lg flex justify-between items-center text-sm">
            <span>{i18n.t('app.admin.warehouse.stock-counts.page.text_47')}<strong>{selectedSession?.expected_bars}</strong></span>
            <span>{i18n.t('app.admin.warehouse.stock-counts.page.text_48')}<strong>{selectedSession?.counted_bars}</strong></span>
            <span className={selectedSession?.variance_bars ? 'text-red-500 font-bold' : ''}>{i18n.t('app.admin.warehouse.stock-counts.page.text_49')}<strong>{selectedSession?.variance_bars}</strong></span>
          </div>
          
          <form onSubmit={handleRecordItem} className="space-y-4 border p-4 rounded-lg bg-card">
            <h4 className="font-semibold text-sm mb-2">{i18n.t('app.admin.warehouse.stock-counts.page.text_50')}</h4>
            <div className="grid grid-cols-2 gap-4">
              <InputField id="r_bar_id" name="r_bar_id" label={i18n.t('app.admin.warehouse.stock-counts.page.text_24')} value={recordBarId} onChange={(e) => setRecordBarId(e.target.value)} />
              <InputField id="r_serial" name="r_serial" label={i18n.t('app.admin.warehouse.stock-counts.page.text_25')} value={recordSerial} onChange={(e) => setRecordSerial(e.target.value)} />
              <InputField id="r_weight" name="r_weight" label={i18n.t('app.admin.warehouse.stock-counts.page.text_26')} type="number" step="0.01" required value={recordWeight || ''} onChange={(e) => setRecordWeight(parseFloat(e.target.value))} />
              <SelectField id="r_status" name="r_status" label={i18n.t('app.admin.warehouse.stock-counts.page.text_27')} value={recordStatus} onChange={(e) => setRecordStatus(e.target.value)} options={[{value:'found', label:i18n.t('app.admin.warehouse.stock-counts.page.text_28')}, {value:'damaged', label:i18n.t('app.admin.warehouse.stock-counts.page.text_29')}]} />
            </div>
            <InputField id="r_notes" name="r_notes" label={i18n.t('app.admin.warehouse.stock-counts.page.text_30')} value={recordNotes} onChange={(e) => setRecordNotes(e.target.value)} />
            <div className="flex justify-end pt-2">
              <button type="submit" disabled={isSubmitting || (!recordBarId && !recordSerial) || !recordWeight} className="px-4 py-2 text-sm bg-primary text-white rounded-md disabled:opacity-50 flex items-center gap-2">
                <ScanBarcode className="w-4 h-4" /> {i18n.t('app.admin.warehouse.stock-counts.page.text_51')}</button>
            </div>
          </form>

          {/* List recently scanned items if needed, or a count */}
          <div className="text-xs text-muted-foreground text-center">
            {i18n.t('app.admin.warehouse.stock-counts.page.text_52')}{sessionItems.length} {i18n.t('app.admin.warehouse.stock-counts.page.text_53')}</div>
        </div>
      </Modal>

      <Modal open={isCompleteModalOpen} onClose={() => setIsCompleteModalOpen(false)} title={i18n.t('app.admin.warehouse.stock-counts.page.text_31')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.stock-counts.page.text_54')}</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.stock-counts.page.text_55')}</button><button onClick={() => handleAction(() => completeSession(selectedSession!.id), setIsCompleteModalOpen, i18n.t('app.admin.warehouse.stock-counts.page.text_32'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-info text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.stock-counts.page.text_56')}</button></div>
        </div>
      </Modal>

      <Modal open={isApproveModalOpen} onClose={() => setIsApproveModalOpen(false)} title={i18n.t('app.admin.warehouse.stock-counts.page.text_33')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.stock-counts.page.text_57')}</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.stock-counts.page.text_58')}</button><button onClick={() => handleAction(() => approveSession(selectedSession!.id), setIsApproveModalOpen, i18n.t('app.admin.warehouse.stock-counts.page.text_34'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-emerald-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.stock-counts.page.text_59')}</button></div>
        </div>
      </Modal>

      <Modal open={isCancelModalOpen} onClose={() => setIsCancelModalOpen(false)} title={i18n.t('app.admin.warehouse.stock-counts.page.text_35')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => cancelSession(selectedSession!.id, cancelReason), setIsCancelModalOpen, i18n.t('app.admin.warehouse.stock-counts.page.text_36')); }} className="space-y-4">
          <InputField id="cancel_reason" name="cancel_reason" label={i18n.t('app.admin.warehouse.stock-counts.page.text_37')} required value={cancelReason} onChange={(e) => setCancelReason(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.warehouse.stock-counts.page.text_60')}</button><button type="submit" disabled={isSubmitting || !cancelReason} className="px-4 py-2 text-sm bg-red-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.stock-counts.page.text_61')}</button></div>
        </form>
      </Modal>

    </div>
  )
}
