'use client'

import { type FormEvent, useCallback, useEffect, useMemo, useState } from "react"
import { CheckCircle2, CircleSlash, Eye, PackageCheck, Plus, RefreshCw, Search, ShieldAlert, Truck, XCircle } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "react-i18next"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import type { SupplierDTO } from "@/types"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { KpiCard } from "@/components/ui/kpi-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { Button } from "@/components/ui/button"
import { Modal } from "@/components/ui/modal"
import { InputField, SelectField, TextAreaField } from "@/components/ui/FormFields"
import { formatDateTime } from "@/lib/format"

type SupplierForm = {
  name_ar: string
  name_en: string
  supplier_type: string
  risk_level: string
  city: string
  address: string
  contact_name: string
  contact_phone: string
  contact_email: string
  website: string
  registration_number: string
  tax_number: string
  license_number: string
  payment_terms: string
  delivery_terms: string
  lead_time_days: string
  minimum_order_amount: string
  credit_limit: string
  rating: string
  is_lbma_certified: boolean
  notes: string
}

const emptyForm: SupplierForm = {
  name_ar: "",
  name_en: "",
  supplier_type: "dealer",
  risk_level: "medium",
  city: "",
  address: "",
  contact_name: "",
  contact_phone: "",
  contact_email: "",
  website: "",
  registration_number: "",
  tax_number: "",
  license_number: "",
  payment_terms: "",
  delivery_terms: "",
  lead_time_days: "",
  minimum_order_amount: "",
  credit_limit: "",
  rating: "",
  is_lbma_certified: false,
  notes: "",
}

const supplierTypeLabel: Record<string, { en: string; ar: string }> = {
  refinery: { en: "Refinery", ar: "مصفاة" },
  dealer: { en: "Dealer", ar: "تاجر" },
  bank: { en: "Bank", ar: "بنك" },
  individual: { en: "Individual", ar: "فرد" },
  government: { en: "Government", ar: "جهة حكومية" },
}

const riskLabel: Record<string, { en: string; ar: string }> = {
  low: { en: "Low", ar: "منخفض" },
  medium: { en: "Medium", ar: "متوسط" },
  high: { en: "High", ar: "عال" },
  critical: { en: "Critical", ar: "حرج" },
}

const supplierStatusLabel: Record<string, { en: string; ar: string }> = {
  pending_approval: { en: "Pending approval", ar: "بانتظار الاعتماد" },
  active: { en: "Active", ar: "نشط" },
  inactive: { en: "Inactive", ar: "غير نشط" },
  suspended: { en: "Suspended", ar: "معلق" },
  blocked: { en: "Blocked", ar: "محظور" },
}

function unwrap<T>(value: any): T {
  return value && typeof value === "object" && "data" in value ? value.data : (value as T)
}

function supplierName(supplier: SupplierDTO, language: "ar" | "en") {
  return (language === "ar" ? supplier.name_ar : supplier.name_en) || supplier.name_ar || supplier.name_en || supplier.supplier_no
}

function statusTone(status: string): StatusTone {
  if (status === "active") return "success"
  if (status === "pending_approval") return "pending"
  if (status === "blocked" || status === "suspended") return "danger"
  return "neutral"
}

function riskTone(risk?: string | null): StatusTone {
  if (risk === "low") return "success"
  if (risk === "medium") return "warning"
  if (risk === "high" || risk === "critical") return "danger"
  return "neutral"
}

