'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 { AlertTriangle, AlertOctagon, Search, CheckCircle2, ShieldAlert, Plus, Scale } from "lucide-react"
import { formatDateTime } from "@/lib/format"
import { useIncidents, type IncidentDTO } from "@/hooks/useIncidents"
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 }> = {
  open: { label: i18n.t('app.admin.warehouse.incidents.page.text_1'), tone: "warning" },
  investigating: { label: i18n.t('app.admin.warehouse.incidents.page.text_2'), tone: "info" },
  resolved: { label: i18n.t('app.admin.warehouse.incidents.page.text_3'), tone: "primary" },
  closed: { label: i18n.t('app.admin.warehouse.incidents.page.text_4'), tone: "neutral" },
}

const severityMap: Record<string, { label: string; tone: StatusTone }> = {
  low: { label: i18n.t('app.admin.warehouse.incidents.page.text_5'), tone: "neutral" },
  medium: { label: i18n.t('app.admin.warehouse.incidents.page.text_6'), tone: "warning" },
  high: { label: i18n.t('app.admin.warehouse.incidents.page.text_7'), tone: "danger" },
  critical: { label: i18n.t('app.admin.warehouse.incidents.page.text_8'), tone: "danger" },
}

export default function IncidentsPage() {
  const { items: incidents, isLoading, fetchItems, createItem, investigateIncident, resolveIncident, closeIncident, fetchLinkedAdjustments, createLinkedAdjustment } = useIncidents()
  
  const [selectedIncident, setSelectedIncident] = useState<IncidentDTO | null>(null)
  
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
  const [isInvestigateModalOpen, setIsInvestigateModalOpen] = useState(false)
  const [isResolveModalOpen, setIsResolveModalOpen] = useState(false)
  const [isCloseModalOpen, setIsCloseModalOpen] = useState(false)
  const [isAdjustmentsModalOpen, setIsAdjustmentsModalOpen] = useState(false)

  // Form states
  const [incidentType, setIncidentType] = useState("missing_bar")
  const [severity, setSeverity] = useState("medium")
  const [incidentBarId, setIncidentBarId] = useState("")
  const [incidentVaultId, setIncidentVaultId] = useState("")
  const [incidentDesc, setIncidentDesc] = useState("")

  const [resolutionNotes, setResolutionNotes] = useState("")
  
  const [adjustmentsList, setAdjustmentsList] = useState<any[]>([])
  const [isAdjustmentsLoading, setIsAdjustmentsLoading] = useState(false)
  
  const [adjType, setAdjType] = useState("write_off")
  const [adjGrams, setAdjGrams] = useState<number | undefined>(undefined)
  const [adjNotes, setAdjNotes] = useState("")

  const [isSubmitting, setIsSubmitting] = useState(false)

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

  const openCount = incidents.filter(i => i.status === 'open').length
  const criticalCount = incidents.filter(i => i.severity === 'critical' || i.severity === 'high').length
  const investigatingCount = incidents.filter(i => i.status === 'investigating').length

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

  const loadAdjustments = async (id: string) => {
    setIsAdjustmentsLoading(true)
    const data = await fetchLinkedAdjustments(id)
    setAdjustmentsList(data)
    setIsAdjustmentsLoading(false)
  }

  const handleCreateIncident = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true)
    const success = await createItem({
      incident_number: `INC-${Date.now()}`,
      incident_type: incidentType,
      severity,
      bar_id: incidentBarId || undefined,
      vault_id: incidentVaultId || undefined,
      description: incidentDesc || undefined
    })
    setIsSubmitting(false)
    if (success) {
      toast.success(i18n.t('app.admin.warehouse.incidents.page.text_9'))
      setIsCreateModalOpen(false)
      setIncidentBarId("")
      setIncidentDesc("")
    }
  }

  const handleCreateAdjustment = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedIncident) return
    setIsSubmitting(true)
    const success = await createLinkedAdjustment({
      inventory_incident_id: selectedIncident.id,
      adjustment_type: adjType,
      grams: adjGrams,
      notes: adjNotes
    })
    setIsSubmitting(false)
    if (success) {
      toast.success(i18n.t('app.admin.warehouse.incidents.page.text_10'))
      setAdjGrams(undefined)
      setAdjNotes("")
      loadAdjustments(selectedIncident.id)
    }
  }

  const columns: Column<IncidentDTO>[] = [
    {
      key: "incident_number",
      header: i18n.t('app.admin.warehouse.incidents.page.text_11'),
      cell: (row) => <span className="font-mono text-sm font-medium">{row.incident_number}</span>,
    },
    {
      key: "type",
      header: i18n.t('app.admin.warehouse.incidents.page.text_12'),
      cell: (row) => <span className="text-sm font-medium capitalize">{row.incident_type.replace('_', ' ')}</span>,
    },
    {
      key: "severity",
      header: i18n.t('app.admin.warehouse.incidents.page.text_13'),
      cell: (row) => {
        const s = severityMap[row.severity] || { label: row.severity, tone: "neutral" }
        return <StatusBadge tone={s.tone}>{s.label}</StatusBadge>
      },
    },
    {
      key: "status",
      header: i18n.t('app.admin.warehouse.incidents.page.text_14'),
      cell: (row) => {
        const s = statusMap[row.status] || { label: row.status, tone: "neutral" }
        return <StatusBadge tone={s.tone}>{s.label}</StatusBadge>
      },
    },
    {
      key: "description",
      header: i18n.t('app.admin.warehouse.incidents.page.text_15'),
      cell: (row) => <span className="text-sm text-muted-foreground truncate max-w-[200px] block">{row.description || '—'}</span>,
    },
    {
      key: "reported_at",
      header: i18n.t('app.admin.warehouse.incidents.page.text_16'),
      cell: (row) => <span className="text-xs text-muted-foreground">{formatDateTime(row.reported_at)}</span>,
    },
    {
      key: "actions",
      header: i18n.t('app.admin.warehouse.incidents.page.text_17'),
      cell: (row) => (
        <div className="flex items-center gap-2">
          {row.status === 'open' && (
            <button onClick={() => { setSelectedIncident(row); setIsInvestigateModalOpen(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">
              <Search className="w-3 h-3" /> {i18n.t('app.admin.warehouse.incidents.page.text_53')}</button>
          )}
          {row.status === 'investigating' && (
            <button onClick={() => { setSelectedIncident(row); setIsResolveModalOpen(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.warehouse.incidents.page.text_54')}</button>
          )}
          {row.status === 'resolved' && (
            <button onClick={() => { setSelectedIncident(row); setIsCloseModalOpen(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.warehouse.incidents.page.text_55')}</button>
          )}
          <button onClick={() => { setSelectedIncident(row); loadAdjustments(row.id); setIsAdjustmentsModalOpen(true); }} className="text-xs px-2 py-1 bg-purple-500/10 text-purple-600 hover:bg-purple-500/20 rounded transition-colors flex items-center gap-1" title={i18n.t('app.admin.warehouse.incidents.page.text_18')}>
            <Scale className="w-3 h-3" /> {i18n.t('app.admin.warehouse.incidents.page.text_56')}</button>
        </div>
      )
    }
  ]

  return (
    <div className="flex flex-col gap-6">
      <div className="flex justify-between items-start">
        <PageHeader 
          title={i18n.t('app.admin.warehouse.incidents.page.text_19')} 
          description={i18n.t('app.admin.warehouse.incidents.page.text_20')}
        />
        <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.warehouse.incidents.page.text_57')}</button>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard title={i18n.t('app.admin.warehouse.incidents.page.text_21')} value={incidents.length} icon={AlertOctagon} tone="primary" />
        <KpiCard title={i18n.t('app.admin.warehouse.incidents.page.text_22')} value={openCount} icon={AlertTriangle} tone="warning" />
        <KpiCard title={i18n.t('app.admin.warehouse.incidents.page.text_23')} value={criticalCount} icon={AlertOctagon} tone="danger" />
        <KpiCard title={i18n.t('app.admin.warehouse.incidents.page.text_24')} value={investigatingCount} icon={Search} tone="info" />
      </div>

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

      {/* Modals */}
      <Modal open={isInvestigateModalOpen} onClose={() => setIsInvestigateModalOpen(false)} title={i18n.t('app.admin.warehouse.incidents.page.text_26')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.incidents.page.text_58')}</p>
          <div className="flex justify-end gap-3 pt-4"><button onClick={() => setIsInvestigateModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.incidents.page.text_59')}</button><button onClick={() => handleAction(() => investigateIncident(selectedIncident!.id), setIsInvestigateModalOpen, i18n.t('app.admin.warehouse.incidents.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.incidents.page.text_60')}</button></div>
        </div>
      </Modal>

      <Modal open={isResolveModalOpen} onClose={() => setIsResolveModalOpen(false)} title={i18n.t('app.admin.warehouse.incidents.page.text_28')} size="sm">
        <form onSubmit={(e) => { e.preventDefault(); handleAction(() => resolveIncident(selectedIncident!.id, resolutionNotes), setIsResolveModalOpen, i18n.t('app.admin.warehouse.incidents.page.text_29')); }} className="space-y-4">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.incidents.page.text_61')}</p>
          <InputField id="res_notes" name="res_notes" label={i18n.t('app.admin.warehouse.incidents.page.text_30')} required value={resolutionNotes} onChange={(e) => setResolutionNotes(e.target.value)} />
          <div className="flex justify-end gap-3 pt-4"><button type="button" onClick={() => setIsResolveModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.incidents.page.text_62')}</button><button type="submit" disabled={isSubmitting || !resolutionNotes} className="px-4 py-2 text-sm bg-primary text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.incidents.page.text_63')}</button></div>
        </form>
      </Modal>

      <Modal open={isCloseModalOpen} onClose={() => setIsCloseModalOpen(false)} title={i18n.t('app.admin.warehouse.incidents.page.text_31')} size="sm">
        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.warehouse.incidents.page.text_64')}</p>
          <div className="flex justify-end gap-3 pt-4"><button onClick={() => setIsCloseModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.warehouse.incidents.page.text_65')}</button><button onClick={() => handleAction(() => closeIncident(selectedIncident!.id), setIsCloseModalOpen, i18n.t('app.admin.warehouse.incidents.page.text_32'))} disabled={isSubmitting} className="px-4 py-2 text-sm bg-emerald-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.incidents.page.text_66')}</button></div>
        </div>
      </Modal>

      <Modal open={isCreateModalOpen} onClose={() => setIsCreateModalOpen(false)} title={i18n.t('app.admin.warehouse.incidents.page.text_33')} size="md">
        <form onSubmit={handleCreateIncident} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <SelectField id="inc_type" name="inc_type" label={i18n.t('app.admin.warehouse.incidents.page.text_34')} value={incidentType} onChange={(e) => setIncidentType(e.target.value)} options={[{value:'missing_bar', label:i18n.t('app.admin.warehouse.incidents.page.text_35')}, {value:'damaged_bar', label:i18n.t('app.admin.warehouse.incidents.page.text_36')}, {value:'weight_variance', label:i18n.t('app.admin.warehouse.incidents.page.text_37')}, {value:'other', label:i18n.t('app.admin.warehouse.incidents.page.text_38')}]} />
            <SelectField id="severity" name="severity" label={i18n.t('app.admin.warehouse.incidents.page.text_39')} value={severity} onChange={(e) => setSeverity(e.target.value)} options={[{value:'low', label:i18n.t('app.admin.warehouse.incidents.page.text_40')}, {value:'medium', label:i18n.t('app.admin.warehouse.incidents.page.text_41')}, {value:'high', label:i18n.t('app.admin.warehouse.incidents.page.text_42')}, {value:'critical', label:i18n.t('app.admin.warehouse.incidents.page.text_43')}]} />
            <InputField id="bar_id" name="bar_id" label={i18n.t('app.admin.warehouse.incidents.page.text_44')} value={incidentBarId} onChange={(e) => setIncidentBarId(e.target.value)} />
            <InputField id="vault_id" name="vault_id" label={i18n.t('app.admin.warehouse.incidents.page.text_45')} value={incidentVaultId} onChange={(e) => setIncidentVaultId(e.target.value)} />
          </div>
          <InputField id="description" name="description" label={i18n.t('app.admin.warehouse.incidents.page.text_46')} required value={incidentDesc} onChange={(e) => setIncidentDesc(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.warehouse.incidents.page.text_67')}</button><button type="submit" disabled={isSubmitting || !incidentDesc} className="px-4 py-2 text-sm bg-primary text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.incidents.page.text_68')}</button></div>
        </form>
      </Modal>

      <Modal open={isAdjustmentsModalOpen} onClose={() => setIsAdjustmentsModalOpen(false)} title={i18n.t('app.admin.warehouse.incidents.page.text_adjustments', { incident_number: selectedIncident?.incident_number })} size="lg">
        <div className="space-y-6 pt-2">
          {/* List existing adjustments */}
          <div>
            <h4 className="text-sm font-semibold mb-3">{i18n.t('app.admin.warehouse.incidents.page.text_69')}</h4>
            {isAdjustmentsLoading ? (
              <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>
            ) : adjustmentsList.length === 0 ? (
              <div className="text-center py-4 text-xs text-muted-foreground">{i18n.t('app.admin.warehouse.incidents.page.text_70')}</div>
            ) : (
              <div className="space-y-2">
                {adjustmentsList.map((adj: any) => (
                  <div key={adj.id} className="flex justify-between items-center p-3 rounded-lg border border-border bg-muted/30">
                    <div>
                      <div className="text-sm font-medium capitalize">{adj.adjustment_type.replace('_', ' ')}</div>
                      <div className="text-xs text-muted-foreground">{i18n.t('app.admin.warehouse.incidents.page.text_71')}{formatNumber(adj.grams)} {i18n.t('app.admin.warehouse.incidents.page.text_72')}{adj.status}</div>
                    </div>
                    <div className="text-xs text-muted-foreground">{formatDateTime(adj.created_at)}</div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Add new adjustment form */}
          {selectedIncident && !['closed'].includes(selectedIncident.status) && (
            <div className="pt-4 border-t border-border">
              <h4 className="text-sm font-semibold mb-3">{i18n.t('app.admin.warehouse.incidents.page.text_73')}</h4>
              <form onSubmit={handleCreateAdjustment} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <SelectField id="adj_type" name="adj_type" label={i18n.t('app.admin.warehouse.incidents.page.text_47')} value={adjType} onChange={(e) => setAdjType(e.target.value)} options={[{value:'write_off', label:i18n.t('app.admin.warehouse.incidents.page.text_48')}, {value:'write_on', label:i18n.t('app.admin.warehouse.incidents.page.text_49')}, {value:'purity_adjustment', label:i18n.t('app.admin.warehouse.incidents.page.text_50')}]} />
                  <InputField id="adj_grams" name="adj_grams" label={i18n.t('app.admin.warehouse.incidents.page.text_51')} type="number" step="0.01" required value={adjGrams || ''} onChange={(e) => setAdjGrams(parseFloat(e.target.value))} />
                </div>
                <InputField id="adj_notes" name="adj_notes" label={i18n.t('app.admin.warehouse.incidents.page.text_52')} required value={adjNotes} onChange={(e) => setAdjNotes(e.target.value)} />
                <div className="flex justify-end gap-3 pt-2">
                  <button type="submit" disabled={isSubmitting || !adjGrams || !adjNotes} className="px-4 py-2 text-sm bg-purple-600 text-white rounded-md disabled:opacity-50">{i18n.t('app.admin.warehouse.incidents.page.text_74')}</button>
                </div>
              </form>
            </div>
          )}
        </div>
      </Modal>

    </div>
  )
}
