'use client'

import { useEffect, useState } from 'react'
import { AlertTriangle, Plus, ChevronDown, ChevronUp } from 'lucide-react'
import { apiFetch } from '@/lib/api'
import { useDashboardI18n } from '@/components/I18nProvider'

// ─── i18n ─────────────────────────────────────────────────────────────────────

const copy = {
  en: {
    heading: 'Complaints',
    subtitle: 'Manage customer complaints and escalations',
    newComplaint: 'New complaint',
    filterStatus: 'Status',
    filterSeverity: 'Severity',
    allStatuses: 'All statuses',
    allSeverities: 'All severities',
    statusOpen: 'Open',
    statusInvestigating: 'Investigating',
    statusResolved: 'Resolved',
    statusClosed: 'Closed',
    sevL1: 'Level 1',
    sevL2: 'Level 2',
    sevL3: 'Level 3',
    noComplaints: 'No complaints found',
    category: 'Category',
    subject: 'Subject',
    reservation: 'Reservation',
    date: 'Date',
    status: 'Status',
    severity: 'Severity',
    details: 'Details',
    description: 'Description',
    notes: 'Notes',
    resolution: 'Resolution',
    updateStatus: 'Update status',
    saving: 'Saving…',
    save: 'Save',
    cancel: 'Cancel',
    createTitle: 'Create complaint',
    fieldReservationId: 'Reservation ID (optional)',
    fieldCategory: 'Category',
    fieldSeverity: 'Severity',
    fieldSubject: 'Subject',
    fieldDescription: 'Description (optional)',
    create: 'Create',
    creating: 'Creating…',
    errorLoad: 'Failed to load complaints',
    errorCreate: 'Failed to create complaint',
    errorUpdate: 'Failed to update complaint',
    categories: {
      BOOKING: 'Booking', PICKUP: 'Pickup', VEHICLE_CLEANLINESS: 'Vehicle Cleanliness',
      VEHICLE_CONDITION: 'Vehicle Condition', STAFF_SERVICE: 'Staff Service', PRICING: 'Pricing',
      DEPOSIT: 'Deposit', INSURANCE: 'Insurance', DAMAGE_CLAIM: 'Damage Claim',
      RETURN_PROCESS: 'Return Process', COMMUNICATION: 'Communication',
      ROADSIDE_ASSISTANCE: 'Roadside Assistance', BILLING: 'Billing', OTHER: 'Other',
    } as Record<string, string>,
  },
  fr: {
    heading: 'Plaintes',
    subtitle: 'Gérez les plaintes et escalades clients',
    newComplaint: 'Nouvelle plainte',
    filterStatus: 'Statut',
    filterSeverity: 'Sévérité',
    allStatuses: 'Tous les statuts',
    allSeverities: 'Toutes les sévérités',
    statusOpen: 'Ouvert',
    statusInvestigating: 'En cours',
    statusResolved: 'Résolu',
    statusClosed: 'Fermé',
    sevL1: 'Niveau 1',
    sevL2: 'Niveau 2',
    sevL3: 'Niveau 3',
    noComplaints: 'Aucune plainte trouvée',
    category: 'Catégorie',
    subject: 'Sujet',
    reservation: 'Réservation',
    date: 'Date',
    status: 'Statut',
    severity: 'Sévérité',
    details: 'Détails',
    description: 'Description',
    notes: 'Notes',
    resolution: 'Résolution',
    updateStatus: 'Mettre à jour le statut',
    saving: 'Enregistrement…',
    save: 'Enregistrer',
    cancel: 'Annuler',
    createTitle: 'Créer une plainte',
    fieldReservationId: 'ID de réservation (optionnel)',
    fieldCategory: 'Catégorie',
    fieldSeverity: 'Sévérité',
    fieldSubject: 'Sujet',
    fieldDescription: 'Description (optionnel)',
    create: 'Créer',
    creating: 'Création…',
    errorLoad: 'Échec du chargement des plaintes',
    errorCreate: 'Échec de la création de la plainte',
    errorUpdate: 'Échec de la mise à jour de la plainte',
    categories: {
      BOOKING: 'Réservation', PICKUP: 'Prise en charge', VEHICLE_CLEANLINESS: 'Propreté du véhicule',
      VEHICLE_CONDITION: 'État du véhicule', STAFF_SERVICE: 'Service du personnel', PRICING: 'Tarification',
      DEPOSIT: 'Dépôt de garantie', INSURANCE: 'Assurance', DAMAGE_CLAIM: 'Réclamation dommages',
      RETURN_PROCESS: 'Processus de retour', COMMUNICATION: 'Communication',
      ROADSIDE_ASSISTANCE: 'Assistance routière', BILLING: 'Facturation', OTHER: 'Autre',
    } as Record<string, string>,
  },
  ar: {
    heading: 'الشكاوى',
    subtitle: 'إدارة شكاوى العملاء والتصعيدات',
    newComplaint: 'شكوى جديدة',
    filterStatus: 'الحالة',
    filterSeverity: 'الخطورة',
    allStatuses: 'جميع الحالات',
    allSeverities: 'جميع مستويات الخطورة',
    statusOpen: 'مفتوح',
    statusInvestigating: 'قيد التحقيق',
    statusResolved: 'تم الحل',
    statusClosed: 'مغلق',
    sevL1: 'المستوى 1',
    sevL2: 'المستوى 2',
    sevL3: 'المستوى 3',
    noComplaints: 'لا توجد شكاوى',
    category: 'الفئة',
    subject: 'الموضوع',
    reservation: 'الحجز',
    date: 'التاريخ',
    status: 'الحالة',
    severity: 'الخطورة',
    details: 'التفاصيل',
    description: 'الوصف',
    notes: 'ملاحظات',
    resolution: 'الحل',
    updateStatus: 'تحديث الحالة',
    saving: 'جار الحفظ…',
    save: 'حفظ',
    cancel: 'إلغاء',
    createTitle: 'إنشاء شكوى',
    fieldReservationId: 'رقم الحجز (اختياري)',
    fieldCategory: 'الفئة',
    fieldSeverity: 'الخطورة',
    fieldSubject: 'الموضوع',
    fieldDescription: 'الوصف (اختياري)',
    create: 'إنشاء',
    creating: 'جار الإنشاء…',
    errorLoad: 'فشل تحميل الشكاوى',
    errorCreate: 'فشل إنشاء الشكوى',
    errorUpdate: 'فشل تحديث الشكوى',
    categories: {
      BOOKING: 'الحجز', PICKUP: 'الاستلام', VEHICLE_CLEANLINESS: 'نظافة المركبة',
      VEHICLE_CONDITION: 'حالة المركبة', STAFF_SERVICE: 'خدمة الموظفين', PRICING: 'التسعير',
      DEPOSIT: 'التأمين', INSURANCE: 'التأمين', DAMAGE_CLAIM: 'مطالبة الأضرار',
      RETURN_PROCESS: 'عملية الإرجاع', COMMUNICATION: 'التواصل',
      ROADSIDE_ASSISTANCE: 'المساعدة على الطريق', BILLING: 'الفواتير', OTHER: 'أخرى',
    } as Record<string, string>,
  },
} as const