export default function SuppliersPage() {
  const { i18n } = useTranslation()
  const language = i18n.language.startsWith("ar") ? "ar" : "en"
  const [suppliers, setSuppliers] = useState<SupplierDTO[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [createOpen, setCreateOpen] = useState(false)
  const [selected, setSelected] = useState<SupplierDTO | null>(null)
  const [blockTarget, setBlockTarget] = useState<SupplierDTO | null>(null)
  const [blockReason, setBlockReason] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [search, setSearch] = useState("")
  const [statusFilter, setStatusFilter] = useState("")
  const [typeFilter, setTypeFilter] = useState("")
  const [form, setForm] = useState<SupplierForm>(emptyForm)
  const supplierTypeOptions = useMemo(() => Object.entries(supplierTypeLabel).map(([value, label]) => ({ value, label: label[language] })), [language])
  const riskOptions = useMemo(() => Object.entries(riskLabel).map(([value, label]) => ({ value, label: label[language] })), [language])

  const refresh = useCallback(async () => {
    setIsLoading(true)
    setError(null)
    try {
      const res = await api.get(ENDPOINTS.SUPPLIERS.LIST, { params: { skip: 0, limit: 500 } })
      const data = unwrap<SupplierDTO[]>(res)
      setSuppliers(Array.isArray(data) ? data : [])
    } catch (err: any) {
      setError(err?.response?.data?.detail || err?.message || "Failed to load suppliers")
    } finally {
      setIsLoading(false)
    }
  }, [])

  useEffect(() => { refresh() }, [refresh])

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase()
    return suppliers.filter(supplier => {
      if (statusFilter && supplier.status !== statusFilter) return false
      if (typeFilter && supplier.supplier_type !== typeFilter) return false
      if (!q) return true
      return [
        supplier.supplier_no,
        supplier.name_ar,
        supplier.name_en,
        supplier.contact_name,
        supplier.contact_phone,
        supplier.contact_email,
        supplier.registration_number,
        supplier.tax_number,
        supplier.license_number,
      ].some(value => value?.toLowerCase().includes(q))
    })
  }, [search, statusFilter, suppliers, typeFilter])

  const metrics = useMemo(() => ({
    approvedActive: suppliers.filter(s => s.is_approved && s.status === "active" && !s.is_blocked).length,
    pending: suppliers.filter(s => s.status === "pending_approval").length,
    blocked: suppliers.filter(s => s.is_blocked || s.status === "blocked").length,
    lbma: suppliers.filter(s => s.is_lbma_certified).length,
  }), [suppliers])

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

  const buildPayload = () => ({
    name_ar: form.name_ar,
    name_en: form.name_en || null,
    supplier_type: form.supplier_type,
    risk_level: form.risk_level || null,
    city: form.city || null,
    address: form.address || null,
    contact_name: form.contact_name || null,
    contact_phone: form.contact_phone || null,
    contact_email: form.contact_email || null,
    website: form.website || null,
    registration_number: form.registration_number || null,
    tax_number: form.tax_number || null,
    license_number: form.license_number || null,
    payment_terms: form.payment_terms || null,
    delivery_terms: form.delivery_terms || null,
    lead_time_days: form.lead_time_days ? Number(form.lead_time_days) : null,
    minimum_order_amount: form.minimum_order_amount || null,
    credit_limit: form.credit_limit || null,
    rating: form.rating || null,
    is_lbma_certified: form.is_lbma_certified,
    notes: form.notes || null,
  })

  const handleCreate = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (!form.name_ar.trim()) {
      toast.error(language === "ar" ? "اسم المورد بالعربية مطلوب." : "Arabic supplier name is required.")
      return
    }
    setIsSubmitting(true)
    try {
      await api.post(ENDPOINTS.SUPPLIERS.CREATE, buildPayload())
      toast.success(language === "ar" ? "تم إنشاء المورد بانتظار الاعتماد." : "Supplier created and waiting for approval.")
      setCreateOpen(false)
      setForm(emptyForm)
      await refresh()
    } catch (err: any) {
      toast.error(err?.response?.data?.message || err?.response?.data?.detail || err?.message || "Failed to create supplier")
    } finally {
      setIsSubmitting(false)
    }
  }

  const approveSupplier = async (supplier: SupplierDTO) => {
    setIsSubmitting(true)
    try {
      await api.post(ENDPOINTS.SUPPLIERS.APPROVE(supplier.id), {})
      toast.success(language === "ar" ? "تم اعتماد المورد." : "Supplier approved.")
      await refresh()
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to approve supplier")
    } finally {
      setIsSubmitting(false)
    }
  }

  const unblockSupplier = async (supplier: SupplierDTO) => {
    setIsSubmitting(true)
    try {
      await api.post(ENDPOINTS.SUPPLIERS.UNBLOCK(supplier.id), {})
      toast.success(language === "ar" ? "تم إلغاء حظر المورد." : "Supplier unblocked.")
      await refresh()
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to unblock supplier")
    } finally {
      setIsSubmitting(false)
    }
  }

  const blockSupplier = async () => {
    if (!blockTarget) return
    setIsSubmitting(true)
    try {
      await api.post(ENDPOINTS.SUPPLIERS.BLOCK(blockTarget.id), { reason: blockReason || null })
      toast.success(language === "ar" ? "تم حظر المورد." : "Supplier blocked.")
      setBlockTarget(null)
      setBlockReason("")
      await refresh()
    } catch (err: any) {
      toast.error(err?.response?.data?.detail || err?.message || "Failed to block supplier")
    } finally {
      setIsSubmitting(false)
    }
  }

  const columns: Column<SupplierDTO>[] = [
    {
      key: "supplier",
      header: language === "ar" ? "المورد" : "Supplier",
      cell: supplier => (
        <div>
          <div className="font-semibold">{supplierName(supplier, language)}</div>
          <div className="font-mono text-[11px] text-muted-foreground">{supplier.supplier_no}</div>
        </div>
      ),
    },
    {
      key: "type",
      header: language === "ar" ? "النوع" : "Type",
      cell: supplier => (
        <div className="flex flex-wrap gap-1.5">
          <StatusBadge tone="info" size="sm">{supplierTypeLabel[supplier.supplier_type]?.[language] ?? supplier.supplier_type}</StatusBadge>
          {supplier.is_lbma_certified && <StatusBadge tone="gold" size="sm">LBMA</StatusBadge>}
        </div>
      ),
    },
    {
      key: "contact",
      header: language === "ar" ? "التواصل" : "Contact",
      cell: supplier => (
        <div className="space-y-0.5 text-xs">
          <div>{supplier.contact_name || "-"}</div>
          <div className="text-muted-foreground">{supplier.contact_phone || supplier.contact_email || "-"}</div>
        </div>
      ),
    },
    {
      key: "terms",
      header: language === "ar" ? "شروط اللوجستيات" : "Logistics Terms",
      cell: supplier => (
        <div className="space-y-0.5 text-xs">
          <div>{supplier.lead_time_days != null ? `${supplier.lead_time_days} ${language === "ar" ? "يوم" : "days"}` : "-"}</div>
          <div className="text-muted-foreground">{supplier.delivery_terms || supplier.payment_terms || "-"}</div>
        </div>
      ),
    },
    {
      key: "risk",
      header: language === "ar" ? "المخاطر" : "Risk",
      cell: supplier => <StatusBadge tone={riskTone(supplier.risk_level)}>{supplier.risk_level ? riskLabel[supplier.risk_level]?.[language] ?? supplier.risk_level : "-"}</StatusBadge>,
    },
    {
      key: "status",
      header: language === "ar" ? "الحالة" : "Status",
      cell: supplier => <StatusBadge tone={statusTone(supplier.status)}>{supplierStatusLabel[supplier.status]?.[language] ?? supplier.status}</StatusBadge>,
    },
    {
      key: "created",
      header: language === "ar" ? "تاريخ الإنشاء" : "Created",
      cell: supplier => <span className="text-xs">{supplier.created_at ? formatDateTime(supplier.created_at) : "-"}</span>,
    },
    {
      key: "actions",
      header: language === "ar" ? "الإجراء" : "Action",
      align: "end",
      cell: supplier => (
        <div className="flex flex-wrap justify-end gap-2">
          <Button size="sm" variant="outline" onClick={event => { event.stopPropagation(); setSelected(supplier) }}>
            <Eye className="h-3.5 w-3.5" />
            {language === "ar" ? "عرض" : "View"}
          </Button>
          {!supplier.is_approved && supplier.status === "pending_approval" && (
            <Button size="sm" variant="outline" disabled={isSubmitting} onClick={event => { event.stopPropagation(); approveSupplier(supplier) }}>
              <CheckCircle2 className="h-3.5 w-3.5" />
              {language === "ar" ? "اعتماد" : "Approve"}
            </Button>
          )}
          {supplier.is_blocked ? (
            <Button size="sm" variant="outline" disabled={isSubmitting} onClick={event => { event.stopPropagation(); unblockSupplier(supplier) }}>
              <CircleSlash className="h-3.5 w-3.5" />
              {language === "ar" ? "إلغاء الحظر" : "Unblock"}
            </Button>
          ) : (
            <Button size="sm" variant="danger" disabled={isSubmitting} onClick={event => { event.stopPropagation(); setBlockTarget(supplier) }}>
              <XCircle className="h-3.5 w-3.5" />
              {language === "ar" ? "حظر" : "Block"}
            </Button>
          )}
        </div>
      ),
    },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "الموردون" : "Suppliers"}
        description={language === "ar" ? "مصدر الموردين المعتمدين لطلبات الشراء وأوامر الشراء والشحنات والاستلام." : "Approved supplier master for purchase requests, purchase orders, shipments, receiving, and returns."}
        breadcrumbs={[
          { label: language === "ar" ? "المخزون واللوجستيات" : "Inventory & Logistics", href: "/inventory-logistics" },
          { label: language === "ar" ? "الموردون" : "Suppliers" },
        ]}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={refresh} disabled={isLoading}>
              <RefreshCw className="h-4 w-4" />
            </Button>
            <Button onClick={() => setCreateOpen(true)}>
              <Plus className="h-4 w-4" />
              {language === "ar" ? "مورد جديد" : "New supplier"}
            </Button>
          </div>
        }
      />

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label={language === "ar" ? "موردون نشطون" : "Active approved"} value={String(metrics.approvedActive)} icon={Truck} tone="gold" accent />
        <KpiCard label={language === "ar" ? "بانتظار الاعتماد" : "Pending approval"} value={String(metrics.pending)} icon={PackageCheck} tone="warning" />
        <KpiCard label={language === "ar" ? "محظورون" : "Blocked"} value={String(metrics.blocked)} icon={ShieldAlert} tone="danger" />
        <KpiCard label={language === "ar" ? "معتمد LBMA" : "LBMA certified"} value={String(metrics.lbma)} icon={CheckCircle2} tone="success" />
      </div>

      <SectionCard title={language === "ar" ? "البحث والتصفية" : "Search and Filters"}>
        <div className="grid gap-3 lg:grid-cols-[1fr_220px_220px]">
          <label className="relative">
            <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <input
              className="w-full rounded-lg border border-border bg-background py-2.5 pl-9 pr-3 text-sm"
              placeholder={language === "ar" ? "ابحث بالاسم أو الرقم أو الترخيص أو التواصل" : "Search by name, number, license, tax, or contact"}
              value={search}
              onChange={event => setSearch(event.target.value)}
            />
          </label>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={statusFilter} onChange={event => setStatusFilter(event.target.value)}>
            <option value="">{language === "ar" ? "كل الحالات" : "All statuses"}</option>
            <option value="pending_approval">{language === "ar" ? "بانتظار الاعتماد" : "Pending approval"}</option>
            <option value="active">{language === "ar" ? "نشط" : "Active"}</option>
            <option value="inactive">{language === "ar" ? "غير نشط" : "Inactive"}</option>
            <option value="suspended">{language === "ar" ? "معلق" : "Suspended"}</option>
            <option value="blocked">{language === "ar" ? "محظور" : "Blocked"}</option>
          </select>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={typeFilter} onChange={event => setTypeFilter(event.target.value)}>
            <option value="">{language === "ar" ? "كل الأنواع" : "All types"}</option>
            {supplierTypeOptions.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
          </select>
        </div>
      </SectionCard>

      <SectionCard title={language === "ar" ? "قائمة الموردين" : "Suppliers"} padded={false}>
        {error && <div className="m-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">{error}</div>}
        {isLoading ? (
          <div className="flex h-52 items-center justify-center">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
          </div>
        ) : (
          <DataTable
            columns={columns}
            data={filtered}
            rowKey={supplier => supplier.id}
            onRowClick={setSelected}
            empty={<div className="text-center text-sm text-muted-foreground">{language === "ar" ? "لا يوجد موردون." : "No suppliers."}</div>}
          />
        )}
      </SectionCard>

      <Modal open={createOpen} onClose={() => setCreateOpen(false)} title={language === "ar" ? "مورد جديد" : "New Supplier"} description={language === "ar" ? "سيظهر المورد في الشراء بعد الاعتماد." : "The supplier becomes usable in purchasing after approval."} size="lg">
        <form onSubmit={handleCreate} className="space-y-5">
          <div className="grid gap-4 sm:grid-cols-2">
            <InputField id="name_ar" name="name_ar" label={language === "ar" ? "الاسم بالعربية" : "Arabic Name"} required value={form.name_ar} onChange={event => setField("name_ar", event.target.value)} />
            <InputField id="name_en" name="name_en" label={language === "ar" ? "الاسم بالإنجليزية" : "English Name"} value={form.name_en} onChange={event => setField("name_en", event.target.value)} />
            <SelectField id="supplier_type" name="supplier_type" label={language === "ar" ? "نوع المورد" : "Supplier Type"} value={form.supplier_type} onChange={event => setField("supplier_type", event.target.value)} options={supplierTypeOptions} />
            <SelectField id="risk_level" name="risk_level" label={language === "ar" ? "مستوى المخاطر" : "Risk Level"} value={form.risk_level} onChange={event => setField("risk_level", event.target.value)} options={riskOptions} />
            <InputField id="contact_name" name="contact_name" label={language === "ar" ? "مسؤول التواصل" : "Contact Name"} value={form.contact_name} onChange={event => setField("contact_name", event.target.value)} />
            <InputField id="contact_phone" name="contact_phone" label={language === "ar" ? "هاتف التواصل" : "Contact Phone"} value={form.contact_phone} onChange={event => setField("contact_phone", event.target.value)} />
            <InputField id="contact_email" name="contact_email" label={language === "ar" ? "بريد التواصل" : "Contact Email"} value={form.contact_email} onChange={event => setField("contact_email", event.target.value)} />
            <InputField id="website" name="website" label={language === "ar" ? "الموقع الإلكتروني" : "Website"} value={form.website} onChange={event => setField("website", event.target.value)} />
            <InputField id="registration_number" name="registration_number" label={language === "ar" ? "رقم التسجيل" : "Registration Number"} value={form.registration_number} onChange={event => setField("registration_number", event.target.value)} />
            <InputField id="tax_number" name="tax_number" label={language === "ar" ? "الرقم الضريبي" : "Tax Number"} value={form.tax_number} onChange={event => setField("tax_number", event.target.value)} />
            <InputField id="license_number" name="license_number" label={language === "ar" ? "رقم الترخيص" : "License Number"} value={form.license_number} onChange={event => setField("license_number", event.target.value)} />
            <InputField id="city" name="city" label={language === "ar" ? "المدينة" : "City"} value={form.city} onChange={event => setField("city", event.target.value)} />
            <InputField id="lead_time_days" name="lead_time_days" type="number" min={0} label={language === "ar" ? "مدة التوريد بالأيام" : "Lead Time Days"} value={form.lead_time_days} onChange={event => setField("lead_time_days", event.target.value)} />
            <InputField id="rating" name="rating" type="number" min={0} max={5} step="0.1" label={language === "ar" ? "التقييم" : "Rating"} value={form.rating} onChange={event => setField("rating", event.target.value)} />
            <InputField id="minimum_order_amount" name="minimum_order_amount" type="number" min={0} step="0.01" label={language === "ar" ? "الحد الأدنى للطلب" : "Minimum Order Amount"} value={form.minimum_order_amount} onChange={event => setField("minimum_order_amount", event.target.value)} />
            <InputField id="credit_limit" name="credit_limit" type="number" min={0} step="0.01" label={language === "ar" ? "حد الائتمان" : "Credit Limit"} value={form.credit_limit} onChange={event => setField("credit_limit", event.target.value)} />
            <InputField id="payment_terms" name="payment_terms" label={language === "ar" ? "شروط الدفع" : "Payment Terms"} value={form.payment_terms} onChange={event => setField("payment_terms", event.target.value)} />
            <InputField id="delivery_terms" name="delivery_terms" label={language === "ar" ? "شروط التسليم" : "Delivery Terms"} value={form.delivery_terms} onChange={event => setField("delivery_terms", event.target.value)} />
            <div className="sm:col-span-2">
              <TextAreaField id="address" name="address" label={language === "ar" ? "العنوان" : "Address"} rows={2} value={form.address} onChange={event => setField("address", event.target.value)} />
            </div>
            <div className="sm:col-span-2">
              <TextAreaField id="notes" name="notes" label={language === "ar" ? "ملاحظات" : "Notes"} rows={2} value={form.notes} onChange={event => setField("notes", event.target.value)} />
            </div>
            <label className="flex items-center gap-2 rounded-lg border border-border p-3 text-sm">
              <input type="checkbox" checked={form.is_lbma_certified} onChange={event => setField("is_lbma_certified", event.target.checked)} />
              {language === "ar" ? "معتمد LBMA" : "LBMA certified"}
            </label>
          </div>
          <div className="flex justify-end gap-2">
            <Button type="button" variant="outline" onClick={() => setCreateOpen(false)}>{language === "ar" ? "إلغاء" : "Cancel"}</Button>
            <Button type="submit" isLoading={isSubmitting}>{language === "ar" ? "إنشاء" : "Create"}</Button>
          </div>
        </form>
      </Modal>

      <Modal open={Boolean(selected)} onClose={() => setSelected(null)} title={selected ? supplierName(selected, language) : ""} description={selected?.supplier_no} size="lg">
        {selected && (
          <div className="grid gap-3 sm:grid-cols-2">
            <Info label={language === "ar" ? "الحالة" : "Status"} value={supplierStatusLabel[selected.status]?.[language] ?? selected.status} />
            <Info label={language === "ar" ? "المخاطر" : "Risk"} value={selected.risk_level ? riskLabel[selected.risk_level]?.[language] ?? selected.risk_level : "-"} />
            <Info label={language === "ar" ? "التواصل" : "Contact"} value={[selected.contact_name, selected.contact_phone, selected.contact_email].filter(Boolean).join(" | ") || "-"} />
            <Info label={language === "ar" ? "الموقع" : "Location"} value={[selected.city, selected.address].filter(Boolean).join(" - ") || "-"} />
            <Info label={language === "ar" ? "التسجيل" : "Registration"} value={selected.registration_number || "-"} />
            <Info label={language === "ar" ? "الضريبة" : "Tax"} value={selected.tax_number || "-"} />
            <Info label={language === "ar" ? "الترخيص" : "License"} value={selected.license_number || "-"} />
            <Info label={language === "ar" ? "مدة التوريد" : "Lead Time"} value={selected.lead_time_days != null ? `${selected.lead_time_days} ${language === "ar" ? "يوم" : "days"}` : "-"} />
            <Info label={language === "ar" ? "شروط الدفع" : "Payment Terms"} value={selected.payment_terms || "-"} />
            <Info label={language === "ar" ? "شروط التسليم" : "Delivery Terms"} value={selected.delivery_terms || "-"} />
            <Info label={language === "ar" ? "حد الائتمان" : "Credit Limit"} value={selected.credit_limit || "-"} />
            <Info label={language === "ar" ? "التقييم" : "Rating"} value={selected.rating || "-"} />
            <div className="sm:col-span-2">
              <Info label={language === "ar" ? "ملاحظات" : "Notes"} value={selected.notes || "-"} />
            </div>
          </div>
        )}
      </Modal>

      <Modal open={Boolean(blockTarget)} onClose={() => setBlockTarget(null)} title={language === "ar" ? "حظر المورد" : "Block Supplier"} description={blockTarget ? supplierName(blockTarget, language) : undefined} size="sm">
        <div className="space-y-4">
          <TextAreaField id="block_reason" name="block_reason" label={language === "ar" ? "سبب الحظر" : "Block Reason"} rows={3} value={blockReason} onChange={event => setBlockReason(event.target.value)} />
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setBlockTarget(null)}>{language === "ar" ? "إلغاء" : "Cancel"}</Button>
            <Button variant="danger" onClick={blockSupplier} isLoading={isSubmitting}>{language === "ar" ? "حظر" : "Block"}</Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}

function Info({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg border border-border p-3 text-sm">
      <div className="text-xs font-medium uppercase text-muted-foreground">{label}</div>
      <div className="mt-1 font-medium">{value}</div>
    </div>
  )
}
