'use client'

import { useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import { useParams } from 'next/navigation'
import Link from 'next/link'
import { toast } from 'react-hot-toast'
import { ArrowLeft, Building2, Calendar, CircleDollarSign, Copy, FileText, Globe, Landmark, Mail, MapPin, Phone, Star, Tag, Truck, Users, XCircle } from 'lucide-react'
import ProtectedRoute from '@/components/ProtectedRoute'
import LoadingSpinner from '@/components/LoadingSpinner'
import { suppliersAPI, Supplier } from '@/lib/api/suppliers'
import { isSupplierSystemCategoryName, uniqueSupplierCategories } from '@/lib/supplierCategories'

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

function Field({ label, value, mono = false }: { label: string; value?: any; mono?: boolean }) {
  if (!value) return null
  return <div><dt className="text-sm font-medium text-gray-500">{label}</dt><dd className={`mt-1 text-sm text-gray-900 ${mono ? 'font-mono' : ''}`}>{value}</dd></div>
}

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))
}

function isSupplierSystemCategory(category: any) {
  const name = String(category?.name || '').trim().toLowerCase()
  const nameAr = String(category?.nameAr || '')
  return name === 'supplier' || name === 'suppliers' || nameAr.includes('مورد')
}

function getCategoryLabels(supplier: Supplier) {
  const categoryNames = (supplier.categories || [])
    .filter((category: any) => !isSupplierSystemCategory(category))
    .map((category: any) => category.nameAr ? `${category.name} (${category.nameAr})` : category.name)
    .filter(Boolean)

  if (categoryNames.length > 0) return categoryNames
  return supplier.customFields?.supplierCategory ? [supplier.customFields.supplierCategory] : []
}

function CategoryBadges({ labels }: { labels: string[] }) {
  if (labels.length === 0) return <span className="text-gray-400 text-sm">بدون تصنيف</span>

  return (
    <div className="flex flex-wrap gap-2">
      {labels.map((label) => (
        <span key={label} 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" />
          {label}
        </span>
      ))}
    </div>
  )
}

