'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import { useParams, useRouter } from "next/navigation"
import { ArrowLeft, Save, Trash2, Plus } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import { usePurchaseOrders } from "@/hooks/usePurchaseOrders"
import type { BranchDTO, CurrencyOption, PaginatedResponse, PurchaseOrderUpdatePayload, SupplierDTO, PuritySummary } from "@/types"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { Button } from "@/components/ui/button"
import { InputField, SelectField, TextAreaField } from "@/components/ui/FormFields"
import { fmtMoney } from "@/lib/format"

function arrayPayload<T>(value: any): T[] {
  const payload = value?.data ?? value
  return Array.isArray(payload) ? payload : (payload as PaginatedResponse<T>)?.items ?? []
}

function dateInputValue(value?: string | null) {
  return value ? value.slice(0, 10) : ""
}

function optional(value: string) {
  return value.trim() || undefined
}

type DraftItem = {
  id?: string
  key: string
  metal_type: string
  purity_id: string
  weight_grams: number
  quantity: number
  pricing_basis: "per_gram" | "per_unit"
  price_per_gram: number
  premium: number
  notes: string
}

const newItem = (): DraftItem => ({
  key: (typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).substring(2)),
  metal_type: "gold",
  purity_id: "",
  weight_grams: 0,
  quantity: 1,
  pricing_basis: "per_gram",
  price_per_gram: 0,
  premium: 0,
  notes: "",
})