// ─── Types ─────────────────────────────────────────────────────────────────────

interface Complaint {
  id: string
  companyId: string
  reservationId: string | null
  reviewId: string | null
  customerId: string | null
  severity: string
  status: string
  category: string
  subject: string
  description: string | null
  resolution: string | null
  notes: string | null
  assignedTo: string | null
  resolvedAt: string | null
  createdAt: string
  reservation: { id: string; startDate: string; status: string; vehicle: { make: string; model: string; year: number } } | null
  customer: { id: string; firstName: string; lastName: string; email: string } | null
  review: { id: string; overallRating: number } | null
}

interface ComplaintsResponse {
  data: Complaint[]
  meta: { total: number; page: number; pageSize: number; totalPages: number }
}

const CATEGORIES = [
  'BOOKING', 'PICKUP', 'VEHICLE_CLEANLINESS', 'VEHICLE_CONDITION', 'STAFF_SERVICE',
  'PRICING', 'DEPOSIT', 'INSURANCE', 'DAMAGE_CLAIM', 'RETURN_PROCESS',
  'COMMUNICATION', 'ROADSIDE_ASSISTANCE', 'BILLING', 'OTHER',
]

function severityBadgeClass(sev: string) {
  if (sev === 'LEVEL_3') return 'badge-red'
  if (sev === 'LEVEL_2') return 'badge-amber'
  return 'badge-gray'
}

