'use client'

import { useEffect, useState, useMemo } 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 { Warehouse, Boxes, ShieldCheck, AlertTriangle, Activity, Loader2 } from "lucide-react"
import { formatDateTime } from "@/lib/format"
import { useInventory, type FractionalPoolDTO } from "@/hooks/useInventory"
import { useBars } from "@/hooks/useBars"
import { Modal } from "@/components/ui/modal"
import { InputField, SelectField } from "@/components/ui/FormFields"
import { toast } from "sonner"
import i18n from "@/lib/i18n";

type InvRow = {
  id: string
  sku: string
  product_name: string
  vault_location: string
  purity: string
  available_units: number
  reserved_units: number
  pending_units: number
  status: string
  last_audit_at: string | null
}

type ActivityRow = {
  id: string
  description: string
  vault_location: string | null
  authorized_by: string | null
  created_at: string
}

const statusMap: Record<string, { label: string; tone: StatusTone }> = {
  adequate: { label: i18n.t('app.admin.inventory.page.text_1'), tone: "success" },
  low: { label: i18n.t('app.admin.inventory.page.text_2'), tone: "warning" },
  critical: { label: i18n.t('app.admin.inventory.page.text_3'), tone: "danger" },
}

export default function InventoryPage() {
  const { items: fractionalPools, isLoading, fetchItems, addBarToPool } = useInventory()
  const { items: bars, fetchItems: fetchBars } = useBars()

  const [isAddBarModalOpen, setIsAddBarModalOpen] = useState(false)
  const [isRemoveBarModalOpen, setIsRemoveBarModalOpen] = useState(false)
  const [selectedPoolId, setSelectedPoolId] = useState("")
  const [selectedBarId, setSelectedBarId] = useState("")
  const [contributedWeight, setContributedWeight] = useState<number | undefined>(undefined)
  const [removeReason, setRemoveReason] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)

  // Fetch pool bars when a pool is selected in the remove modal
  const [poolBars, setPoolBars] = useState<{ id: string, bar_id: string, bar_code?: string }[]>([])

  const [activities] = useState<ActivityRow[]>([
    {
      id: "ACT-1",
      description: i18n.t('app.admin.inventory.page.text_4'),
      vault_location: i18n.t('app.admin.inventory.page.text_5'),
      authorized_by: i18n.t('app.admin.inventory.page.text_6'),
      created_at: new Date().toISOString()
    },
    {
      id: "ACT-2",
      description: i18n.t('app.admin.inventory.page.text_7'),
      vault_location: "Main Warehouse - Sanaa",
      authorized_by: i18n.t('app.admin.inventory.page.text_8'),
      created_at: new Date(Date.now() - 3600000).toISOString()
    },
    {
      id: "ACT-3",
      description: i18n.t('app.admin.inventory.page.text_9'),
      vault_location: i18n.t('app.admin.inventory.page.text_10'),
      authorized_by: i18n.t('app.admin.inventory.page.text_11'),
      created_at: new Date(Date.now() - 7200000).toISOString()
    }
  ]) // Can be hooked up later

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

  const handleAddBar = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedPoolId || !selectedBarId) return
    setIsSubmitting(true)
    const success = await addBarToPool(selectedPoolId, selectedBarId, contributedWeight)
    setIsSubmitting(false)
    if (success) {
      toast.success(i18n.t('app.admin.inventory.page.text_12'))
      setIsAddBarModalOpen(false)
      setSelectedPoolId("")
      setSelectedBarId("")
      setContributedWeight(undefined)
      fetchItems() // refresh pool data
      fetchBars() // refresh available bars
    }
  }

  const handleRemoveBar = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedPoolId || !selectedBarId) return
    setIsSubmitting(true)
    const success = await removeBarFromPool(selectedPoolId, selectedBarId, removeReason)
    setIsSubmitting(false)
    if (success) {
      toast.success(i18n.t('app.admin.inventory.page.text_13'))
      setIsRemoveBarModalOpen(false)
      setSelectedPoolId("")
      setSelectedBarId("")
      setRemoveReason("")
      fetchItems()
      fetchBars()
    }
  }

  const rows: InvRow[] = useMemo(() => fractionalPools.map((pool: FractionalPoolDTO) => ({
    id: pool.id,
    sku: `POOL-${pool.id.substring(0, 6).toUpperCase()}`,
    product_name: `Pool ${pool.purity_name || 'Gold'}`,
    vault_location: pool.vault_name || '—',
    purity: pool.purity_name?.replace('K', '') || '—',
    available_units: pool.available_weight,
    reserved_units: pool.reserved_weight,
    pending_units: pool.allocated_client_weight,
    status: pool.coverage_status,
    last_audit_at: pool.last_calculated_at,
  })), [fractionalPools])

  const totalAvailable = useMemo(() => rows.reduce((acc, row) => acc + Number(row.available_units || 0), 0), [rows])
  const totalReserved = useMemo(() => rows.reduce((acc, row) => acc + Number(row.reserved_units || 0), 0), [rows])
  const criticalCount = useMemo(() => rows.filter(r => r.status === 'deficit' || r.status === 'critical').length, [rows])
  const vaults = useMemo(() => new Set(rows.map(r => r.vault_location)).size, [rows])

  const [selectedId, setSelectedId] = useState<string | null>(null)
  
  // Default selection
  useEffect(() => {
    if (rows.length > 0 && !selectedId) {
      const crit = rows.find(r => r.status === "deficit" || r.status === "critical");
      setSelectedId(crit ? crit.id : rows[0].id);
    }
  }, [rows, selectedId])

  const selected = rows.find(r => r.id === selectedId) || null

  const columns: Column<InvRow>[] = [
    { key: "sku", header: "SKU", cell: (r) => <span className="font-mono text-[12px] text-muted-foreground">{r.sku}</span> },
    { key: "product", header: i18n.t('app.admin.inventory.page.text_14'), cell: (r) => <span className="text-[13px] font-medium">{r.product_name}</span> },
    { key: "vault", header: i18n.t('app.admin.inventory.page.text_15'), cell: (r) => <span className="text-[12.5px]">{r.vault_location}</span> },
    { key: "available", header: i18n.t('app.admin.inventory.page.text_16'), cell: (r) => <span className="font-mono tabular-nums text-[13px] font-semibold">{r.available_units}</span> },
    { key: "reserved", header: i18n.t('app.admin.inventory.page.text_17'), cell: (r) => <span className="font-mono tabular-nums text-[13px] text-amber-700">{r.reserved_units}</span> },
    { key: "status", header: i18n.t('app.admin.inventory.page.text_18'), cell: (r) => <StatusBadge tone={statusMap[r.status]?.tone ?? "neutral"} size="sm">{statusMap[r.status]?.label ?? r.status}</StatusBadge> },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title={i18n.t('app.admin.inventory.page.text_19')}
        description={i18n.t('app.admin.inventory.page.text_20')}
        breadcrumbs={[{ label: i18n.t('app.admin.inventory.page.text_21'), href: "#" }, { label: i18n.t('app.admin.inventory.page.text_22') }]}
        actions={
          <div className="flex items-center gap-2">
            <button 
              onClick={() => { setSelectedPoolId(""); setSelectedBarId(""); setIsAddBarModalOpen(true); }}
              className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring gap-2"
            >
              <Boxes className="h-4 w-4" />
              {i18n.t('app.admin.inventory.page.text_50')}</button>
            <button 
              onClick={() => { setSelectedPoolId(""); setSelectedBarId(""); setIsRemoveBarModalOpen(true); }}
              className="inline-flex items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring gap-2"
            >
              <Activity className="h-4 w-4" />
              {i18n.t('app.admin.inventory.page.text_51')}</button>
          </div>
        }
      />

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.inventory.page.text_23')} value={String(totalAvailable)} icon={Boxes} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.inventory.page.text_24')} value={String(totalReserved)} icon={ShieldCheck} tone="warning" />
        <KpiCard label={i18n.t('app.admin.inventory.page.text_25')} value={String(vaults)} icon={Warehouse} tone="info" />
        <KpiCard label={i18n.t('app.admin.inventory.page.text_26')} value={String(criticalCount)} icon={AlertTriangle} tone="danger" />
      </div>

      <div className="grid gap-6 lg:grid-cols-[1fr_400px]">
        <SectionCard title={i18n.t('app.admin.inventory.page.text_27')} padded={false}>
          {isLoading && rows.length === 0 ? (
            <div className="flex justify-center items-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
          ) : rows.length === 0 ? (
            <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.inventory.page.text_52')}</div>
          ) : (
            <DataTable 
              columns={columns} 
              data={rows} 
              rowKey={(r) => r.id} 
              activeRowKey={selected?.id} 
              onRowClick={(r) => setSelectedId(r.id)}
            />
          )}
        </SectionCard>

        <div className="space-y-6">
          <SectionCard title={selected ? selected.product_name : i18n.t('app.admin.inventory.page.text_28')}>
            {selected ? (
              <div className="space-y-3">
                <div className="rounded-lg border border-border bg-muted/30 p-3 space-y-2 text-[12.5px]">
                  <div className="flex justify-between"><span className="text-muted-foreground">SKU</span><span className="font-mono">{selected.sku}</span></div>
                  <div className="flex justify-between"><span className="text-muted-foreground">{i18n.t('app.admin.inventory.page.text_53')}</span><span>{selected.vault_location}</span></div>
                  <div className="flex justify-between"><span className="text-muted-foreground">{i18n.t('app.admin.inventory.page.text_54')}</span><span className="font-mono">{selected.purity}%</span></div>
                  <div className="flex justify-between"><span className="text-muted-foreground">{i18n.t('app.admin.inventory.page.text_55')}</span><span>{selected.last_audit_at ? formatDateTime(selected.last_audit_at) : "—"}</span></div>
                </div>
                <div className="grid grid-cols-3 gap-2 text-center">
                  <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-2.5">
                    <p className="text-[10.5px] uppercase text-emerald-700">{i18n.t('app.admin.inventory.page.text_56')}</p>
                    <p className="font-mono text-[18px] font-bold text-emerald-700 tabular-nums">{selected.available_units}</p>
                  </div>
                  <div className="rounded-lg border border-amber-200 bg-amber-50 p-2.5">
                    <p className="text-[10.5px] uppercase text-amber-700">{i18n.t('app.admin.inventory.page.text_57')}</p>
                    <p className="font-mono text-[18px] font-bold text-amber-700 tabular-nums">{selected.reserved_units}</p>
                  </div>
                  <div className="rounded-lg border border-border bg-muted p-2.5">
                    <p className="text-[10.5px] uppercase text-muted-foreground">{i18n.t('app.admin.inventory.page.text_58')}</p>
                    <p className="font-mono text-[18px] font-bold tabular-nums">{selected.pending_units}</p>
                  </div>
                </div>
              </div>
            ) : (
              <p className="text-[13px] text-muted-foreground">{i18n.t('app.admin.inventory.page.text_59')}</p>
            )}
          </SectionCard>

          <SectionCard title={i18n.t('app.admin.inventory.page.text_29')} icon={<Activity className="h-4 w-4 text-gold-600" />}>
            {activities.length === 0 ? (
              <p className="text-[13px] text-muted-foreground">{i18n.t('app.admin.inventory.page.text_60')}</p>
            ) : (
              <ul className="space-y-3">
                {activities.map((a) => (
                  <li key={a.id} className="flex items-start gap-2.5 text-[12.5px]">
                    <div className="h-2 w-2 rounded-full bg-gold-500 mt-1.5 shrink-0" />
                    <div className="flex-1">
                      <p className="font-medium">{a.description}</p>
                      <p className="text-[11px] text-muted-foreground mt-0.5">
                        {a.vault_location ?? "—"} · {a.authorized_by ?? "—"} · {formatDateTime(a.created_at)}
                      </p>
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </SectionCard>
        </div>
    </div>

      <Modal open={isAddBarModalOpen} onClose={() => setIsAddBarModalOpen(false)} title={i18n.t('app.admin.inventory.page.text_30')} description={i18n.t('app.admin.inventory.page.text_31')} size="md">
        <form onSubmit={handleAddBar} className="space-y-4">
          <SelectField 
            id="pool_id" 
            name="pool_id" 
            label={i18n.t('app.admin.inventory.page.text_32')} 
            required 
            value={selectedPoolId} 
            onChange={(e) => setSelectedPoolId(e.target.value)} 
            options={fractionalPools.map(p => ({ value: p.id, label: i18n.t('app.admin.inventory.page.text_pool', { purity: p.purity_name || 'Gold', vault: p.vault_name || i18n.t('app.admin.inventory.page.text_33') }) }))} 
            placeholder={i18n.t('app.admin.inventory.page.text_34')} 
          />
          <SelectField 
            id="bar_id" 
            name="bar_id" 
            label={i18n.t('app.admin.inventory.page.text_35')} 
            required 
            value={selectedBarId} 
            onChange={(e) => setSelectedBarId(e.target.value)} 
            options={bars.filter(b => b.status === 'available').map(b => ({ value: b.id, label: i18n.t('app.admin.inventory.page.text_bar_weight', { bar_code: b.bar_code, weight: b.weight }) }))} 
            placeholder={i18n.t('app.admin.inventory.page.text_36')} 
          />
          <InputField 
            id="contributed_weight" 
            name="contributed_weight" 
            label={i18n.t('app.admin.inventory.page.text_37')} 
            type="number" 
            step="0.01" 
            min="0"
            value={contributedWeight || ""} 
            onChange={(e) => setContributedWeight(e.target.value ? parseFloat(e.target.value) : undefined)} 
          />
          <div className="flex justify-end gap-3 pt-4 border-t border-border mt-6">
            <button type="button" onClick={() => setIsAddBarModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.inventory.page.text_61')}</button>
            <button type="submit" disabled={isSubmitting || !selectedPoolId || !selectedBarId} className="px-4 py-2 text-sm bg-primary text-white rounded-md disabled:opacity-50">{isSubmitting ? i18n.t('app.admin.inventory.page.text_38') : i18n.t('app.admin.inventory.page.text_39')}</button>
          </div>
        </form>
      </Modal>

      <Modal open={isRemoveBarModalOpen} onClose={() => setIsRemoveBarModalOpen(false)} title={i18n.t('app.admin.inventory.page.text_40')} description={i18n.t('app.admin.inventory.page.text_41')} size="md">
        <form onSubmit={handleRemoveBar} className="space-y-4">
          <SelectField 
            id="remove_pool_id" 
            name="remove_pool_id" 
            label={i18n.t('app.admin.inventory.page.text_42')} 
            required 
            value={selectedPoolId} 
            onChange={(e) => setSelectedPoolId(e.target.value)} 
            options={fractionalPools.map(p => ({ value: p.id, label: i18n.t('app.admin.inventory.page.text_pool', { purity: p.purity_name || 'Gold', vault: p.vault_name || i18n.t('app.admin.inventory.page.text_43') }) }))} 
            placeholder={i18n.t('app.admin.inventory.page.text_44')} 
          />
          {/* Note: ideally we would fetch the bars for the selected pool dynamically, but for simplicity we rely on the user to select the bar_id from a known list or enter it manually for now, or just list all reserved/allocated bars. Let's just list all bars that are in status allocated_to_pool */}
          <SelectField 
            id="remove_bar_id" 
            name="remove_bar_id" 
            label={i18n.t('app.admin.inventory.page.text_45')} 
            required 
            value={selectedBarId} 
            onChange={(e) => setSelectedBarId(e.target.value)} 
            options={bars.filter(b => b.status === 'allocated_to_pool').map(b => ({ value: b.id, label: i18n.t('app.admin.inventory.page.text_bar_weight', { bar_code: b.bar_code, weight: b.weight }) }))} 
            placeholder={i18n.t('app.admin.inventory.page.text_46')} 
          />
          <InputField 
            id="remove_reason" 
            name="remove_reason" 
            label={i18n.t('app.admin.inventory.page.text_47')} 
            value={removeReason} 
            onChange={(e) => setRemoveReason(e.target.value)} 
          />
          <div className="flex justify-end gap-3 pt-4 border-t border-border mt-6">
            <button type="button" onClick={() => setIsRemoveBarModalOpen(false)} className="px-4 py-2 text-sm bg-muted rounded-md">{i18n.t('app.admin.inventory.page.text_62')}</button>
            <button type="submit" disabled={isSubmitting || !selectedPoolId || !selectedBarId} className="px-4 py-2 text-sm bg-red-600 text-white rounded-md disabled:opacity-50">{isSubmitting ? i18n.t('app.admin.inventory.page.text_48') : i18n.t('app.admin.inventory.page.text_49')}</button>
          </div>
        </form>
      </Modal>

    </div>
  )
}