import { useState, FormEvent } from "react"
import { useReceivingOrders } from "@/hooks/useReceiving"
import { usePurities } from "@/hooks/usePurities"
import { DataTable, type Column } from "@/components/ui/data-table"
import { Modal } from "@/components/ui/modal"
import { InputField, SelectField, TextAreaField } from "@/components/ui/FormFields"
import { SearchableSelectField } from "@/components/ui/searchable-select-field"
import { Button } from "@/components/ui/button"
import { Search, CheckCircle2 } from "lucide-react"
import { formatNumber } from "@/lib/format"
import { SectionCard } from "@/components/ui/section-card"
import { toast } from "sonner"
import i18n from "@/lib/i18n"

type AssayForm = {
  item_id: string
  method: string
  purity_id: string
  final_weight_grams: number | ""
  net_gold_grams: number | ""
  result: string
  grade: string
  remarks: string
}

const initialAssay: AssayForm = {
  item_id: "",
  method: "manual",
  purity_id: "",
  final_weight_grams: "",
  net_gold_grams: "",
  result: "accepted",
  grade: "A",
  remarks: "",
}

function toAssayPayload(form: AssayForm, itemDeclaredWeight?: string | null | number) {
  const finalWeight = Number(form.final_weight_grams || 0)
  const declaredWeight = Number(itemDeclaredWeight || 0)
  return {
    method: form.method || null,
    purity_id: form.purity_id || null,
    final_weight_grams: finalWeight,
    net_gold_grams: Number(form.net_gold_grams || finalWeight),
    difference_grams: finalWeight && declaredWeight ? finalWeight - declaredWeight : null,
    result: form.result,
    grade: form.grade || null,
    remarks: form.remarks || null,
    notes: form.remarks || null,
  }
}