function statusBadgeClass(status: string) {
  if (status === 'RESOLVED' || status === 'CLOSED') return 'badge-green'
  if (status === 'INVESTIGATING') return 'badge-blue'
  return 'badge-amber'
}

// ─── Main page ─────────────────────────────────────────────────────────────────

export default function ComplaintsPage() {
  const { language } = useDashboardI18n()
  const t = copy[language as keyof typeof copy] ?? copy.en

  const [complaints, setComplaints] = useState<Complaint[]>([])
  const [meta, setMeta] = useState({ total: 0, page: 1, pageSize: 20, totalPages: 1 })
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const [filterStatus, setFilterStatus] = useState('')
  const [filterSeverity, setFilterSeverity] = useState('')
  const [page, setPage] = useState(1)

  const [expandedId, setExpandedId] = useState<string | null>(null)
  const [showCreate, setShowCreate] = useState(false)

  // Create form state
  const [formReservationId, setFormReservationId] = useState('')
  const [formCategory, setFormCategory] = useState('')
  const [formSeverity, setFormSeverity] = useState('LEVEL_1')
  const [formSubject, setFormSubject] = useState('')
  const [formDescription, setFormDescription] = useState('')
  const [formCreating, setFormCreating] = useState(false)

  // Edit state (for expanded complaint)
  const [editStatus, setEditStatus] = useState<Record<string, string>>({})
  const [editNotes, setEditNotes] = useState<Record<string, string>>({})
  const [editResolution, setEditResolution] = useState<Record<string, string>>({})
  const [savingId, setSavingId] = useState<string | null>(null)

  async function loadData() {
    setLoading(true)
    setError(null)
    try {
      const params = new URLSearchParams({ page: String(page), pageSize: '20' })
      if (filterStatus) params.set('status', filterStatus)
      if (filterSeverity) params.set('severity', filterSeverity)
      const data = await apiFetch<ComplaintsResponse>(`/complaints?${params}`)
      setComplaints(data.data ?? [])
      setMeta(data.meta ?? { total: 0, page: 1, pageSize: 20, totalPages: 1 })
    } catch {
      setError(t.errorLoad)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { loadData() }, [page, filterStatus, filterSeverity])

  function toggleExpand(id: string, complaint: Complaint) {
    if (expandedId === id) {
      setExpandedId(null)
    } else {
      setExpandedId(id)
      setEditStatus((prev) => ({ ...prev, [id]: complaint.status }))
      setEditNotes((prev) => ({ ...prev, [id]: complaint.notes ?? '' }))
      setEditResolution((prev) => ({ ...prev, [id]: complaint.resolution ?? '' }))
    }
  }

  async function handleCreate() {
    if (!formCategory || !formSubject.trim()) return
    setFormCreating(true)
    try {
      await apiFetch('/complaints', {
        method: 'POST',
        body: JSON.stringify({
          reservationId: formReservationId.trim() || undefined,
          category: formCategory,
          severity: formSeverity,
          subject: formSubject.trim(),
          description: formDescription.trim() || undefined,
        }),
      })
      setShowCreate(false)
      setFormReservationId('')
      setFormCategory('')
      setFormSeverity('LEVEL_1')
      setFormSubject('')
      setFormDescription('')
      await loadData()
    } catch {
      alert(t.errorCreate)
    } finally {
      setFormCreating(false)
    }
  }

  async function handleUpdate(id: string) {
    setSavingId(id)
    try {
      await apiFetch(`/complaints/${id}`, {
        method: 'PATCH',
        body: JSON.stringify({
          status: editStatus[id],
          notes: editNotes[id] || undefined,
          resolution: editResolution[id] || undefined,
        }),
      })
      await loadData()
    } catch {
      alert(t.errorUpdate)
    } finally {
      setSavingId(null)
    }
  }

  const isRtl = language === 'ar'

  return (
    <div className={`space-y-6 p-6 ${isRtl ? 'rtl' : 'ltr'}`}>
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-blue-950 dark:text-white">{t.heading}</h1>
          <p className="mt-1 text-sm text-stone-500 dark:text-slate-400">{t.subtitle}</p>
        </div>
        <button onClick={() => setShowCreate((v) => !v)} className="btn-primary">
          <Plus className="h-4 w-4" />
          {t.newComplaint}
        </button>
      </div>

      {/* Create form */}
      {showCreate && (
        <div className="card p-6 space-y-4">
          <h2 className="text-lg font-semibold text-blue-950 dark:text-white">{t.createTitle}</h2>
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="mb-1 block text-sm font-medium text-stone-700 dark:text-slate-300">{t.fieldReservationId}</label>
              <input
                type="text"
                value={formReservationId}
                onChange={(e) => setFormReservationId(e.target.value)}
                className="input-field"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-stone-700 dark:text-slate-300">{t.fieldCategory}</label>
              <select
                value={formCategory}
                onChange={(e) => setFormCategory(e.target.value)}
                className="input-field"
              >
                <option value="">— select —</option>
                {CATEGORIES.map((c) => (
                  <option key={c} value={c}>{t.categories[c] ?? c}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-stone-700 dark:text-slate-300">{t.fieldSeverity}</label>
              <select value={formSeverity} onChange={(e) => setFormSeverity(e.target.value)} className="input-field">
                <option value="LEVEL_1">{t.sevL1}</option>
                <option value="LEVEL_2">{t.sevL2}</option>
                <option value="LEVEL_3">{t.sevL3}</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-stone-700 dark:text-slate-300">{t.fieldSubject}</label>
              <input
                type="text"
                value={formSubject}
                onChange={(e) => setFormSubject(e.target.value)}
                className="input-field"
              />
            </div>
            <div className="sm:col-span-2">
              <label className="mb-1 block text-sm font-medium text-stone-700 dark:text-slate-300">{t.fieldDescription}</label>
              <textarea
                value={formDescription}
                onChange={(e) => setFormDescription(e.target.value)}
                rows={3}
                className="input-field resize-none"
              />
            </div>
          </div>
          <div className="flex gap-2">
            <button
              onClick={handleCreate}
              disabled={formCreating || !formCategory || !formSubject.trim()}
              className="btn-primary"
            >
              {formCreating ? t.creating : t.create}
            </button>
            <button onClick={() => setShowCreate(false)} className="btn-secondary">{t.cancel}</button>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="card p-4">
        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center gap-2">
            <label className="text-sm font-medium text-stone-700 dark:text-slate-300">{t.filterStatus}</label>
            <select
              value={filterStatus}
              onChange={(e) => { setFilterStatus(e.target.value); setPage(1) }}
              className="input-field w-auto"
            >
              <option value="">{t.allStatuses}</option>
              <option value="OPEN">{t.statusOpen}</option>
              <option value="INVESTIGATING">{t.statusInvestigating}</option>
              <option value="RESOLVED">{t.statusResolved}</option>
              <option value="CLOSED">{t.statusClosed}</option>
            </select>
          </div>
          <div className="flex items-center gap-2">
            <label className="text-sm font-medium text-stone-700 dark:text-slate-300">{t.filterSeverity}</label>
            <select
              value={filterSeverity}
              onChange={(e) => { setFilterSeverity(e.target.value); setPage(1) }}
              className="input-field w-auto"
            >
              <option value="">{t.allSeverities}</option>
              <option value="LEVEL_1">{t.sevL1}</option>
              <option value="LEVEL_2">{t.sevL2}</option>
              <option value="LEVEL_3">{t.sevL3}</option>
            </select>
          </div>
        </div>
      </div>

      {/* List */}
      {loading ? (
        <div className="card p-10 text-center text-stone-400 dark:text-slate-500">Loading…</div>
      ) : error ? (
        <div className="card p-10 text-center text-red-500">{error}</div>
      ) : complaints.length === 0 ? (
        <div className="card p-10 text-center text-stone-400 dark:text-slate-500">{t.noComplaints}</div>
      ) : (
        <div className="space-y-3">
          {complaints.map((complaint) => {
            const isExpanded = expandedId === complaint.id
            const customerName = complaint.customer
              ? `${complaint.customer.firstName} ${complaint.customer.lastName}`
              : null

            return (
              <div key={complaint.id} className="card overflow-hidden">
                <button
                  onClick={() => toggleExpand(complaint.id, complaint)}
                  className="flex w-full items-start justify-between p-5 text-left hover:bg-stone-50 dark:hover:bg-blue-950/30"
                >
                  <div className="flex flex-1 flex-wrap items-center gap-3">
                    <span className={severityBadgeClass(complaint.severity)}>
                      <AlertTriangle className="mr-1 h-3 w-3" />
                      {complaint.severity === 'LEVEL_1' ? t.sevL1 : complaint.severity === 'LEVEL_2' ? t.sevL2 : t.sevL3}
                    </span>
                    <span className={statusBadgeClass(complaint.status)}>
                      {complaint.status === 'OPEN' ? t.statusOpen
                        : complaint.status === 'INVESTIGATING' ? t.statusInvestigating
                        : complaint.status === 'RESOLVED' ? t.statusResolved
                        : t.statusClosed}
                    </span>
                    <span className="badge-gray">{t.categories[complaint.category] ?? complaint.category}</span>
                    <span className="font-medium text-blue-950 dark:text-white">{complaint.subject}</span>
                    {customerName && <span className="text-sm text-stone-500 dark:text-slate-400">{customerName}</span>}
                    {complaint.reservationId && (
                      <span className="font-mono text-xs text-stone-400 dark:text-slate-500">
                        {complaint.reservationId.slice(0, 8)}…
                      </span>
                    )}
                  </div>
                  <div className="flex shrink-0 items-center gap-3">
                    <span className="text-xs text-stone-400 dark:text-slate-500">
                      {new Date(complaint.createdAt).toLocaleDateString()}
                    </span>
                    {isExpanded ? <ChevronUp className="h-4 w-4 text-stone-400" /> : <ChevronDown className="h-4 w-4 text-stone-400" />}
                  </div>
                </button>

                {/* Expanded detail */}
                {isExpanded && (
                  <div className="border-t border-stone-100 p-5 dark:border-blue-900/30 space-y-4">
                    {complaint.description && (
                      <div>
                        <p className="mb-1 text-xs font-medium uppercase tracking-wide text-stone-500 dark:text-slate-400">{t.description}</p>
                        <p className="text-sm text-stone-700 dark:text-slate-300">{complaint.description}</p>
                      </div>
                    )}

                    <div className="grid gap-4 sm:grid-cols-3">
                      <div>
                        <label className="mb-1 block text-xs font-medium uppercase tracking-wide text-stone-500 dark:text-slate-400">{t.updateStatus}</label>
                        <select
                          value={editStatus[complaint.id] ?? complaint.status}
                          onChange={(e) => setEditStatus((prev) => ({ ...prev, [complaint.id]: e.target.value }))}
                          className="input-field"
                        >
                          <option value="OPEN">{t.statusOpen}</option>
                          <option value="INVESTIGATING">{t.statusInvestigating}</option>
                          <option value="RESOLVED">{t.statusResolved}</option>
                          <option value="CLOSED">{t.statusClosed}</option>
                        </select>
                      </div>
                      <div className="sm:col-span-2">
                        <label className="mb-1 block text-xs font-medium uppercase tracking-wide text-stone-500 dark:text-slate-400">{t.notes}</label>
                        <textarea
                          value={editNotes[complaint.id] ?? ''}
                          onChange={(e) => setEditNotes((prev) => ({ ...prev, [complaint.id]: e.target.value }))}
                          rows={2}
                          className="input-field resize-none"
                        />
                      </div>
                    </div>

                    <div>
                      <label className="mb-1 block text-xs font-medium uppercase tracking-wide text-stone-500 dark:text-slate-400">{t.resolution}</label>
                      <textarea
                        value={editResolution[complaint.id] ?? ''}
                        onChange={(e) => setEditResolution((prev) => ({ ...prev, [complaint.id]: e.target.value }))}
                        rows={2}
                        className="input-field resize-none"
                      />
                    </div>

                    <div className="flex gap-2">
                      <button
                        onClick={() => handleUpdate(complaint.id)}
                        disabled={savingId === complaint.id}
                        className="btn-primary text-sm"
                      >
                        {savingId === complaint.id ? t.saving : t.save}
                      </button>
                      <button onClick={() => setExpandedId(null)} className="btn-secondary text-sm">{t.cancel}</button>
                    </div>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      )}

      {/* Pagination */}
      {meta.totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page <= 1}
            className="btn-secondary text-sm"
          >
            ←
          </button>
          <span className="text-sm text-stone-600 dark:text-slate-400">
            {page} / {meta.totalPages}
          </span>
          <button
            onClick={() => setPage((p) => Math.min(meta.totalPages, p + 1))}
            disabled={page >= meta.totalPages}
            className="btn-secondary text-sm"
          >
            →
          </button>
        </div>
      )}
    </div>
  )
}
