'use client'

import { useEffect, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Save } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { api } from "@/lib/api"
import { useSupplierShipments } from "@/hooks/useSupplierShipments"
import type { PaginatedResponse, PurchaseOrder, SupplierDTO, VaultDTO } from "@/types"
import type { SupplierShipmentCreatePayload } 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"

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

export default function CreateSupplierShipmentPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { create, isSubmitting } = useSupplierShipments()
  const purchaseOrderId = searchParams.get("purchase_order_id")
  const [linkedOrder, setLinkedOrder] = useState<PurchaseOrder | null>(null)
  const [suppliers, setSuppliers] = useState<SupplierDTO[]>([])
  const [vaults, setVaults] = useState<VaultDTO[]>([])
  const [branches, setBranches] = useState<any[]>([])
  const [form, setForm] = useState({
    purchase_order_id: "",
    supplier_id: "",
    target_vault_id: "",
    shipped_weight_grams: "",
    bar_count: "",
    carrier_name: "",
    tracking_no: "",
    insurance_provider: "",
    insurance_policy_no: "",
    shipping_cost: "",
    expected_arrival_date: "",
    notes: "",
  })

  useEffect(() => {
    Promise.all([
      api.get("/suppliers/"),
      api.get("/warehouse/vaults"),
      api.get("/branches/"),
    ])
      .then(([s, v, b]) => {
        setSuppliers(arrayPayload<SupplierDTO>(s))
        setVaults(arrayPayload<VaultDTO>(v))
        setBranches(arrayPayload<any>(b))
      })
      .catch(err => toast.error(err?.message || "Failed to load"))
  }, [])

  useEffect(() => {
    if (!purchaseOrderId) return
    api.get(`/purchase-orders/${purchaseOrderId}`)
      .then((response) => {
        const order = (response?.data ?? response) as PurchaseOrder
        const totalWeight = (order.items ?? []).reduce((sum, item) => sum + Number(item.weight_grams || 0) * Number(item.quantity || 1), 0)
        const barCount = (order.items ?? []).reduce((sum, item) => sum + Number(item.quantity || 1), 0)
        setLinkedOrder(order)
        setForm(current => ({
          ...current,
          purchase_order_id: order.id,
          supplier_id: order.supplier_id ?? current.supplier_id,
          target_vault_id: order.target_vault_id ?? current.target_vault_id,
          shipped_weight_grams: totalWeight ? String(totalWeight) : current.shipped_weight_grams,
          bar_count: barCount ? String(barCount) : current.bar_count,
          expected_arrival_date: order.expected_delivery_date ?? current.expected_arrival_date,
          notes: current.notes || order.buy_order_no,
        }))
      })
      .catch(err => toast.error(err?.response?.data?.detail || err?.message || "Failed to load purchase order"))
  }, [purchaseOrderId])

  const setField = (name: string, value: string) => {
    setForm(current => ({ ...current, [name]: value }))
  }

  const save = async () => {
    if (!form.supplier_id) { toast.error(language === "ar" ? "اختر المورد." : "Select a supplier."); return }
    const payload: SupplierShipmentCreatePayload = {
      purchase_order_id: form.purchase_order_id || undefined,
      supplier_id: form.supplier_id,
      target_vault_id: form.target_vault_id || undefined,
      shipped_weight_grams: Number(form.shipped_weight_grams) || 0,
      bar_count: Number(form.bar_count) || 0,
      carrier_name: form.carrier_name || undefined,
      tracking_no: form.tracking_no || undefined,
      insurance_provider: form.insurance_provider || undefined,
      insurance_policy_no: form.insurance_policy_no || undefined,
      shipping_cost: Number(form.shipping_cost) || 0,
      expected_arrival_date: form.expected_arrival_date || undefined,
      notes: form.notes || undefined,
    }
    try {
      const shipment = await create(payload)
      toast.success(language === "ar" ? "تم إنشاء الشحنة." : "Shipment created.")
      router.push(`/supplier-shipments/${shipment.id}`)
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to create shipment")
    }
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "إنشاء شحنة" : "Create shipment"}
        description={language === "ar" ? "أدخل بيانات شحنة المورد." : "Enter supplier shipment details."}
        breadcrumbs={[
          { label: language === "ar" ? "شحنات الموردين" : "Supplier Shipments", href: "/supplier-shipments" },
          { label: language === "ar" ? "إنشاء" : "Create" },
        ]}
      />

      <SectionCard title={language === "ar" ? "بيانات الشحنة" : "Shipment information"}>
        {linkedOrder && (
          <div className="mb-4 rounded-lg border border-gold-200 bg-gold-50/50 p-3 text-sm">
            <div className="font-semibold">{language === "ar" ? "مرتبط بأمر الشراء" : "Linked purchase order"}</div>
            <div className="mt-1 font-mono text-muted-foreground">{linkedOrder.buy_order_no}</div>
          </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"}
            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="target_vault_id"
            name="target_vault_id"
            label={language === "ar" ? "الخزنة المستهدفة" : "Target vault"}
            value={form.target_vault_id}
            onChange={e => setField("target_vault_id", e.target.value)}
            options={vaults.map(v => ({ value: v.id, label: v.name }))}
          />
          <InputField
            id="shipped_weight_grams"
            name="shipped_weight_grams"
            label={language === "ar" ? "الوزن المشحون (جم)" : "Shipped weight (g)"}
            type="number"
            min="0"
            step="0.000001"
            value={form.shipped_weight_grams}
            onChange={e => setField("shipped_weight_grams", e.target.value)}
          />
          <InputField
            id="bar_count"
            name="bar_count"
            label={language === "ar" ? "عدد السبيكات" : "Bar count"}
            type="number"
            min="0"
            value={form.bar_count}
            onChange={e => setField("bar_count", e.target.value)}
          />
          <InputField
            id="carrier_name"
            name="carrier_name"
            label={language === "ar" ? "الناقل" : "Carrier"}
            value={form.carrier_name}
            onChange={e => setField("carrier_name", e.target.value)}
          />
          <InputField
            id="tracking_no"
            name="tracking_no"
            label={language === "ar" ? "رقم التتبع" : "Tracking No"}
            value={form.tracking_no}
            onChange={e => setField("tracking_no", e.target.value)}
          />
          <InputField
            id="insurance_provider"
            name="insurance_provider"
            label={language === "ar" ? "شركة التأمين" : "Insurance provider"}
            value={form.insurance_provider}
            onChange={e => setField("insurance_provider", e.target.value)}
          />
          <InputField
            id="insurance_policy_no"
            name="insurance_policy_no"
            label={language === "ar" ? "رقم وثيقة التأمين" : "Policy number"}
            value={form.insurance_policy_no}
            onChange={e => setField("insurance_policy_no", e.target.value)}
          />
          <InputField
            id="shipping_cost"
            name="shipping_cost"
            label={language === "ar" ? "تكلفة الشحن" : "Shipping cost"}
            type="number"
            min="0"
            step="0.01"
            value={form.shipping_cost}
            onChange={e => setField("shipping_cost", e.target.value)}
          />
          <InputField
            id="expected_arrival_date"
            name="expected_arrival_date"
            label={language === "ar" ? "الوصول المتوقع" : "Expected arrival"}
            type="date"
            value={form.expected_arrival_date}
            onChange={e => setField("expected_arrival_date", 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>
        <div className="mt-4 flex justify-end gap-2">
          <Button variant="outline" onClick={() => router.back()}>{language === "ar" ? "إلغاء" : "Cancel"}</Button>
          <Button onClick={save} isLoading={isSubmitting}>
            <Save className="h-4 w-4" />
            {language === "ar" ? "حفظ" : "Save"}
          </Button>
        </div>
      </SectionCard>
    </div>
  )
}