function SupplierDetailContent() {
  const params = useParams()
  const supplierId = params.id as string
  const [supplier, setSupplier] = useState<Supplier | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [copiedField, setCopiedField] = useState<string | null>(null)

  useEffect(() => {
    const fetchSupplier = async () => {
      setLoading(true)
      setError(null)
      try { setSupplier(await suppliersAPI.getById(supplierId)) }
      catch (err: any) { const message = err.response?.data?.message || 'Failed to load supplier'; setError(message); toast.error(message) }
      finally { setLoading(false) }
    }
    fetchSupplier()
  }, [supplierId])

  const copyToClipboard = (text: string, field: string) => {
    navigator.clipboard.writeText(text)
    setCopiedField(field)
    toast.success(`${field} copied`)
    setTimeout(() => setCopiedField(null), 1800)
  }

  if (loading) return <div className="min-h-screen bg-gray-50 flex items-center justify-center"><LoadingSpinner size="lg" message="Loading supplier details..." /></div>
  if (error || !supplier) return <div className="min-h-screen bg-gray-50 flex items-center justify-center"><div className="text-center"><XCircle className="h-16 w-16 text-red-500 mx-auto mb-4" /><h2 className="text-2xl font-bold text-gray-900 mb-2">Supplier Not Found</h2><p className="text-gray-600 mb-6">{error || 'This supplier does not exist'}</p><Link href="/suppliers" className="inline-flex items-center gap-2 px-6 py-3 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700"><ArrowLeft className="h-4 w-4" /> Back to Suppliers</Link></div></div>

  const customFields = supplier.customFields || {}
  const supplierName = supplier.companyName || supplier.name
  const contactPerson = supplier.name && supplier.name !== supplierName ? supplier.name : ''
  const supplierCategoryLabels = getSupplierCategoryLabels(supplier)
  const categoryLabels = supplierCategoryLabels

  // Additional contact persons (stored as a JSON array in customFields).
  // Safe to read even if absent / malformed: filter to objects with a name.
  const additionalContacts: Array<{
    name?: string
    position?: string
    email?: string
    phone?: string
    mobile?: string
    notes?: string
  }> = Array.isArray(customFields.additionalContacts)
    ? customFields.additionalContacts.filter(
        (c: any) => c && typeof c === 'object' && typeof c.name === 'string' && c.name.trim() !== ''
      )
    : []

  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="/suppliers" 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><div className="flex items-center gap-3"><h1 className="text-2xl font-bold text-gray-900">{supplierName}</h1><span className={`px-3 py-1 rounded-full text-xs font-medium ${supplier.status === 'ACTIVE' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}`}>{supplier.status}</span></div><p className="text-sm text-gray-600 mt-1">Supplier Management • {supplier.uniqueContactId}</p></div></div>
            </div>
          </div>
          <nav className="flex items-center gap-2 text-sm text-gray-600 mt-4"><Link href="/dashboard" className="hover:text-emerald-600">Dashboard</Link><span>/</span><Link href="/suppliers" className="hover:text-emerald-600">Suppliers</Link><span>/</span><span className="text-gray-900 font-medium">{supplierName}</span></nav>
        </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 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-1"><div className="bg-white rounded-xl shadow-sm border p-6"><div className="text-center mb-6"><div className="h-32 w-32 rounded-full bg-gradient-to-br from-emerald-600 to-emerald-700 flex items-center justify-center text-white text-4xl font-bold mx-auto mb-4">{supplierName.charAt(0).toUpperCase()}</div><h2 className="text-xl font-bold text-gray-900">{supplierName}</h2>{supplier.companyNameAr && <p className="text-gray-600 mt-1" dir="rtl">{supplier.companyNameAr}</p>}{customFields.supplierCode && <p className="text-sm text-gray-500 mt-2 font-mono">{customFields.supplierCode}</p>}</div><div className="mb-6 pb-6 border-b"><label className="text-sm font-medium text-gray-700 block mb-2">Rating</label>{renderStars(supplier.rating)}</div><div className="space-y-2">{supplier.email && <button onClick={() => copyToClipboard(supplier.email!, 'Email')} className="w-full flex items-center gap-3 px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50"><Mail className="h-5 w-5 text-gray-600" /><span className="flex-1 text-left text-sm">{supplier.email}</span><Copy className={`h-4 w-4 ${copiedField === 'Email' ? 'text-green-600' : 'text-gray-400'}`} /></button>}{(supplier.phone || supplier.mobile) && <button onClick={() => copyToClipboard((supplier.phone || supplier.mobile)!, 'Phone')} className="w-full flex items-center gap-3 px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50"><Phone className="h-5 w-5 text-gray-600" /><span className="flex-1 text-left text-sm">{supplier.phone || supplier.mobile}</span><Copy className={`h-4 w-4 ${copiedField === 'Phone' ? 'text-green-600' : 'text-gray-400'}`} /></button>}{supplier.website && <a href={supplier.website.startsWith('http') ? supplier.website : `https://${supplier.website}`} target="_blank" rel="noopener noreferrer" className="w-full flex items-center gap-3 px-4 py-3 border border-gray-200 rounded-lg hover:bg-gray-50"><Globe className="h-5 w-5 text-gray-600" /><span className="flex-1 text-left text-sm">{supplier.website}</span></a>}</div><div className="mt-6 pt-6 border-t space-y-2"><div className="flex items-center gap-2 text-sm text-gray-600"><Calendar className="h-4 w-4" /><span>Created: {new Date(supplier.createdAt).toLocaleDateString()}</span></div><div className="space-y-2"><div className="flex items-center gap-2 text-sm text-gray-600"><Tag className="h-4 w-4" /><span>Categories</span></div><CategoryBadges labels={categoryLabels} /></div></div></div></div>
          <div className="lg:col-span-2 space-y-6">
            <InfoCard icon={Building2} title="Supplier Information"><dl className="grid grid-cols-1 md:grid-cols-2 gap-4"><Field label="Supplier Name" value={supplierName} /><Field label="Arabic Name" value={supplier.companyNameAr} /><Field label="Contact Person" value={contactPerson} /><Field label="Contact Position" value={customFields.contactPosition} /><Field label="Supplier Code" value={customFields.supplierCode} mono /><div><dt className="text-sm font-medium text-gray-500">Supplier Categories</dt><dd className="mt-2"><CategoryBadges labels={categoryLabels} /></dd></div></dl></InfoCard>

            {additionalContacts.length > 0 && (
              <InfoCard icon={Users} title={`أشخاص تواصل إضافيين (${additionalContacts.length})`}>
                <div className="space-y-4">
                  {additionalContacts.map((contact, index) => (
                    <div
                      key={index}
                      className="rounded-lg border border-gray-200 bg-gray-50/50 p-4"
                    >
                      <div className="flex items-center justify-between mb-3 flex-wrap gap-2">
                        <div className="flex items-center gap-2">
                          <div className="h-8 w-8 rounded-full bg-emerald-100 flex items-center justify-center text-emerald-700 font-semibold text-sm">
                            {(contact.name || '?').charAt(0).toUpperCase()}
                          </div>
                          <div>
                            <p className="font-medium text-gray-900">{contact.name}</p>
                            {contact.position && (
                              <p className="text-xs text-gray-500">{contact.position}</p>
                            )}
                          </div>
                        </div>
                      </div>

                      <dl className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        {contact.email && (
                          <div className="flex items-center gap-2 text-sm">
                            <Mail className="h-4 w-4 text-gray-400 shrink-0" />
                            <a
                              href={`mailto:${contact.email}`}
                              className="text-emerald-700 hover:underline truncate"
                            >
                              {contact.email}
                            </a>
                          </div>
                        )}
                        {contact.phone && (
                          <div className="flex items-center gap-2 text-sm">
                            <Phone className="h-4 w-4 text-gray-400 shrink-0" />
                            <span className="text-gray-900" dir="ltr">{contact.phone}</span>
                            <span className="text-xs text-gray-500">(الهاتف)</span>
                          </div>
                        )}
                        {contact.mobile && (
                          <div className="flex items-center gap-2 text-sm">
                            <Phone className="h-4 w-4 text-gray-400 shrink-0" />
                            <span className="text-gray-900" dir="ltr">{contact.mobile}</span>
                            <span className="text-xs text-gray-500">(الموبايل)</span>
                          </div>
                        )}
                        {contact.notes && (
                          <div className="md:col-span-2 flex items-start gap-2 text-sm">
                            <FileText className="h-4 w-4 text-gray-400 shrink-0 mt-0.5" />
                            <span className="text-gray-700 whitespace-pre-wrap">{contact.notes}</span>
                          </div>
                        )}
                      </dl>
                    </div>
                  ))}
                </div>
              </InfoCard>
            )}
            <InfoCard icon={Landmark} title="Legal & Financial"><dl className="grid grid-cols-1 md:grid-cols-2 gap-4"><Field label="Tax Number" value={supplier.taxNumber} mono /><Field label="Commercial Register" value={supplier.commercialRegister} mono /><Field label="Payment Terms" value={customFields.paymentTerms} /><Field label="Bank Name" value={customFields.bankName} /><Field label="Bank Account / IBAN" value={customFields.bankAccount} mono /></dl>{!supplier.taxNumber && !supplier.commercialRegister && !customFields.paymentTerms && !customFields.bankName && !customFields.bankAccount && <div className="text-center py-6 text-gray-500"><CircleDollarSign className="h-10 w-10 mx-auto mb-2 text-gray-300" /><p>No financial information available</p></div>}</InfoCard>
            <InfoCard icon={MapPin} title="Address & Notes"><dl className="grid grid-cols-1 md:grid-cols-2 gap-4"><Field label="Address" value={supplier.address} /><Field label="City" value={supplier.city} /><Field label="Country" value={supplier.country} /><Field label="Postal Code" value={supplier.postalCode} /></dl>{customFields.notes && <div className="mt-6 pt-6 border-t"><div className="flex items-center gap-2 mb-2"><FileText className="h-4 w-4 text-gray-500" /><h4 className="font-medium text-gray-900">Notes</h4></div><p className="text-sm text-gray-700 whitespace-pre-wrap">{customFields.notes}</p></div>}</InfoCard>
          </div>
        </div>
      </main>
    </div>
  )
}

function InfoCard({ icon: Icon, title, children }: { icon: any; title: string; children: ReactNode }) {
  return <div className="bg-white rounded-xl shadow-sm border p-6"><div className="flex items-center gap-2 mb-4"><Icon className="h-5 w-5 text-emerald-600" /><h3 className="text-lg font-semibold text-gray-900">{title}</h3></div>{children}</div>
}

export default function SupplierDetailPage() {
  return <ProtectedRoute><SupplierDetailContent /></ProtectedRoute>
}
