'use client'

import { useState } from "react"
import { useRouter } from "next/navigation"
import { ArrowLeft, Save } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { useOutboundOrders } from "@/hooks/useLogistics"
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"

const sourceTypeOptions = [
  { value: "platform_allocation", label: "Platform allocation" },
  { value: "purchase_return", label: "Purchase return" },
  { value: "transfer_order", label: "Transfer order" },
  { value: "delivery_request", label: "Delivery request" },
  { value: "manual", label: "Manual" },
]

export default function CreateOutboundOrderPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const { create, isSubmitting } = useOutboundOrders()
  const [form, setForm] = useState({
    source_type: "platform_allocation",
    source_id: "",
    target_vault_id: "",
    target_branch_id: "",
    bar_count: "0",
    total_weight_grams: "0",
    carrier_name: "",
    tracking_no: "",
    notes: "",
  })

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

  const validate = () => {
    if (!form.source_type) { toast.error(language === "ar" ? "اختر نوع المصدر." : "Select a source type."); return false }
    if (!form.source_id) { toast.error(language === "ar" ? "أدخل معرف المصدر." : "Enter the source ID."); return false }
    if (Number(form.bar_count) < 0) { toast.error(language === "ar" ? "عدد السبائك غير صحيح." : "Bar count is invalid."); return false }
    if (Number(form.total_weight_grams) < 0) { toast.error(language === "ar" ? "الوزن غير صحيح." : "Weight is invalid."); return false }
    return true
  }

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (!validate()) return
    try {
      const created = await create({
        source_type: form.source_type,
        source_id: form.source_id,
        target_vault_id: form.target_vault_id || null,
        target_branch_id: form.target_branch_id || null,
        bar_count: Number(form.bar_count),
        total_weight_grams: form.total_weight_grams,
        carrier_name: form.carrier_name || null,
        tracking_no: form.tracking_no || null,
        notes: form.notes || null,
      })
      toast.success(language === "ar" ? "تم إنشاء أمر الصرف المخزني." : "Stock issue order created.")
      router.push(`/outbound-orders/${created.id}`)
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to create outbound order")
    }
  }

  return (
    <form className="space-y-6" onSubmit={handleSubmit}>
      <PageHeader
        title={language === "ar" ? "أمر صرف مخزني جديد" : "New Stock Issue Order"}
        description={language === "ar" ? "أنشئ أمر صرف مخزني من مصدر تشغيلي ثم اعتمده وجهزه وأرسله." : "Create a stock issue order from an operational source, then approve, pick, and dispatch it."}
        breadcrumbs={[
          { label: language === "ar" ? "أوامر الصرف المخزني" : "Stock Issue Orders", href: "/outbound-orders" },
          { label: language === "ar" ? "جديد" : "New" },
        ]}
        actions={
          <div className="flex gap-2">
            <Button type="button" variant="outline" onClick={() => router.push("/outbound-orders")}>
              <ArrowLeft className="h-4 w-4" />
              {language === "ar" ? "رجوع" : "Back"}
            </Button>
            <Button type="submit" isLoading={isSubmitting}>
              <Save className="h-4 w-4" />
              {language === "ar" ? "حفظ" : "Create"}
            </Button>
          </div>
        }
      />

      <SectionCard title={language === "ar" ? "المصدر" : "Source"}>
        <div className="grid gap-4 md:grid-cols-2">
          <SelectField
            id="source_type"
            name="source_type"
            label={language === "ar" ? "نوع المصدر" : "Source type"}
            required
            value={form.source_type}
            options={sourceTypeOptions}
            onChange={event => setField("source_type", event.target.value)}
          />
          <InputField
            id="source_id"
            name="source_id"
            label={language === "ar" ? "معرف المصدر" : "Source ID"}
            required
            value={form.source_id}
            onChange={event => setField("source_id", event.target.value)}
            placeholder="UUID"
          />
        </div>
      </SectionCard>

      <SectionCard title={language === "ar" ? "الوجهة والكمية" : "Destination and Quantity"}>
        <div className="grid gap-4 md:grid-cols-2">
          <InputField id="target_vault_id" name="target_vault_id" label={language === "ar" ? "معرف الخزنة المستهدفة" : "Target vault ID"} value={form.target_vault_id} onChange={event => setField("target_vault_id", event.target.value)} placeholder="Optional UUID" />
          <InputField id="target_branch_id" name="target_branch_id" label={language === "ar" ? "معرف الفرع المستهدف" : "Target branch ID"} value={form.target_branch_id} onChange={event => setField("target_branch_id", event.target.value)} placeholder="Optional UUID" />
          <InputField id="bar_count" name="bar_count" type="number" min={0} label={language === "ar" ? "عدد السبائك" : "Bar count"} value={form.bar_count} onChange={event => setField("bar_count", event.target.value)} />
          <InputField id="total_weight_grams" name="total_weight_grams" type="number" min={0} step="0.001" label={language === "ar" ? "إجمالي الوزن بالجرام" : "Total weight grams"} value={form.total_weight_grams} onChange={event => setField("total_weight_grams", event.target.value)} />
        </div>
      </SectionCard>

      <SectionCard title={language === "ar" ? "النقل" : "Carrier"}>
        <div className="grid gap-4 md:grid-cols-2">
          <InputField id="carrier_name" name="carrier_name" label={language === "ar" ? "شركة النقل" : "Carrier name"} value={form.carrier_name} onChange={event => setField("carrier_name", event.target.value)} />
          <InputField id="tracking_no" name="tracking_no" label={language === "ar" ? "رقم التتبع" : "Tracking number"} value={form.tracking_no} onChange={event => setField("tracking_no", event.target.value)} />
          <div className="md:col-span-2">
            <TextAreaField id="notes" name="notes" label={language === "ar" ? "ملاحظات" : "Notes"} value={form.notes} onChange={event => setField("notes", event.target.value)} rows={4} />
          </div>
        </div>
      </SectionCard>
    </form>
  )
}
