'use client'

import { useCallback, useEffect, useMemo, useState } from 'react'
import type { FormEvent } from 'react'
import Link from 'next/link'
import { toast } from 'react-hot-toast'
import { ArrowLeft, BadgeCheck, Building2, CircleDollarSign, Download, Edit, Eye, Filter, Landmark, Loader2,Shield, Mail, Phone, Plus, Search, Star, Tag, Trash2, Truck, X } from 'lucide-react'
import ProtectedRoute from '@/components/ProtectedRoute'
import LoadingSpinner from '@/components/LoadingSpinner'
import Modal from '@/components/Modal'
import { useAuth } from '@/contexts/AuthContext'
import SupplierCategorySelector from '@/components/suppliers/SupplierCategorySelector'
import { suppliersAPI, Supplier, SupplierFilters, CreateSupplierData, UpdateSupplierData, SupplierStats } from '@/lib/api/suppliers'
import { DEFAULT_SUPPLIER_CATEGORIES, isSupplierSystemCategoryName, uniqueSupplierCategories } from '@/lib/supplierCategories'

type SupplierAdditionalContact = {
  name: string
  position: string
  email: string
  phone: string
  mobile: string
  notes: string
}

const emptyAdditionalContact = (): SupplierAdditionalContact => ({
  name: '',
  position: '',
  email: '',
  phone: '',
  mobile: '',
  notes: '',
})

type SupplierFormState = {
  companyName: string
  companyNameAr: string
  name: string
  email: string
  phone: string
  mobile: string
  website: string
  taxNumber: string
  commercialRegister: string
  address: string
  city: string
  country: string
  supplierCode: string
  supplierCategories: string[]
  paymentTerms: string
  bankName: string
  bankAccount: string
  contactPosition: string
  notes: string
  tags: string
  rating: number
  status: string
  additionalContacts: SupplierAdditionalContact[]
}

function getSupplierCategoryLabels(supplier: Supplier): string[] {
  const customFields = supplier.customFields || {}
  if (Array.isArray(customFields.supplierCategories)) {
    const categories = uniqueSupplierCategories(customFields.supplierCategories)
    if (categories.length > 0) return categories
  }
  if (customFields.supplierCategory) return [String(customFields.supplierCategory)]
  return uniqueSupplierCategories((supplier.categories || [])
    .filter((category: any) => !isSupplierSystemCategoryName(category.name, category.nameAr))
    .map((category: any) => category.nameAr ? `${category.name} (${category.nameAr})` : category.name))
}

const buildInitialForm = (supplier?: Supplier): SupplierFormState => {
  const customFields = supplier?.customFields || {}

  // Hydrate additional contacts from customFields, tolerating bad/missing data.
  const rawAdditional = Array.isArray(customFields.additionalContacts)
    ? customFields.additionalContacts
    : []
  const additionalContacts: SupplierAdditionalContact[] = rawAdditional.map((c: any) => ({
    name: typeof c?.name === 'string' ? c.name : '',
    position: typeof c?.position === 'string' ? c.position : '',
    email: typeof c?.email === 'string' ? c.email : '',
    phone: typeof c?.phone === 'string' ? c.phone : '',
    mobile: typeof c?.mobile === 'string' ? c.mobile : '',
    notes: typeof c?.notes === 'string' ? c.notes : '',
  }))

  return {
    companyName: supplier?.companyName || supplier?.name || '',
    companyNameAr: supplier?.companyNameAr || '',
    name: supplier?.name || '',
    email: supplier?.email || '',
    phone: supplier?.phone || '',
    mobile: supplier?.mobile || '',
    website: supplier?.website || '',
    taxNumber: supplier?.taxNumber || '',
    commercialRegister: supplier?.commercialRegister || '',
    address: supplier?.address || '',
    city: supplier?.city || '',
    country: supplier?.country || 'Syria',
    supplierCode: customFields.supplierCode || '',
    supplierCategories: supplier ? getSupplierCategoryLabels(supplier) : [],
    paymentTerms: customFields.paymentTerms || '',
    bankName: customFields.bankName || '',
    bankAccount: customFields.bankAccount || '',
    contactPosition: customFields.contactPosition || '',
    notes: customFields.notes || '',
    tags: supplier?.tags?.join(', ') || '',
    rating: supplier?.rating || 0,
    status: supplier?.status || 'ACTIVE',
    additionalContacts,
  }
}

