'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 { sellErrorMessage, useSellOrders } from "@/hooks/useSellOrders"
import type { BranchDTO, CurrencyOption, CustomerDTO, PaginatedResponse, PuritySummary, SellOrderItemPayload, 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 DraftItem = SellOrderItemPayload & { key: string }
type FormState = { customer_id: string; currency_id: string; branch_id: string; vault_id: 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)),
  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 ?? []
}

export default function CreateSellOrderPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { create, quote, act, isSubmitting } = useSellOrders()
  const [customers, setCustomers] = useState<CustomerDTO[]>([])
  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>({ customer_id: "", currency_id: "", branch_id: "", vault_id: "", 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("/branches/"),
      api.get("/warehouse/vaults"),
      api.get("/purities/", { params: { active_only: true } }),
      api.get(ENDPOINTS.CURRENCIES.LIST),
    ])
      .then(([c, b, v, p, cur]) => {
        setCustomers(arrayPayload<CustomerDTO>(c))
        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(sellErrorMessage(err)))
      .finally(() => setLoadingLookups(false))
  }, [])

  const selectedCustomer = customers.find(customer => customer.id === form.customer_id)
  const selectedVaults = vaults.filter(vault => !form.branch_id || vault.branch_id === form.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), 0),
    [items],
  )

  const setField = (name: keyof FormState, value: string) => {
    setForm(current => {
      const next = { ...current, [name]: value }
      if (name === "branch_id") next.vault_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.customer_id) next.customer_id = language === "ar" ? "اختر العميل." : "Select a customer."
    if (!form.currency_id) next.currency_id = language === "ar" ? "اختر العملة." : "Select a currency."
    if (!form.branch_id) next.branch_id = language === "ar" ? "اختر الفرع." : "Select a branch."
    if (!form.vault_id) next.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(item.purity_id, form.currency_id)))
      setItems(current => current.map((item, index) => ({ ...item, price_per_gram: Number(prices[index].sell_price_per_gram) })))
      toast.success(language === "ar" ? "تم احتساب السعر بنجاح." : "Prices calculated.")
      return true
    } catch (err) {
      toast.error(sellErrorMessage(err))
      return false
    } finally {
      setQuoting(false)
    }
  }

  const save = async (submitForReview = false) => {
    setSubmitAfterSave(submitForReview)
    if (!validate(true)) {
      setSubmitAfterSave(false)
      return
    }
    try {
      const order = await create({
        ...form,
        priority: form.priority as any,
        sell_order_type: "customer_sale",
        items: items.map(({ key, ...item }) => item),
      })
      if (submitForReview) {
        await act(order.id, "submit", language === "ar" ? "إرسال للمراجعة من شاشة الإنشاء" : "Submitted from create form")
        toast.success(language === "ar" ? "تم حفظ أمر البيع وإرساله للمراجعة." : "Sell order saved and submitted for review.")
      } else {
        toast.success(language === "ar" ? "تم حفظ أمر البيع كمسودة." : "Sell order saved as draft.")
      }
      router.push(`/sell-orders/${order.id}`)
    } catch (err) {
      toast.error(sellErrorMessage(err))
    } finally {
      setSubmitAfterSave(false)
    }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "إنشاء أمر بيع" : "Create sell order"}
        description={language === "ar" ? "أدخل بيانات العميل والذهب، ثم احسب السعر قبل حفظ المسودة أو إرسالها للمراجعة." : "Enter customer and gold details, then calculate pricing before saving or submitting."}
        breadcrumbs={[
          { label: language === "ar" ? "أوامر البيع" : "Sell orders", href: "/sell-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="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}` }))}
          />
          <SelectField
            id="priority"
            name="priority"
            label={language === "ar" ? "الأولوية" : "Priority"}
            value={form.priority}
            onChange={event => setField("priority", event.target.value)}
            options={["low", "normal", "high", "urgent"].map(value => ({ value, label: value }))}
          />
          <SelectField
            id="pricing_mode"
            name="pricing_mode"
            label={language === "ar" ? "طريقة التسعير" : "Pricing mode"}
            value="current_price"
            disabled
            options={[{ value: "current_price", label: language === "ar" ? "سعر السوق الحالي" : "Current market price" }]}
            onChange={() => undefined}
          />
          <SelectField
            id="branch_id"
            name="branch_id"
            label={language === "ar" ? "الفرع" : "Branch"}
            required
            disabled={loadingLookups}
            error={errors.branch_id}
            value={form.branch_id}
            onChange={event => setField("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="vault_id"
            name="vault_id"
            label={language === "ar" ? "الخزنة" : "Vault"}
            required
            disabled={!form.branch_id}
            error={errors.vault_id}
            value={form.vault_id}
            onChange={event => setField("vault_id", event.target.value)}
            options={selectedVaults.map(vault => ({ value: vault.id, label: vault.name }))}
          />
        </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={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>
  )
}
