'use client'

import { useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { Calculator, 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 { buyErrorMessage, useBuyOrders } from "@/hooks/useBuyOrders"
import type { BranchDTO, BuyOrderItemPayload, CurrencyOption, CustomerDTO, PaginatedResponse, PuritySummary, VaultDTO } 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 SupplierOption = { id: string; supplier_code?: string | null; name_en?: string | null; name_ar?: string | null; legal_name?: string | null; status?: string | null }
type DraftItem = BuyOrderItemPayload & { key: string }
type FormState = {
  buy_order_type: "supplier" | "customer_buyback"
  supplier_id: string
  customer_id: string
  currency_id: string
  exchange_rate: string
  target_branch_id: string
  target_vault_id: string
  expected_delivery_date: string
  payment_terms: string
  delivery_terms: string
  cost_center: string
  supplier_reference: string
  external_reference: string
  priority: string
  notes: string
}
type FormErrors = Partial<Record<keyof FormState | "items" | "pricing", 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,
  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 ?? []
}

const priorityOptions = {
  low: { en: "Low", ar: "منخفضة" },
  normal: { en: "Normal", ar: "عادية" },
  high: { en: "High", ar: "عالية" },
  urgent: { en: "Urgent", ar: "عاجلة" },
}

export default function CreateBuyOrderPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { create, quote, act, isSubmitting } = useBuyOrders()
  const [customers, setCustomers] = useState<CustomerDTO[]>([])
  const [suppliers, setSuppliers] = useState<SupplierOption[]>([])
  const [branches, setBranches] = useState<BranchDTO[]>([])
  const [vaults, setVaults] = useState<VaultDTO[]>([])
  const [purities, setPurities] = useState<PuritySummary[]>([])
  const [currencies, setCurrencies] = useState<CurrencyOption[]>([])
  const [form, setForm] = useState<FormState>({
    buy_order_type: "supplier",
    supplier_id: "",
    customer_id: "",
    currency_id: "",
    exchange_rate: "1",
    target_branch_id: "",
    target_vault_id: "",
    expected_delivery_date: "",
    payment_terms: "",
    delivery_terms: "",
    cost_center: "",
    supplier_reference: "",
    external_reference: "",
    priority: "normal",
    notes: "",
  })
  const [items, setItems] = useState<DraftItem[]>([newItem()])
  const [errors, setErrors] = useState<FormErrors>({})
  const [loadingLookups, setLoadingLookups] = useState(true)
  const [quoting, setQuoting] = useState(false)
  const [submitAfterSave, setSubmitAfterSave] = useState(false)

  useEffect(() => {
    setLoadingLookups(true)
    Promise.all([
      api.get("/customers", { params: { page: 1, page_size: 100 } }),
      api.get("/suppliers/approved", { params: { skip: 0, limit: 100 } }),
      api.get("/branches/"),
      api.get("/warehouse/vaults"),
      api.get("/purities/", { params: { active_only: true } }),
      api.get(ENDPOINTS.CURRENCIES.LIST),
    ])
      .then(([c, s, b, v, p, cur]) => {
        setCustomers(arrayPayload<CustomerDTO>(c))
        setSuppliers(arrayPayload<SupplierOption>(s))
        setBranches(arrayPayload<BranchDTO>(b))
        setVaults(arrayPayload<VaultDTO>(v))
        setPurities(arrayPayload<PuritySummary>(p))
        setCurrencies(Array.isArray(cur?.data ?? cur) ? (cur?.data ?? cur) : [])
      })
      .catch(err => toast.error(buyErrorMessage(err)))
      .finally(() => setLoadingLookups(false))
  }, [])

  const selectedVaults = vaults.filter(vault => !form.target_branch_id || vault.branch_id === form.target_branch_id)
  const selectedCurrency = currencies.find(currency => currency.id === form.currency_id)
  const subtotal = useMemo(
    () => items.reduce((sum, item) => sum + Number(item.weight_grams) * Number(item.quantity || 1) * Number(item.price_per_gram || 0) + Number(item.premium || 0) * Number(item.quantity || 1), 0),
    [items],
  )

  const setField = (name: keyof FormState, value: string) => {
    setForm(current => {
      const next = { ...current, [name]: value }
      if (name === "target_branch_id") next.target_vault_id = ""
      if (name === "buy_order_type") {
        next.supplier_id = ""
        next.customer_id = ""
      }
      return next
    })
    setErrors(current => ({ ...current, [name]: undefined }))
  }

  const updateItem = (key: string, field: keyof DraftItem, value: string | number) => {
    setItems(current => current.map(item => item.key === key ? { ...item, [field]: value, ...(field === "purity_id" || field === "weight_grams" ? { price_per_gram: 0 } : {}) } : item))
    setErrors(current => ({ ...current, items: undefined, pricing: undefined }))
  }

  const validate = (requirePricing: boolean) => {
    const next: FormErrors = {}
    if (form.buy_order_type === "supplier" && !form.supplier_id) next.supplier_id = language === "ar" ? "اختر المورد." : "Select a supplier."
    if (form.buy_order_type === "customer_buyback" && !form.customer_id) next.customer_id = language === "ar" ? "اختر العميل." : "Select a customer."
    if (!form.currency_id) next.currency_id = language === "ar" ? "اختر العملة." : "Select a currency."
    if (!form.target_branch_id) next.target_branch_id = language === "ar" ? "اختر الفرع." : "Select a branch."
    if (!form.target_vault_id) next.target_vault_id = language === "ar" ? "اختر الخزنة." : "Select a vault."
    if (items.some(item => !item.purity_id || Number(item.weight_grams) <= 0 || Number(item.quantity || 0) <= 0)) {
      next.items = language === "ar" ? "أكمل العيار والوزن والكمية لكل بند." : "Complete purity, weight, and quantity for every item."
    }
    if (requirePricing && items.some(item => Number(item.price_per_gram || 0) <= 0)) {
      next.pricing = language === "ar" ? "احتسب السعر قبل الحفظ أو الإرسال." : "Calculate prices before saving or submitting."
    }
    setErrors(next)
    return Object.keys(next).length === 0
  }

  const calculate = async () => {
    if (!validate(false)) return false
    setQuoting(true)
    try {
      const prices = await Promise.all(items.map(item => quote(String(item.purity_id), form.currency_id, item.product_id)))
      setItems(current => current.map((item, index) => ({ ...item, price_per_gram: Number(prices[index].buy_price_per_gram) })))
      toast.success(language === "ar" ? "تم احتساب سعر الشراء." : "Buy prices calculated.")
      return true
    } catch (err) {
      toast.error(buyErrorMessage(err))
      return false
    } finally {
      setQuoting(false)
    }
  }

  const save = async (submitForReview = false) => {
    setSubmitAfterSave(submitForReview)
    if (!validate(true)) {
      setSubmitAfterSave(false)
      return
    }
    try {
      const order = await create({
        buy_order_type: form.buy_order_type,
        priority: form.priority as any,
        supplier_id: form.buy_order_type === "supplier" ? form.supplier_id : null,
        customer_id: form.buy_order_type === "customer_buyback" ? form.customer_id : null,
        currency_id: form.currency_id,
        exchange_rate: Number(form.exchange_rate || 1),
        target_branch_id: form.target_branch_id,
        target_vault_id: form.target_vault_id,
        expected_delivery_date: form.expected_delivery_date || null,
        payment_terms: form.payment_terms || null,
        delivery_terms: form.delivery_terms || null,
        cost_center: form.cost_center || null,
        supplier_reference: form.supplier_reference || null,
        external_reference: form.external_reference || null,
        notes: form.notes || null,
        items: items.map(({ key, ...item }) => item),
      })
      if (submitForReview) {
        await act(order.id, "submit", { reason: language === "ar" ? "إرسال للمراجعة من شاشة الإنشاء" : "Submitted from create form" })
        toast.success(language === "ar" ? "تم حفظ أمر الشراء وإرساله للمراجعة." : "Buy order saved and submitted for review.")
      } else {
        toast.success(language === "ar" ? "تم حفظ أمر الشراء كمسودة." : "Buy order saved as draft.")
      }
      router.push(`/buy-orders/${order.id}`)
    } catch (err) {
      toast.error(buyErrorMessage(err))
    } finally {
      setSubmitAfterSave(false)
    }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "إنشاء أمر شراء" : "Create buy order"}
        description={language === "ar" ? "أدخل بيانات الشراء والذهب، ثم احتسب السعر قبل الحفظ أو الإرسال." : "Enter buy order and gold details, then calculate pricing before saving or submitting."}
        breadcrumbs={[
          { label: language === "ar" ? "أوامر الشراء" : "Buy orders", href: "/buy-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="buy_order_type" name="buy_order_type" label={language === "ar" ? "نوع الشراء" : "Buy type"} value={form.buy_order_type} onChange={event => setField("buy_order_type", event.target.value)} options={[
            { value: "supplier", label: language === "ar" ? "شراء من مورد" : "Supplier purchase" },
            { value: "customer_buyback", label: language === "ar" ? "شراء من عميل" : "Customer buyback" },
          ]} />
          {form.buy_order_type === "supplier" ? (
            <SelectField id="supplier_id" name="supplier_id" label={language === "ar" ? "المورد" : "Supplier"} required disabled={loadingLookups} error={errors.supplier_id} value={form.supplier_id} onChange={event => setField("supplier_id", event.target.value)} options={suppliers.map(supplier => ({ value: supplier.id, label: (language === "ar" ? supplier.name_ar : supplier.name_en) || supplier.legal_name || supplier.supplier_code || supplier.id }))} />
          ) : (
            <SelectField id="customer_id" name="customer_id" label={language === "ar" ? "العميل" : "Customer"} required disabled={loadingLookups} error={errors.customer_id} value={form.customer_id} onChange={event => setField("customer_id", event.target.value)} options={customers.filter(customer => customer.status === "active").map(customer => ({ value: customer.id, label: customer.name || customer.customer_code || customer.id }))} />
          )}
          <SelectField id="currency_id" name="currency_id" label={language === "ar" ? "العملة" : "Currency"} required disabled={loadingLookups} error={errors.currency_id} value={form.currency_id} onChange={event => setField("currency_id", event.target.value)} options={currencies.map(currency => ({ value: currency.id, label: `${currency.code} - ${language === "ar" ? currency.name_ar : currency.name_en}` }))} />
          <InputField id="exchange_rate" name="exchange_rate" label={language === "ar" ? "سعر الصرف" : "Exchange rate"} type="number" min="0" step="0.000001" value={form.exchange_rate} onChange={event => setField("exchange_rate", event.target.value)} />
          <SelectField id="priority" name="priority" label={language === "ar" ? "الأولوية" : "Priority"} value={form.priority} onChange={event => setField("priority", event.target.value)} options={Object.entries(priorityOptions).map(([value, label]) => ({ value, label: label[language] }))} />
          <InputField id="expected_delivery_date" name="expected_delivery_date" label={language === "ar" ? "تاريخ التسليم المتوقع" : "Expected delivery"} type="date" value={form.expected_delivery_date} onChange={event => setField("expected_delivery_date", event.target.value)} />
          <SelectField id="target_branch_id" name="target_branch_id" label={language === "ar" ? "الفرع" : "Target branch"} required disabled={loadingLookups} error={errors.target_branch_id} value={form.target_branch_id} onChange={event => setField("target_branch_id", event.target.value)} options={branches.filter(branch => branch.status === "active").map(branch => ({ value: branch.id, label: language === "ar" ? branch.name_ar : branch.name_en || branch.name_ar }))} />
          <SelectField id="target_vault_id" name="target_vault_id" label={language === "ar" ? "الخزنة" : "Target vault"} required disabled={!form.target_branch_id} error={errors.target_vault_id} value={form.target_vault_id} onChange={event => setField("target_vault_id", event.target.value)} options={selectedVaults.map(vault => ({ value: vault.id, label: vault.name }))} />
          <InputField id="cost_center" name="cost_center" label={language === "ar" ? "مركز التكلفة" : "Cost center"} value={form.cost_center} onChange={event => setField("cost_center", event.target.value)} />
          <InputField id="supplier_reference" name="supplier_reference" label={language === "ar" ? "مرجع المورد" : "Supplier reference"} value={form.supplier_reference} onChange={event => setField("supplier_reference", event.target.value)} />
          <InputField id="external_reference" name="external_reference" label={language === "ar" ? "مرجع خارجي" : "External reference"} value={form.external_reference} onChange={event => setField("external_reference", event.target.value)} />
        </div>
        <div className="mt-4 grid gap-4 md:grid-cols-2">
          <TextAreaField id="payment_terms" name="payment_terms" label={language === "ar" ? "شروط الدفع" : "Payment terms"} rows={3} value={form.payment_terms} onChange={event => setField("payment_terms", event.target.value)} />
          <TextAreaField id="delivery_terms" name="delivery_terms" label={language === "ar" ? "شروط التسليم" : "Delivery terms"} rows={3} value={form.delivery_terms} onChange={event => setField("delivery_terms", event.target.value)} />
        </div>
        <div className="mt-4">
          <TextAreaField id="notes" name="notes" label={language === "ar" ? "ملاحظات" : "Notes"} rows={3} value={form.notes} onChange={event => setField("notes", event.target.value)} />
        </div>
      </SectionCard>

      <SectionCard title={language === "ar" ? "بنود الذهب" : "Gold items"}>
        {errors.items && <div className="mb-3 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">{errors.items}</div>}
        {errors.pricing && <div className="mb-3 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">{errors.pricing}</div>}
        <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-5">
                <SelectField id={`purity-${item.key}`} name="purity_id" label={language === "ar" ? "العيار" : "Purity"} required value={String(item.purity_id || "")} onChange={event => updateItem(item.key, "purity_id", event.target.value)} options={purities.map(purity => ({ value: purity.id, label: `${purity.karat}K - ${language === "ar" ? purity.name_ar : purity.name_en}` }))} />
                <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={event => updateItem(item.key, "weight_grams", Number(event.target.value))} />
                <InputField id={`qty-${item.key}`} name="quantity" label={language === "ar" ? "الكمية" : "Quantity"} type="number" min="1" required value={item.quantity ?? 1} onChange={event => updateItem(item.key, "quantity", Number(event.target.value))} />
                <InputField id={`price-${item.key}`} name="price_per_gram" label={language === "ar" ? "سعر الجرام" : "Price / gram"} type="number" disabled value={item.price_per_gram ?? 0} onChange={() => undefined} />
                <InputField id={`premium-${item.key}`} name="premium" label={language === "ar" ? "العلاوة" : "Premium"} type="number" min="0" value={item.premium ?? 0} onChange={event => updateItem(item.key, "premium", Number(event.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={calculate} isLoading={quoting} disabled={isSubmitting}><Calculator className="h-4 w-4" />{language === "ar" ? "احتساب السعر" : "Calculate price"}</Button>
            <Button onClick={() => save(false)} isLoading={isSubmitting && !submitAfterSave} disabled={quoting}><Save className="h-4 w-4" />{language === "ar" ? "حفظ كمسودة" : "Save draft"}</Button>
            <Button variant="secondary" onClick={() => save(true)} isLoading={isSubmitting && submitAfterSave} disabled={quoting}><Send className="h-4 w-4" />{language === "ar" ? "إرسال للمراجعة" : "Submit for review"}</Button>
          </div>
        </div>
      </SectionCard>
    </div>
  )
}