function renderRating(rating?: number) {
  if (!rating) return <span className="text-sm text-gray-400">بدون تقييم</span>
  return <div className="flex items-center gap-0.5">{[1, 2, 3, 4, 5].map((star) => <Star key={star} className={`h-4 w-4 ${star <= rating ? 'fill-yellow-400 text-yellow-400' : 'text-gray-300'}`} />)}</div>
}

function getSupplierName(supplier: Supplier) {
  return supplier.companyName || supplier.name || '-'
}

function getContactPerson(supplier: Supplier) {
  const supplierName = getSupplierName(supplier)
  if (!supplier.name || supplier.name === supplierName) return '-'
  return supplier.name
}

function SupplierForm({ supplier, submitting, availableCategories, onCancel, onSubmit }: {
  supplier?: Supplier
  submitting?: boolean
  availableCategories?: string[]
  onCancel: () => void
  onSubmit: (data: any) => Promise<void>
}) {
  const isEdit = !!supplier
  const [form, setForm] = useState<SupplierFormState>(buildInitialForm(supplier))
  const [formErrors, setFormErrors] = useState<Record<string, string>>({})

  useEffect(() => {
    setForm(buildInitialForm(supplier))
    setFormErrors({})
  }, [supplier])

  const updateField = (field: keyof SupplierFormState, value: string | number) => setForm((prev) => ({ ...prev, [field]: value }))
  const optional = (value: string) => value.trim() || undefined

  // Helpers for additional contact persons.
  const updateAdditionalContact = (
    index: number,
    field: keyof SupplierAdditionalContact,
    value: string
  ) => {
    setForm((prev) => {
      const next = prev.additionalContacts.map((contact, i) =>
        i === index ? { ...contact, [field]: value } : contact
      )
      return { ...prev, additionalContacts: next }
    })
  }
  const addAdditionalContact = () => {
    setForm((prev) => ({
      ...prev,
      additionalContacts: [...prev.additionalContacts, emptyAdditionalContact()],
    }))
  }
  const removeAdditionalContact = (index: number) => {
    setForm((prev) => ({
      ...prev,
      additionalContacts: prev.additionalContacts.filter((_, i) => i !== index),
    }))
  }

  const validate = () => {
    const errors: Record<string, string> = {}
    if (!form.companyName.trim() && !form.name.trim()) errors.companyName = 'اسم المورد أو مسؤول التواصل مطلوب'
    if (form.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errors.email = 'صيغة البريد الإلكتروني غير صحيحة'

    form.additionalContacts.forEach((contact, index) => {
      // A row is "filled" if any field has content; once filled, name and a valid email become rules.
      const hasAnyValue = Object.values(contact).some((value) => value.trim() !== '')
      if (hasAnyValue && !contact.name.trim()) {
        errors[`additionalContact_${index}_name`] = 'اسم شخص التواصل مطلوب'
      }
      if (contact.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contact.email)) {
        errors[`additionalContact_${index}_email`] = 'صيغة البريد الإلكتروني غير صحيحة'
      }
    })

    setFormErrors(errors)
    return Object.keys(errors).length === 0
  }

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault()
    if (!validate()) return
    const companyName = form.companyName.trim() || form.name.trim()
    const contactName = form.name.trim() || companyName
    const supplierCategories = uniqueSupplierCategories(form.supplierCategories)

    // Drop entirely-empty rows; trim every field on the rest.
    const cleanedAdditionalContacts = form.additionalContacts
      .map((contact) => ({
        name: contact.name.trim(),
        position: contact.position.trim(),
        email: contact.email.trim(),
        phone: contact.phone.trim(),
        mobile: contact.mobile.trim(),
        notes: contact.notes.trim(),
      }))
      .filter((contact) => Object.values(contact).some((value) => value !== ''))

    const payload: any = {
      name: contactName,
      companyName,
      companyNameAr: optional(form.companyNameAr),
      email: optional(form.email),
      phone: optional(form.phone),
      mobile: optional(form.mobile),
      website: optional(form.website),
      taxNumber: optional(form.taxNumber),
      commercialRegister: optional(form.commercialRegister),
      address: optional(form.address),
      city: optional(form.city),
      country: form.country.trim() || 'Syria',
      source: 'SUPPLIER_MODULE',
      rating: form.rating || undefined,
      tags: form.tags.split(',').map((tag) => tag.trim()).filter(Boolean),
      customFields: {
        supplierCode: form.supplierCode.trim(),
        supplierCategories,
        supplierCategory: supplierCategories[0] || '',
        paymentTerms: form.paymentTerms.trim(),
        bankName: form.bankName.trim(),
        bankAccount: form.bankAccount.trim(),
        contactPosition: form.contactPosition.trim(),
        notes: form.notes.trim(),
        additionalContacts: cleanedAdditionalContacts,
      },
    }
    if (isEdit) payload.status = form.status
    await onSubmit(payload)
  }

  const inputClass = 'w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500 bg-white text-gray-900'

  return (
    <form onSubmit={handleSubmit} className="space-y-6" noValidate>
      <div>
        <h3 className="text-lg font-semibold text-gray-900 mb-4">بيانات المورد الأساسية</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div><label className="block text-sm font-medium text-gray-700 mb-1">اسم المورد / الشركة <span className="text-red-500">*</span></label><input value={form.companyName} onChange={(e) => updateField('companyName', e.target.value)} className={inputClass} placeholder="اسم الشركة أو المورد" />{formErrors.companyName && <p className="text-red-500 text-xs mt-1">{formErrors.companyName}</p>}</div>
          <div><label className="block text-sm font-medium text-gray-700 mb-1">اسم المورد بالعربي</label><input value={form.companyNameAr} onChange={(e) => updateField('companyNameAr', e.target.value)} className={inputClass} dir="rtl" /></div>
          <div><label className="block text-sm font-medium text-gray-700 mb-1">مسؤول التواصل الرئيسي</label><input value={form.name} onChange={(e) => updateField('name', e.target.value)} className={inputClass} placeholder="اسم الشخص المسؤول" /></div>
          <div><label className="block text-sm font-medium text-gray-700 mb-1">الصفة / المنصب</label><input value={form.contactPosition} onChange={(e) => updateField('contactPosition', e.target.value)} className={inputClass} placeholder="Sales Manager, Accountant..." /></div>
        </div>
      </div>
      <div className="pt-6 border-t">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">التصنيف والاعتماد</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div><label className="block text-sm font-medium text-gray-700 mb-1">كود المورد</label><input value={form.supplierCode} onChange={(e) => updateField('supplierCode', e.target.value)} className={`${inputClass} font-mono`} placeholder="SUP-001" /></div>
          <div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700 mb-1">تصنيف المورد</label><SupplierCategorySelector selectedCategories={form.supplierCategories} availableCategories={availableCategories} onChange={(supplierCategories) => setForm((prev) => ({ ...prev, supplierCategories }))} /></div>
          {isEdit && <div><label className="block text-sm font-medium text-gray-700 mb-1">الحالة</label><select value={form.status} onChange={(e) => updateField('status', e.target.value)} className={inputClass}><option value="ACTIVE">Active</option><option value="INACTIVE">Inactive</option><option value="BLOCKED">Blocked</option></select></div>}
        </div>
        <div className="mt-4"><label className="block text-sm font-medium text-gray-700 mb-2">التقييم</label><div className="flex items-center gap-2">{[1, 2, 3, 4, 5].map((star) => <button key={star} type="button" onClick={() => updateField('rating', star)} className="focus:outline-none"><Star className={`h-7 w-7 ${star <= form.rating ? 'fill-yellow-400 text-yellow-400' : 'text-gray-300 hover:text-yellow-200'}`} /></button>)}{form.rating > 0 && <button type="button" onClick={() => updateField('rating', 0)} className="text-sm text-gray-500 hover:text-gray-700">مسح التقييم</button>}</div></div>
      </div>
      <div className="pt-6 border-t"><h3 className="text-lg font-semibold text-gray-900 mb-4">بيانات التواصل</h3><div className="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label className="block text-sm font-medium text-gray-700 mb-1">البريد الإلكتروني</label><input type="email" value={form.email} onChange={(e) => updateField('email', e.target.value)} className={inputClass} />{formErrors.email && <p className="text-red-500 text-xs mt-1">{formErrors.email}</p>}</div><div><label className="block text-sm font-medium text-gray-700 mb-1">الهاتف</label><input value={form.phone} onChange={(e) => updateField('phone', e.target.value)} className={inputClass} /></div><div><label className="block text-sm font-medium text-gray-700 mb-1">الموبايل</label><input value={form.mobile} onChange={(e) => updateField('mobile', e.target.value)} className={inputClass} /></div><div><label className="block text-sm font-medium text-gray-700 mb-1">الموقع الإلكتروني</label><input value={form.website} onChange={(e) => updateField('website', e.target.value)} className={inputClass} /></div></div></div>

      <div className="pt-6 border-t">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900">أشخاص تواصل إضافيين</h3>
          <button
            type="button"
            onClick={addAdditionalContact}
            className="flex items-center gap-2 px-3 py-1.5 text-sm bg-emerald-50 text-emerald-700 border border-emerald-200 rounded-lg hover:bg-emerald-100"
          >
            <Plus className="h-4 w-4" />
            إضافة شخص تواصل
          </button>
        </div>

        {form.additionalContacts.length === 0 ? (
          <p className="text-sm text-gray-500">
            لم تتم إضافة أشخاص تواصل إضافيين. اضغط "إضافة شخص تواصل" لإضافة المزيد.
          </p>
        ) : (
          <div className="space-y-4">
            {form.additionalContacts.map((contact, index) => (
              <div
                key={index}
                className="rounded-xl border border-gray-200 bg-gray-50/50 p-4 relative"
              >
                <div className="flex items-center justify-between mb-3">
                  <h4 className="text-sm font-semibold text-gray-700">
                    شخص تواصل #{index + 1}
                  </h4>
                  <button
                    type="button"
                    onClick={() => removeAdditionalContact(index)}
                    className="flex items-center gap-1 text-sm text-red-600 hover:text-red-700"
                    aria-label="حذف شخص التواصل"
                  >
                    <Trash2 className="h-4 w-4" />
                    حذف
                  </button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      الاسم <span className="text-red-500">*</span>
                    </label>
                    <input
                      value={contact.name}
                      onChange={(e) =>
                        updateAdditionalContact(index, 'name', e.target.value)
                      }
                      className={inputClass}
                      placeholder="اسم الشخص"
                    />
                    {formErrors[`additionalContact_${index}_name`] && (
                      <p className="text-red-500 text-xs mt-1">
                        {formErrors[`additionalContact_${index}_name`]}
                      </p>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      الصفة / المنصب
                    </label>
                    <input
                      value={contact.position}
                      onChange={(e) =>
                        updateAdditionalContact(index, 'position', e.target.value)
                      }
                      className={inputClass}
                      placeholder="Sales Manager, Accountant..."
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      البريد الإلكتروني
                    </label>
                    <input
                      type="email"
                      value={contact.email}
                      onChange={(e) =>
                        updateAdditionalContact(index, 'email', e.target.value)
                      }
                      className={inputClass}
                    />
                    {formErrors[`additionalContact_${index}_email`] && (
                      <p className="text-red-500 text-xs mt-1">
                        {formErrors[`additionalContact_${index}_email`]}
                      </p>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      الهاتف
                    </label>
                    <input
                      value={contact.phone}
                      onChange={(e) =>
                        updateAdditionalContact(index, 'phone', e.target.value)
                      }
                      className={inputClass}
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      الموبايل
                    </label>
                    <input
                      value={contact.mobile}
                      onChange={(e) =>
                        updateAdditionalContact(index, 'mobile', e.target.value)
                      }
                      className={inputClass}
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      ملاحظات
                    </label>
                    <input
                      value={contact.notes}
                      onChange={(e) =>
                        updateAdditionalContact(index, 'notes', e.target.value)
                      }
                      className={inputClass}
                      placeholder="ملاحظات إضافية..."
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
      <div className="pt-6 border-t"><h3 className="text-lg font-semibold text-gray-900 mb-4">بيانات مالية وقانونية</h3><div className="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label className="block text-sm font-medium text-gray-700 mb-1">الرقم الضريبي</label><input value={form.taxNumber} onChange={(e) => updateField('taxNumber', e.target.value)} className={`${inputClass} font-mono`} /></div><div><label className="block text-sm font-medium text-gray-700 mb-1">السجل التجاري</label><input value={form.commercialRegister} onChange={(e) => updateField('commercialRegister', e.target.value)} className={`${inputClass} font-mono`} /></div><div><label className="block text-sm font-medium text-gray-700 mb-1">شروط الدفع</label><input value={form.paymentTerms} onChange={(e) => updateField('paymentTerms', e.target.value)} className={inputClass} placeholder="Net 30, Cash..." /></div><div><label className="block text-sm font-medium text-gray-700 mb-1">اسم البنك</label><input value={form.bankName} onChange={(e) => updateField('bankName', e.target.value)} className={inputClass} /></div><div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700 mb-1">الحساب البنكي / IBAN</label><input value={form.bankAccount} onChange={(e) => updateField('bankAccount', e.target.value)} className={`${inputClass} font-mono`} /></div></div></div>
      <div className="pt-6 border-t"><h3 className="text-lg font-semibold text-gray-900 mb-4">العنوان والملاحظات</h3><div className="grid grid-cols-1 md:grid-cols-2 gap-4"><div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700 mb-1">العنوان</label><input value={form.address} onChange={(e) => updateField('address', e.target.value)} className={inputClass} /></div><div><label className="block text-sm font-medium text-gray-700 mb-1">المدينة</label><input value={form.city} onChange={(e) => updateField('city', e.target.value)} className={inputClass} /></div><div><label className="block text-sm font-medium text-gray-700 mb-1">الدولة</label><input value={form.country} onChange={(e) => updateField('country', e.target.value)} className={inputClass} /></div><div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700 mb-1">Tags</label><input value={form.tags} onChange={(e) => updateField('tags', e.target.value)} className={inputClass} placeholder="tag1, tag2" /></div><div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700 mb-1">ملاحظات</label><textarea value={form.notes} onChange={(e) => updateField('notes', e.target.value)} className={inputClass} rows={3} /></div></div></div>
      <div className="flex items-center justify-end gap-3 pt-6 border-t"><button type="button" onClick={onCancel} className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50" disabled={submitting}>إلغاء</button><button type="submit" className="flex items-center gap-2 px-6 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 disabled:opacity-50" disabled={submitting}>{submitting ? <><Loader2 className="h-4 w-4 animate-spin" /> جاري الحفظ...</> : (isEdit ? 'تحديث المورد' : 'إنشاء المورد')}</button></div>
    </form>
  )
}

function SuppliersContent() {
  const [suppliers, setSuppliers] = useState<Supplier[]>([])
  const [stats, setStats] = useState<SupplierStats>({ total: 0, active: 0, inactive: 0, blocked: 0 })
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [total, setTotal] = useState(0)
  const pageSize = 10
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedStatus, setSelectedStatus] = useState('all')
  const [selectedCategory, setSelectedCategory] = useState('all')
  const [showAdvancedFilters, setShowAdvancedFilters] = useState(false)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [showArchiveDialog, setShowArchiveDialog] = useState(false)
  const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null)
  const [submitting, setSubmitting] = useState(false)
  const [exporting, setExporting] = useState(false)
    const { hasPermission } = useAuth()

  const canViewSupplier = hasPermission('suppliers', 'view')
  const canCreateSupplier = hasPermission('suppliers', 'create')
  const canEditSupplier = hasPermission('suppliers', 'edit')
  const canDeleteSupplier = hasPermission('suppliers', 'delete')
  const canExportSupplier = hasPermission('suppliers', 'export')

  const availableCategories = useMemo(() => uniqueSupplierCategories([...DEFAULT_SUPPLIER_CATEGORIES, ...suppliers.flatMap(getSupplierCategoryLabels)]), [suppliers])

  const buildFilters = useCallback((): SupplierFilters => {
    const filters: SupplierFilters = { page: currentPage, pageSize }
    if (searchTerm) filters.search = searchTerm
    if (selectedStatus !== 'all') filters.status = selectedStatus
    if (selectedCategory !== 'all') filters.category = selectedCategory
    return filters
  }, [currentPage, searchTerm, selectedStatus, selectedCategory])

  const fetchStats = useCallback(async () => {
    if (!canViewSupplier) return
    try { setStats(await suppliersAPI.getStats()) } catch { setStats({ total: 0, active: 0, inactive: 0, blocked: 0 }) }
  }, [canViewSupplier])

  const fetchSuppliers = useCallback(async () => {
    if (!canViewSupplier) {
      setLoading(false)
      return
    }

    setLoading(true)
    setError(null)
    try {
      const data = await suppliersAPI.getAll(buildFilters())
      setSuppliers(data.suppliers)
      setTotal(data.total)
      setTotalPages(data.totalPages)
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to load suppliers'
      setError(message)
      toast.error(message)
    } finally {
      setLoading(false)
    }
  }, [buildFilters, canViewSupplier])

  useEffect(() => { fetchStats() }, [fetchStats])
  useEffect(() => { const t = setTimeout(() => { setCurrentPage(1); fetchSuppliers() }, 500); return () => clearTimeout(t) }, [searchTerm])
  useEffect(() => { fetchSuppliers() }, [currentPage, selectedStatus, selectedCategory])

  const refresh = async () => Promise.all([fetchSuppliers(), fetchStats()])

  const handleCreate = async (data: CreateSupplierData) => {
    setSubmitting(true)
    try { await suppliersAPI.create(data); toast.success('تم إنشاء المورد بنجاح'); setShowCreateModal(false); await refresh() }
    catch (err: any) { toast.error(err.response?.data?.message || 'فشل إنشاء المورد'); throw err }
    finally { setSubmitting(false) }
  }

  const handleEdit = async (data: UpdateSupplierData) => {
    if (!selectedSupplier) return
    setSubmitting(true)
    try { await suppliersAPI.update(selectedSupplier.id, data); toast.success('تم تحديث المورد بنجاح'); setShowEditModal(false); setSelectedSupplier(null); await refresh() }
    catch (err: any) { toast.error(err.response?.data?.message || 'فشل تحديث المورد'); throw err }
    finally { setSubmitting(false) }
  }

  const handleArchive = async () => {
    if (!selectedSupplier) return
    setSubmitting(true)
    try { await suppliersAPI.archive(selectedSupplier.id, 'Archived from Supplier Management'); toast.success('تم حذف المورد بنجاح'); setShowArchiveDialog(false); setSelectedSupplier(null); await refresh() }
    catch (err: any) { toast.error(err.response?.data?.message || 'فشل حذف المورد') }
    finally { setSubmitting(false) }
  }

  const handleExport = async () => {
    setExporting(true)
    try {
      const filters = buildFilters(); delete filters.page; delete filters.pageSize
      const blob = await suppliersAPI.export(filters)
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `suppliers_${new Date().toISOString().split('T')[0]}.xlsx`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      toast.success('تم تصدير الموردين بنجاح')
    } catch (err: any) { toast.error(err.response?.data?.message || 'فشل تصدير الموردين') }
    finally { setExporting(false) }
  }

    if (!canViewSupplier) {
    return (
      <div className="min-h-screen bg-gray-50">
        <header className="bg-white shadow-sm border-b">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
            <div className="flex items-center gap-4">
              <Link href="/dashboard" className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
                <ArrowLeft className="h-5 w-5 text-gray-600" />
              </Link>
              <div className="flex items-center gap-3">
                <div className="bg-emerald-100 p-2 rounded-lg">
                  <Truck className="h-6 w-6 text-emerald-600" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">إدارة الموردين</h1>
                  <p className="text-sm text-gray-600">Supplier Management</p>
                </div>
              </div>
            </div>
          </div>
        </header>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Link href="/dashboard" className="p-2 hover:bg-gray-100 rounded-lg transition-colors"><ArrowLeft className="h-5 w-5 text-gray-600" /></Link>
              <div className="flex items-center gap-3"><div className="bg-emerald-100 p-2 rounded-lg"><Truck className="h-6 w-6 text-emerald-600" /></div><div><h1 className="text-2xl font-bold text-gray-900">إدارة الموردين</h1><p className="text-sm text-gray-600">Supplier Management</p></div></div>
            </div>
            <div className="flex items-center gap-3">
              {canExportSupplier && (
                <button
                  onClick={handleExport}
                  className="flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                  disabled={exporting}
                >
                  {exporting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
                  Export
                </button>
              )}

              {canCreateSupplier && (
                <button
                  onClick={() => setShowCreateModal(true)}
                  className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700"
                >
                  إضافة مورد
                </button>
              )}
              
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8"><StatCard label="Total Suppliers" value={stats.total} icon={Truck} iconClass="bg-emerald-100 text-emerald-600" /><StatCard label="Active Suppliers" value={stats.active} icon={BadgeCheck} iconClass="bg-green-100 text-green-600" /><StatCard label="Inactive / Blocked" value={stats.inactive + stats.blocked} icon={X} iconClass="bg-orange-100 text-orange-600" /><StatCard label="This Page" value={suppliers.length} icon={Landmark} iconClass="bg-purple-100 text-purple-600" /></div>

        <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200 mb-6"><div className="space-y-4"><div className="flex flex-col md:flex-row gap-4"><div className="flex-1 relative"><Search className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" /><input type="text" placeholder="Search suppliers (name, phone, email, tax number...)" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full pr-10 pl-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500 bg-white text-gray-900" /></div><select value={selectedStatus} onChange={(e) => setSelectedStatus(e.target.value)} className="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500 bg-white text-gray-900"><option value="all">All Status</option><option value="ACTIVE">Active</option><option value="INACTIVE">Inactive</option><option value="BLOCKED">Blocked</option></select><button onClick={() => setShowAdvancedFilters(!showAdvancedFilters)} className={`flex items-center gap-2 px-4 py-3 border rounded-lg ${showAdvancedFilters ? 'bg-emerald-50 border-emerald-300 text-emerald-700' : 'border-gray-300 text-gray-700 hover:bg-gray-50'}`}><Filter className="h-4 w-4" /> Advanced</button></div>{showAdvancedFilters && <div className="pt-4 border-t border-gray-200 grid grid-cols-1 md:grid-cols-3 gap-4"><div><label className="block text-sm font-medium text-gray-700 mb-2">تصنيف المورد</label><select value={selectedCategory} onChange={(e) => setSelectedCategory(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500 bg-white text-gray-900"><option value="all">كل التصنيفات</option>{availableCategories.map((category) => <option key={category} value={category}>{category}</option>)}</select></div><div className="flex items-end"><button onClick={() => { setSearchTerm(''); setSelectedStatus('all'); setSelectedCategory('all'); setCurrentPage(1) }} className="w-full px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">Clear All Filters</button></div></div>}</div></div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          {loading ? <div className="p-12"><LoadingSpinner size="lg" message="Loading suppliers..." /></div> : error ? <div className="p-12 text-center"><p className="text-red-600 mb-4">{error}</p><button onClick={fetchSuppliers} className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700">Retry</button></div> : suppliers.length === 0 ? <div className="p-12 text-center"><Truck className="h-12 w-12 text-gray-400 mx-auto mb-4" /><p className="text-gray-600 mb-4">لا يوجد موردين مطابقين للفلاتر الحالية</p><button onClick={() => setShowCreateModal(true)} className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700">إضافة مورد</button></div> : <><div className="overflow-x-auto"><table className="w-full"><thead className="bg-gray-50 border-b border-gray-200"><tr><th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Supplier</th><th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Contact Info</th><th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Category</th><th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Rating</th><th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Status</th><th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Actions</th></tr></thead><tbody className="divide-y divide-gray-200">{suppliers.map((supplier) => { const customFields = supplier.customFields || {}; const categoryLabels = getSupplierCategoryLabels(supplier); return <tr key={supplier.id} className="hover:bg-gray-50"><td className="px-6 py-4"><div className="flex items-center gap-3"><div className="h-10 w-10 rounded-full bg-gradient-to-br from-emerald-600 to-emerald-700 flex items-center justify-center text-white font-bold">{getSupplierName(supplier).charAt(0).toUpperCase()}</div><div><p className="font-semibold text-gray-900">{getSupplierName(supplier)}</p>{customFields.supplierCode && <p className="text-xs text-gray-500 font-mono">{customFields.supplierCode}</p>}{supplier.companyNameAr && <p className="text-sm text-gray-600" dir="rtl">{supplier.companyNameAr}</p>}</div></div></td><td className="px-6 py-4"><div className="space-y-1">{getContactPerson(supplier) !== '-' && <div className="flex items-center gap-2 text-sm text-gray-700"><Building2 className="h-4 w-4" />{getContactPerson(supplier)}{customFields.contactPosition && <span className="text-xs text-gray-400">({customFields.contactPosition})</span>}</div>}{supplier.email && <div className="flex items-center gap-2 text-sm text-gray-600"><Mail className="h-4 w-4" />{supplier.email}</div>}{(supplier.phone || supplier.mobile) && <div className="flex items-center gap-2 text-sm text-gray-600"><Phone className="h-4 w-4" />{supplier.phone || supplier.mobile}</div>}</div></td><td className="px-6 py-4"><div className="flex flex-wrap gap-1">{categoryLabels.length > 0 ? categoryLabels.map((category) => <span key={category} className="inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700"><Tag className="h-3 w-3" />{category}</span>) : <span className="text-sm text-gray-400">بدون تصنيف</span>}{customFields.paymentTerms && <div className="flex items-center gap-1 text-xs text-gray-500 w-full mt-1"><CircleDollarSign className="h-3 w-3" />{customFields.paymentTerms}</div>}</div></td><td className="px-6 py-4">{renderRating(supplier.rating)}</td><td className="px-6 py-4"><span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${supplier.status === 'ACTIVE' ? 'bg-green-100 text-green-700' : supplier.status === 'BLOCKED' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-700'}`}>{supplier.status === 'ACTIVE' ? 'Active' : supplier.status}</span></td><td className="px-6 py-4">
            <div className="flex items-center gap-2">
              {canViewSupplier && (
                <Link
                  href={`/suppliers/${supplier.id}`}
                  className="p-2 hover:bg-blue-50 text-blue-600 rounded-lg"
                  title="View"
                >
                  <Eye className="h-4 w-4" />
                </Link>
              )}

              {canEditSupplier && (
                <button
                  onClick={() => { setSelectedSupplier(supplier); setShowEditModal(true) }}
                  className="p-2 hover:bg-green-50 text-green-600 rounded-lg"
                  title="Edit"
                >
                  <Edit className="h-4 w-4" />
                </button>
              )}

              {canDeleteSupplier && (
                <button
                  onClick={() => { setSelectedSupplier(supplier); setShowArchiveDialog(true) }}
                  className="p-2 hover:bg-red-50 text-red-600 rounded-lg"
                  title="Archive"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              )}
            </div>
        </td></tr> })}</tbody></table></div><div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between"><p className="text-sm text-gray-600">Showing <span className="font-semibold">{((currentPage - 1) * pageSize) + 1}</span> to <span className="font-semibold">{Math.min(currentPage * pageSize, total)}</span> of <span className="font-semibold">{total}</span> suppliers</p><div className="flex items-center gap-2"><button onClick={() => setCurrentPage(currentPage - 1)} disabled={currentPage === 1} className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50">Previous</button>{Array.from({ length: Math.min(5, totalPages) }, (_, i) => i + 1).map((page) => <button key={page} onClick={() => setCurrentPage(page)} className={`px-4 py-2 rounded-lg ${currentPage === page ? 'bg-emerald-600 text-white' : 'border border-gray-300 text-gray-700 hover:bg-gray-50'}`}>{page}</button>)}<button onClick={() => setCurrentPage(currentPage + 1)} disabled={currentPage === totalPages} className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50">Next</button></div></div></>}
        </div>
      </main>

      {canCreateSupplier && (
        <Modal isOpen={showCreateModal} onClose={() => setShowCreateModal(false)} title="إضافة مورد جديد" size="xl">
          <SupplierForm
            key="create-supplier"
            availableCategories={availableCategories}
            onSubmit={handleCreate}
            onCancel={() => setShowCreateModal(false)}
            submitting={submitting}
          />
        </Modal>
      )}

      {canEditSupplier && (
        <Modal isOpen={showEditModal} onClose={() => { setShowEditModal(false); setSelectedSupplier(null) }} title="تعديل المورد" size="xl">
          <SupplierForm
            key={selectedSupplier?.id || 'edit-supplier'}
            supplier={selectedSupplier || undefined}
            availableCategories={availableCategories}
            onSubmit={handleEdit}
            onCancel={() => { setShowEditModal(false); setSelectedSupplier(null) }}
            submitting={submitting}
          />
        </Modal>
      )}
      
      {canDeleteSupplier && showArchiveDialog && selectedSupplier && <div className="fixed inset-0 z-50 overflow-y-auto"><div className="fixed inset-0 bg-black bg-opacity-50" onClick={() => setShowArchiveDialog(false)} /><div className="flex min-h-screen items-center justify-center p-4"><div className="relative bg-white rounded-xl shadow-2xl p-6 max-w-md w-full"><div className="flex items-center gap-4 mb-4"><div className="bg-red-100 p-3 rounded-full"><Trash2 className="h-6 w-6 text-red-600" /></div><div><h3 className="text-lg font-bold text-gray-900">حذف المورد</h3><p className="text-sm text-gray-600">سيتم إخفاء المورد من قائمة الموردين</p></div></div><p className="text-gray-700 mb-6">هل أنت متأكد من حذف <span className="font-semibold">{getSupplierName(selectedSupplier)}</span>؟</p><div className="flex items-center justify-end gap-3"><button onClick={() => { setShowArchiveDialog(false); setSelectedSupplier(null) }} className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50" disabled={submitting}>إلغاء</button><button onClick={handleArchive} className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50" disabled={submitting}>{submitting ? <><Loader2 className="h-4 w-4 animate-spin" /> جاري الحذف...</> : 'حذف المورد'}</button></div></div></div></div>}
    </div>
  )
}

function StatCard({ label, value, icon: Icon, iconClass }: { label: string; value: number; icon: any; iconClass: string }) {
  return <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200"><div className="flex items-center justify-between"><div><p className="text-sm text-gray-600">{label}</p><p className="text-3xl font-bold text-gray-900 mt-1">{value}</p></div><div className={`p-3 rounded-lg ${iconClass}`}><Icon className="h-8 w-8" /></div></div></div>
}

export default function SuppliersPage() {
  return <ProtectedRoute><SuppliersContent /></ProtectedRoute>
}
