'use client'

import { useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { Plus, Save, Send, Trash2 } 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, PuritySummary, SupplierDTO } from "@/types"
import type { PurchaseOrderCreatePayload } 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"

type DraftItem = {
  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: "",
})

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

export default function CreatePurchaseOrderPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { create, act, isSubmitting } = usePurchaseOrders()
  const [suppliers, setSuppliers] = useState<SupplierDTO[]>([])
  const [branches, setBranches] = useState<BranchDTO[]>([])
  const [currencies, setCurrencies] = useState<CurrencyOption[]>([])
  const [purities, setPurities] = useState<PuritySummary[]>([])
  const [form, setForm] = useState({
    supplier_id: "",
    currency_id: "",
    target_branch_id: "",
    target_vault_id: "",
    priority: "normal",
    payment_terms: "",
    delivery_terms: "",
    expected_delivery_date: "",
    supplier_reference: "",
    notes: "",
  })
  const [items, setItems] = useState<DraftItem[]>([newItem()])
  const [vaults, setVaults] = useState<any[]>([])

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

  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 (!form.supplier_id) { toast.error(language === "ar" ? "اختر المورد." : "Select a supplier."); return false }
    if (!form.currency_id) { toast.error(language === "ar" ? "اختر العملة." : "Select a currency."); return false }
    if (!form.target_branch_id) { toast.error(language === "ar" ? "اختر الفرع." : "Select a branch."); return false }
    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 (submitForReview = false) => {
    if (!validate()) return
    const payload: PurchaseOrderCreatePayload = {
      ...form,
      exchange_rate: 1,
      items: items.map(({ key, ...item }) => item),
    }
    try {
      const order = await create(payload)
      if (submitForReview) {
        await act(order.id, "submit_review")
        toast.success(language === "ar" ? "تم حفظ الأمر وإرساله للمراجعة." : "Order saved and submitted for review.")
      } else {
        toast.success(language === "ar" ? "تم حفظ الأمر كمسودة." : "Order saved as draft.")
      }
      router.push(`/purchase-orders/${order.id}`)
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to create order")
    }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "إنشاء أمر شراء" : "Create purchase order"}
        description={language === "ar" ? "أدخل بيانات المورد والمعادن، ثم احفظ المسودة أو أرسلها للمراجعة." : "Enter supplier and metal details, then save draft or submit for review."}
        breadcrumbs={[
          { label: language === "ar" ? "أوامر الشراء" : "Purchase Orders", href: "/purchase-orders" },
          { label: language === "ar" ? "إنشاء" : "Create" },
        ]}
      />

      <SectionCard title={language === "ar" ? "بيانات الأمر" : "Order information"}>
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          <SelectField
            id="supplier_id"
            name="supplier_id"
            label={language === "ar" ? "المورد" : "Supplier"}
            required
            value={form.supplier_id}
            onChange={e => setField("supplier_id", e.target.value)}
            options={suppliers.filter(s => s.status === "active").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"}
            required
            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"}
            required
            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="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 onClick={() => save(false)} isLoading={isSubmitting}>
              <Save className="h-4 w-4" />
              {language === "ar" ? "حفظ كمسودة" : "Save draft"}
            </Button>
            <Button variant="secondary" onClick={() => save(true)} isLoading={isSubmitting}>
              <Send className="h-4 w-4" />
              {language === "ar" ? "إرسال للمراجعة" : "Submit for review"}
            </Button>
          </div>
        </div>
      </SectionCard>
    </div>
  )
}