export default function EditPurchaseOrderPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { selected: order, isLoading, isSubmitting, error, get, update } = usePurchaseOrders()
  const [suppliers, setSuppliers] = useState<SupplierDTO[]>([])
  const [branches, setBranches] = useState<BranchDTO[]>([])
  const [currencies, setCurrencies] = useState<CurrencyOption[]>([])
  const [purities, setPurities] = useState<PuritySummary[]>([])
  const [vaults, setVaults] = useState<any[]>([])
  const [form, setForm] = useState({
    supplier_id: "",
    currency_id: "",
    target_branch_id: "",
    target_vault_id: "",
    priority: "normal",
    payment_terms: "",
    delivery_terms: "",
    cost_center: "",
    expected_delivery_date: "",
    supplier_reference: "",
    external_reference: "",
    notes: "",
  })
  const [items, setItems] = useState<DraftItem[]>([])

  const refresh = useCallback(async () => {
    if (!id) return
    const loaded = await get(id)
    if (!loaded) return
    setForm({
      supplier_id: loaded.supplier_id ?? "",
      currency_id: loaded.currency_id ?? "",
      target_branch_id: loaded.target_branch_id ?? "",
      target_vault_id: loaded.target_vault_id ?? "",
      priority: loaded.priority ?? "normal",
      payment_terms: loaded.payment_terms ?? "",
      delivery_terms: loaded.delivery_terms ?? "",
      cost_center: loaded.cost_center ?? "",
      expected_delivery_date: dateInputValue(loaded.expected_delivery_date),
      supplier_reference: loaded.supplier_reference ?? "",
      external_reference: loaded.external_reference ?? "",
      notes: loaded.notes ?? "",
    })
    if (loaded.items && loaded.items.length > 0) {
      setItems(loaded.items.map(i => ({
        id: i.id,
        key: (typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).substring(2)),
        metal_type: i.metal_type || "gold",
        purity_id: i.purity_id || "",
        weight_grams: Number(i.weight_grams) || 0,
        quantity: i.quantity || 1,
        pricing_basis: i.pricing_basis || "per_gram",
        price_per_gram: Number(i.price_per_gram) || 0,
        premium: Number(i.premium) || 0,
        notes: i.notes || "",
      })))
    } else {
      setItems([newItem()])
    }
  }, [id, get])

  useEffect(() => {
    refresh()
    Promise.all([
      api.get("/suppliers/"),
      api.get("/branches/"),
      api.get(ENDPOINTS.CURRENCIES.LIST),
      api.get("/warehouse/vaults"),
      api.get("/purities/", { params: { active_only: true } }),
    ])
      .then(([s, b, c, v, p]) => {
        setSuppliers(arrayPayload<SupplierDTO>(s))
        setBranches(arrayPayload<BranchDTO>(b))
        setCurrencies(Array.isArray(c?.data ?? c) ? (c?.data ?? c) : [])
        setVaults(arrayPayload<any>(v))
        setPurities(arrayPayload<PuritySummary>(p))
      })
      .catch(err => toast.error(err?.response?.data?.detail || err?.message || "Failed to load lookups"))
  }, [refresh])

  const selectedVaults = vaults.filter(v => !form.target_branch_id || v.branch_id === form.target_branch_id)
  const selectedCurrency = currencies.find(c => c.id === form.currency_id)
  const itemTotal = (item: DraftItem) => {
    const basisValue = item.pricing_basis === "per_unit" ? Number(item.quantity || 0) : Number(item.weight_grams || 0)
    return (basisValue * Number(item.price_per_gram || 0)) + Number(item.premium || 0)
  }

  const subtotal = useMemo(
    () => items.reduce((sum, item) => sum + itemTotal(item), 0),
    [items],
  )

  const setField = (name: string, value: string) => {
    setForm(current => {
      const next = { ...current, [name]: value }
      if (name === "target_branch_id") next.target_vault_id = ""
      return next
    })
  }

  const updateItem = (key: string, field: keyof DraftItem, value: string | number) => {
    setItems(current => current.map(item => item.key === key ? { ...item, [field]: value } : item))
  }

  const validate = () => {
    if (items.some(item => !item.purity_id || Number(item.weight_grams) <= 0)) {
      toast.error(language === "ar" ? "أكمل العيار والوزن لكل بند." : "Complete purity and weight for every item.")
      return false
    }
    return true
  }

  const save = async () => {
    if (!id || !order) return
    if (order.status !== "draft") {
      toast.error(language === "ar" ? "يمكن تعديل أوامر الشراء في حالة المسودة فقط." : "Only draft purchase orders can be edited.")
      return
    }
    if (!validate()) return
    const payload: PurchaseOrderUpdatePayload = {
      supplier_id: optional(form.supplier_id),
      currency_id: optional(form.currency_id),
      target_branch_id: optional(form.target_branch_id),
      target_vault_id: optional(form.target_vault_id),
      priority: optional(form.priority),
      payment_terms: optional(form.payment_terms),
      delivery_terms: optional(form.delivery_terms),
      cost_center: optional(form.cost_center),
      expected_delivery_date: optional(form.expected_delivery_date),
      supplier_reference: optional(form.supplier_reference),
      external_reference: optional(form.external_reference),
      notes: optional(form.notes),
    }
    try {
      await update(id, payload)

      const newItems = items.filter(i => !i.id)
      const currentIds = items.map(i => i.id).filter(Boolean)
      const deletedItems = (order.items || []).filter(i => !currentIds.includes(i.id))
      const updatedItems = items.filter(i => {
        if (!i.id) return false
        const orig = order.items?.find(o => o.id === i.id)
        if (!orig) return false
        return orig.purity_id !== i.purity_id ||
               Number(orig.weight_grams) !== Number(i.weight_grams) ||
               orig.quantity !== i.quantity ||
               (orig.pricing_basis || "per_gram") !== i.pricing_basis ||
               Number(orig.price_per_gram) !== Number(i.price_per_gram) ||
               Number(orig.premium) !== Number(i.premium)
      })

      for (const item of [...deletedItems, ...updatedItems]) {
         const itemId = item.id || (item as any).id
         if (itemId) await api.del(ENDPOINTS.BUY_ORDERS.ITEM(id, itemId))
      }
      for (const item of [...newItems, ...updatedItems]) {
         await api.post(ENDPOINTS.BUY_ORDERS.ITEMS(id), {
           metal_type: item.metal_type,
           purity_id: item.purity_id || null,
           weight_grams: Number(item.weight_grams),
           quantity: Number(item.quantity),
           pricing_basis: item.pricing_basis,
           price_per_gram: Number(item.price_per_gram),
           premium: Number(item.premium),
           notes: item.notes || null
         })
      }
      if (deletedItems.length > 0 || updatedItems.length > 0 || newItems.length > 0) {
         await api.post(ENDPOINTS.BUY_ORDERS.RECALCULATE(id))
      }

      toast.success(language === "ar" ? "تم تحديث أمر الشراء." : "Purchase order updated.")
      router.push(`/purchase-orders/${id}`)
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to update purchase order")
    }
  }

  if (isLoading && !order) {
    return <div className="flex h-80 items-center justify-center"><div className="h-9 w-9 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" /></div>
  }

  if (!order) {
    return <div className="rounded-lg border border-red-200 bg-red-50 p-6 text-red-700">{error || "Purchase order not found"}</div>
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "تعديل أمر الشراء" : "Edit purchase order"}
        description={order.buy_order_no}
        breadcrumbs={[
          { label: language === "ar" ? "أوامر الشراء" : "Purchase Orders", href: "/purchase-orders" },
          { label: order.buy_order_no, href: `/purchase-orders/${order.id}` },
          { label: language === "ar" ? "تعديل" : "Edit" },
        ]}
        actions={
          <Button variant="outline" onClick={() => router.push(`/purchase-orders/${order.id}`)}>
            <ArrowLeft className="h-4 w-4" />
            {language === "ar" ? "رجوع" : "Back"}
          </Button>
        }
      />

      <SectionCard title={language === "ar" ? "بيانات أمر الشراء" : "Purchase order details"}>
        {order.status !== "draft" && (
          <div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">
            {language === "ar" ? "يمكن تعديل أوامر الشراء في حالة المسودة فقط." : "Only draft purchase orders can be edited."}
          </div>
        )}
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          <SelectField
            id="supplier_id"
            name="supplier_id"
            label={language === "ar" ? "المورد" : "Supplier"}
            value={form.supplier_id}
            onChange={e => setField("supplier_id", e.target.value)}
            options={suppliers.map(s => ({ value: s.id, label: language === "ar" ? s.name_ar : s.name_en || s.name_ar }))}
          />
          <SelectField
            id="currency_id"
            name="currency_id"
            label={language === "ar" ? "العملة" : "Currency"}
            value={form.currency_id}
            onChange={e => setField("currency_id", e.target.value)}
            options={currencies.map(c => ({ value: c.id, label: `${c.code} - ${language === "ar" ? c.name_ar : c.name_en}` }))}
          />
          <SelectField
            id="priority"
            name="priority"
            label={language === "ar" ? "الأولوية" : "Priority"}
            value={form.priority}
            onChange={e => setField("priority", e.target.value)}
            options={["low", "normal", "high", "urgent"].map(v => ({ value: v, label: v }))}
          />
          <SelectField
            id="target_branch_id"
            name="target_branch_id"
            label={language === "ar" ? "الفرع" : "Branch"}
            value={form.target_branch_id}
            onChange={e => setField("target_branch_id", e.target.value)}
            options={branches.filter(b => b.status === "active").map(b => ({ value: b.id, label: language === "ar" ? b.name_ar : b.name_en || b.name_ar }))}
          />
          <SelectField
            id="target_vault_id"
            name="target_vault_id"
            label={language === "ar" ? "الخزنة" : "Vault"}
            value={form.target_vault_id}
            onChange={e => setField("target_vault_id", e.target.value)}
            disabled={!form.target_branch_id}
            options={selectedVaults.map(v => ({ value: v.id, label: v.name }))}
          />
          <InputField
            id="expected_delivery_date"
            name="expected_delivery_date"
            label={language === "ar" ? "تاريخ التسليم المتوقع" : "Expected delivery"}
            type="date"
            value={form.expected_delivery_date}
            onChange={e => setField("expected_delivery_date", e.target.value)}
          />
          <InputField
            id="supplier_reference"
            name="supplier_reference"
            label={language === "ar" ? "مرجع المورد" : "Supplier reference"}
            value={form.supplier_reference}
            onChange={e => setField("supplier_reference", e.target.value)}
          />
          <InputField
            id="external_reference"
            name="external_reference"
            label={language === "ar" ? "مرجع خارجي" : "External reference"}
            value={form.external_reference}
            onChange={e => setField("external_reference", e.target.value)}
          />
          <InputField
            id="cost_center"
            name="cost_center"
            label={language === "ar" ? "مركز التكلفة" : "Cost center"}
            value={form.cost_center}
            onChange={e => setField("cost_center", e.target.value)}
          />
          <InputField
            id="payment_terms"
            name="payment_terms"
            label={language === "ar" ? "شروط الدفع" : "Payment terms"}
            value={form.payment_terms}
            onChange={e => setField("payment_terms", e.target.value)}
          />
          <InputField
            id="delivery_terms"
            name="delivery_terms"
            label={language === "ar" ? "شروط التسليم" : "Delivery terms"}
            value={form.delivery_terms}
            onChange={e => setField("delivery_terms", e.target.value)}
          />
        </div>
        <div className="mt-4">
          <TextAreaField id="notes" name="notes" label={language === "ar" ? "ملاحظات" : "Notes"} rows={3} value={form.notes} onChange={e => setField("notes", e.target.value)} />
        </div>
      </SectionCard>

      <SectionCard title={language === "ar" ? "بنود المعادن" : "Metal items"}>
        <div className="space-y-4">
          {items.map((item, index) => (
            <div key={item.key} className="rounded-lg border border-border bg-muted/20 p-4">
              <div className="mb-3 flex items-center justify-between">
                <strong>{language === "ar" ? `البند ${index + 1}` : `Item ${index + 1}`}</strong>
                {items.length > 1 && (
                  <Button size="sm" variant="ghost" onClick={() => setItems(current => current.filter(row => row.key !== item.key))}>
                    <Trash2 className="h-4 w-4 text-red-600" />
                  </Button>
                )}
              </div>
              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-6">
                <SelectField
                  id={`purity-${item.key}`}
                  name="purity_id"
                  label={language === "ar" ? "العيار" : "Purity"}
                  required
                  value={item.purity_id}
                  onChange={e => updateItem(item.key, "purity_id", e.target.value)}
                  options={purities.map(p => ({ value: p.id, label: `${p.karat}K` }))}
                />
                <InputField
                  id={`weight-${item.key}`}
                  name="weight_grams"
                  label={language === "ar" ? "الوزن (جم)" : "Weight (g)"}
                  type="number"
                  min="0.000001"
                  step="0.000001"
                  required
                  value={item.weight_grams}
                  onChange={e => updateItem(item.key, "weight_grams", Number(e.target.value))}
                />
                <InputField
                  id={`qty-${item.key}`}
                  name="quantity"
                  label={language === "ar" ? "الكمية" : "Quantity"}
                  type="number"
                  min="1"
                  required
                  value={item.quantity}
                  onChange={e => updateItem(item.key, "quantity", Number(e.target.value))}
                />
                <SelectField
                  id={`pricing-basis-${item.key}`}
                  name="pricing_basis"
                  label={language === "ar" ? "طريقة السعر" : "Price basis"}
                  value={item.pricing_basis}
                  onChange={e => updateItem(item.key, "pricing_basis", e.target.value)}
                  options={[
                    { value: "per_gram", label: language === "ar" ? "لكل جرام" : "Per gram" },
                    { value: "per_unit", label: language === "ar" ? "لكل وحدة" : "Per unit" },
                  ]}
                />
                <InputField
                  id={`price-${item.key}`}
                  name="price_per_gram"
                  label={item.pricing_basis === "per_unit" ? (language === "ar" ? "سعر الوحدة" : "Price / unit") : (language === "ar" ? "سعر الجرام" : "Price / gram")}
                  type="number"
                  min="0"
                  step="0.01"
                  value={item.price_per_gram}
                  onChange={e => updateItem(item.key, "price_per_gram", Number(e.target.value))}
                />
                <InputField
                  id={`premium-${item.key}`}
                  name="premium"
                  label={language === "ar" ? "العلاوة" : "Premium"}
                  type="number"
                  min="0"
                  step="0.01"
                  value={item.premium}
                  onChange={e => updateItem(item.key, "premium", Number(e.target.value))}
                />
              </div>
            </div>
          ))}
        </div>
        <div className="mt-4 flex flex-wrap justify-between gap-3 border-t border-border pt-4">
          <Button variant="outline" onClick={() => setItems(current => [...current, newItem()])}>
            <Plus className="h-4 w-4" />
            {language === "ar" ? "إضافة بند" : "Add item"}
          </Button>
          <div className="flex flex-wrap items-center gap-3">
            <span className="font-mono text-lg font-bold">{fmtMoney(subtotal, selectedCurrency?.code)}</span>
            <Button variant="outline" onClick={() => router.push(`/purchase-orders/${order.id}`)}>
              {language === "ar" ? "إلغاء" : "Cancel"}
            </Button>
            <Button onClick={save} isLoading={isSubmitting} disabled={order.status !== "draft"}>
              <Save className="h-4 w-4" />
              {language === "ar" ? "حفظ التعديلات" : "Save changes"}
            </Button>
          </div>
        </div>
      </SectionCard>
    </div>
  )
}