export function OrderInspections({ orders, receiving, purities }: { orders: any[], receiving: any, purities: any }) {
  const [assayOpen, setAssayOpen] = useState(false)
  const [selectedOrder, setSelectedOrder] = useState<any>(null)
  const [assayForm, setAssayForm] = useState<AssayForm>(initialAssay)

  const pendingItems = orders.flatMap(o => 
    (o.items || []).filter((i: any) => !i.assay_result_id).map((i: any) => ({ ...i, _order: o }))
  )

  const saveAssay = async (event: FormEvent) => {
    event.preventDefault()
    if (!assayForm.item_id || !assayForm.final_weight_grams) {
      toast.error(i18n.t("app.admin.warehouse.receiving.requests.toast.fill_required") || "Please fill required fields")
      return
    }
    const item = selectedOrder?.items.find((row: any) => row.id === assayForm.item_id)
    const ok = await receiving.addAssayResult(selectedOrder.id, assayForm.item_id, toAssayPayload(assayForm, item?.declared_weight_grams))
    if (!ok) return
    toast.success(i18n.t("app.admin.warehouse.receiving.requests.toast.inspection_saved") || "Inspection saved")
    setAssayOpen(false)
    await receiving.fetchItems(1, 100, "", { status: "received" })
  }

  const columns: Column<any>[] = [
    {
      key: "order_no",
      header: i18n.t('app.admin.warehouse.receiving.requests.field.request_no') || "Order No",
      cell: (row) => (
        <div className="flex items-center gap-2">
          <Search className="h-4 w-4 text-muted-foreground" />
          <span className="font-mono text-sm font-medium">{String(row._order.receiving_order_no)}</span>
        </div>
      ),
    },
    {
      key: "purity",
      header: i18n.t('app.admin.warehouse.receiving.requests.field.purity') || "Purity",
      cell: (row) => {
        const p = purities.items.find((x: any) => x.id === row.purity_id)
        return <span className="text-sm">{p ? (p.name_ar || p.name_en || `${p.karat}K`) : "-"}</span>
      }
    },
    {
      key: "weight",
      header: i18n.t('app.admin.warehouse.inspections.page.text_8') || "Weight",
      cell: (row) => (
        <span className="text-sm">
          - / {row.declared_weight_grams !== null ? formatNumber(row.declared_weight_grams) : "-"}
        </span>
      ),
    },
    {
      key: "actions",
      header: i18n.t('app.admin.warehouse.inspections.page.text_14') || "Actions",
      cell: (row) => (
        <div className="flex items-center gap-2">
          <button 
            onClick={() => {
              setSelectedOrder(row._order)
              setAssayForm({ ...initialAssay, item_id: row.id })
              setAssayOpen(true)
            }}
            className="text-xs px-2 py-1 bg-emerald-500/10 text-emerald-600 hover:bg-emerald-500/20 rounded transition-colors flex items-center gap-1"
          >
            <CheckCircle2 className="w-3 h-3" />
            {i18n.t('app.admin.warehouse.receiving.requests.action.inspect') || "Inspect"}
          </button>
        </div>
      )
    }
  ]

  const purityOptions = purities.items.map((p: any) => ({ value: p.id, label: p.name_ar || p.name_en || `${p.karat}K` }))
  const selectedItems = selectedOrder?.items || []

  return (
    <>
      <SectionCard title={i18n.t("app.admin.warehouse.receiving.requests.receiving_orders") || "Order Inspections"}>
        <DataTable columns={columns} data={pendingItems} rowKey={(row) => row.id} />
      </SectionCard>

      <Modal open={assayOpen} onClose={() => setAssayOpen(false)} title={i18n.t("app.admin.warehouse.receiving.requests.inspection.title") || "Inspection"} description={selectedOrder?.receiving_order_no} size="lg">
        <form className="space-y-4" onSubmit={saveAssay}>
          <div className="grid gap-4 md:grid-cols-2">
            <SelectField label={i18n.t("app.admin.warehouse.receiving.requests.field.item") || "Item"} id="item_id" name="item_id" value={assayForm.item_id} onChange={(event) => setAssayForm({ ...assayForm, item_id: event.target.value })} options={selectedItems.map((item: any) => ({ value: item.id, label: `${item.purity_id} - ${item.declared_weight_grams}g` }))} required />
            <InputField label={i18n.t("app.admin.warehouse.receiving.requests.field.method") || "Method"} id="method" name="method" value={assayForm.method} onChange={(event) => setAssayForm({ ...assayForm, method: event.target.value })} />
            <SearchableSelectField label={i18n.t("app.admin.warehouse.receiving.requests.field.measured_purity") || "Purity"} id="assay_purity" value={assayForm.purity_id} onChange={(value) => setAssayForm({ ...assayForm, purity_id: value })} options={purityOptions} placeholder={i18n.t("app.admin.warehouse.receiving.requests.placeholder.search_purity") || "Search"} />
            <InputField label={i18n.t("app.admin.warehouse.receiving.requests.field.final_weight") || "Final Weight"} id="final_weight" name="final_weight" type="number" min="0.01" step="0.01" value={assayForm.final_weight_grams} onChange={(event) => setAssayForm({ ...assayForm, final_weight_grams: event.target.value ? Number(event.target.value) : "" })} required />
            <InputField label={i18n.t("app.admin.warehouse.receiving.requests.field.net_gold") || "Net Gold"} id="net_gold" name="net_gold" type="number" min="0" step="0.01" value={assayForm.net_gold_grams} onChange={(event) => setAssayForm({ ...assayForm, net_gold_grams: event.target.value ? Number(event.target.value) : "" })} />
            <SelectField label={i18n.t("app.admin.warehouse.receiving.requests.field.result") || "Result"} id="result" name="result" value={assayForm.result} onChange={(event) => setAssayForm({ ...assayForm, result: event.target.value })} options={["accepted", "partial_accepted", "rejected", "damaged", "mismatch"].map((value) => ({ value, label: i18n.t(`app.admin.warehouse.receiving.requests.inspection_result.${value}`) || value }))} />
            <InputField label={i18n.t("app.admin.warehouse.receiving.requests.field.grade") || "Grade"} id="grade" name="grade" value={assayForm.grade} onChange={(event) => setAssayForm({ ...assayForm, grade: event.target.value })} />
          </div>
          <TextAreaField label={i18n.t("app.admin.warehouse.receiving.requests.field.remarks") || "Remarks"} id="remarks" name="remarks" value={assayForm.remarks} onChange={(event) => setAssayForm({ ...assayForm, remarks: event.target.value })} />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button type="button" variant="outline" onClick={() => setAssayOpen(false)}>{i18n.t("app.admin.warehouse.receiving.requests.action.cancel_dialog") || "Cancel"}</Button>
            <Button type="submit" isLoading={receiving.isSubmitting}>{i18n.t("app.admin.warehouse.receiving.requests.action.save_inspection") || "Save"}</Button>
          </div>
        </form>
      </Modal>
    </>
  )
}
