'use client'

import { useEffect, useState, useRef, useCallback } from 'react'
import {
  Plus,
  Pencil,
  Trash2,
  Search,
  Loader2,
  X,
  UserCheck,
  UserPlus,
  Trophy,
  Phone,
  Mail,
  MapPin,
  FileText,
  ShoppingBag,
  Calendar,
  User,
} from 'lucide-react'
import { formatCurrency, getInitials } from '@/lib/utils'
import toast from 'react-hot-toast'
import Pagination, { PaginationData } from '@/components/Pagination'

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface Customer {
  id: string
  name: string
  phone: string
  email?: string | null
  address?: string | null
  notes?: string | null
  totalOrders: number
  totalSpent: number
  lastOrderAt?: string | null
  createdAt: string
}

interface CustomerOrder {
  id: string
  orderNumber: string
  total: number
  status: string
  paymentStatus: string
  createdAt: string
  items?: { menuItem?: { name: string }; quantity: number; subtotal: number }[]
}

interface CustomerFormData {
  name: string
  phone: string
  email: string
  address: string
  notes: string
}

interface StatsData {
  totalCustomers: number
  newThisMonth: number
  topSpender: { name: string; totalSpent: number } | null
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const EMPTY_FORM: CustomerFormData = {
  name: '',
  phone: '',
  email: '',
  address: '',
  notes: '',
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export default function CustomersPage() {
  // ---- Customer list state ------------------------------------------------
  const [customers, setCustomers] = useState<Customer[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [pagination, setPagination] = useState<PaginationData>({
    page: 1,
    limit: 20,
    total: 0,
    totalPages: 0,
  })

  // ---- Stats state --------------------------------------------------------
  const [stats, setStats] = useState<StatsData>({
    totalCustomers: 0,
    newThisMonth: 0,
    topSpender: null,
  })

  // ---- Create / Edit modal state ------------------------------------------
  const [showModal, setShowModal] = useState(false)
  const [editing, setEditing] = useState<Customer | null>(null)
  const [form, setForm] = useState<CustomerFormData>({ ...EMPTY_FORM })
  const [saving, setSaving] = useState(false)

  // ---- Detail modal state -------------------------------------------------
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null)
  const [customerOrders, setCustomerOrders] = useState<CustomerOrder[]>([])
  const [ordersLoading, setOrdersLoading] = useState(false)
  const [ordersPagination, setOrdersPagination] = useState<PaginationData>({
    page: 1,
    limit: 10,
    total: 0,
    totalPages: 0,
  })

  // ---- Delete confirmation state ------------------------------------------
  const [deleteTarget, setDeleteTarget] = useState<Customer | null>(null)
  const [deleting, setDeleting] = useState(false)

  // ---- Debounce ref -------------------------------------------------------
  const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null)

  // =========================================================================
  // Data fetching
  // =========================================================================

  const fetchCustomers = useCallback(async (page = 1, searchQuery = search) => {
    try {
      const params = new URLSearchParams()
      params.set('page', String(page))
      params.set('limit', '20')
      if (searchQuery) params.set('search', searchQuery)

      const res = await fetch(`/api/customers?${params}`)
      if (!res.ok) throw new Error('Gagal memuat data pelanggan')
      const data = await res.json()

      setCustomers(data.customers || [])
      if (data.pagination) setPagination(data.pagination)

      // Derive stats from the response when available, otherwise compute from list
      if (data.stats) {
        setStats(data.stats)
      } else {
        deriveStats(data.customers || [], data.pagination?.total ?? 0)
      }
    } catch (err: any) {
      toast.error(err.message || 'Gagal memuat data pelanggan')
    } finally {
      setLoading(false)
    }
  }, [search])

  /** Fallback: derive basic stats from the current customer list. */
  const deriveStats = (list: Customer[], total: number) => {
    const now = new Date()
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)

    const newThisMonth = list.filter(
      (c) => new Date(c.createdAt) >= startOfMonth
    ).length

    const topSpender =
      list.length > 0
        ? list.reduce((top, c) => (c.totalSpent > (top?.totalSpent ?? 0) ? c : top), list[0])
        : null

    setStats({
      totalCustomers: total,
      newThisMonth,
      topSpender: topSpender
        ? { name: topSpender.name, totalSpent: topSpender.totalSpent }
        : null,
    })
  }

  const fetchCustomerOrders = async (customerId: string, page = 1) => {
    setOrdersLoading(true)
    try {
      const params = new URLSearchParams()
      params.set('page', String(page))
      params.set('limit', '10')

      const res = await fetch(`/api/customers/${customerId}/orders?${params}`)
      if (!res.ok) throw new Error('Gagal memuat riwayat pesanan')
      const data = await res.json()

      setCustomerOrders(data.orders || [])
      if (data.pagination) setOrdersPagination(data.pagination)
    } catch (err: any) {
      toast.error(err.message || 'Gagal memuat riwayat pesanan')
    } finally {
      setOrdersLoading(false)
    }
  }

  // =========================================================================
  // Effects
  // =========================================================================

  // Initial load
  useEffect(() => {
    fetchCustomers(1, '')
  }, [])

  // Debounced search
  useEffect(() => {
    if (searchTimeout.current) clearTimeout(searchTimeout.current)
    searchTimeout.current = setTimeout(() => {
      fetchCustomers(1, search)
    }, 300)

    return () => {
      if (searchTimeout.current) clearTimeout(searchTimeout.current)
    }
  }, [search])

  // Fetch orders when a customer is selected
  useEffect(() => {
    if (selectedCustomer) {
      setCustomerOrders([])
      setOrdersPagination({ page: 1, limit: 10, total: 0, totalPages: 0 })
      fetchCustomerOrders(selectedCustomer.id, 1)
    }
  }, [selectedCustomer])

  // =========================================================================
  // Handlers
  // =========================================================================

  const openCreate = () => {
    setEditing(null)
    setForm({ ...EMPTY_FORM })
    setShowModal(true)
  }

  const openEdit = (customer: Customer, e?: React.MouseEvent) => {
    if (e) e.stopPropagation()
    setEditing(customer)
    setForm({
      name: customer.name,
      phone: customer.phone,
      email: customer.email || '',
      address: customer.address || '',
      notes: customer.notes || '',
    })
    setShowModal(true)
  }

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!form.name.trim()) {
      toast.error('Nama pelanggan wajib diisi')
      return
    }
    if (!form.phone.trim()) {
      toast.error('No. HP wajib diisi')
      return
    }

    setSaving(true)
    try {
      const payload: Record<string, string> = {
        name: form.name.trim(),
        phone: form.phone.trim(),
      }
      if (form.email.trim()) payload.email = form.email.trim()
      if (form.address.trim()) payload.address = form.address.trim()
      if (form.notes.trim()) payload.notes = form.notes.trim()

      const url = editing ? `/api/customers/${editing.id}` : '/api/customers'
      const method = editing ? 'PUT' : 'POST'

      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      })

      if (!res.ok) {
        const errData = await res.json().catch(() => ({}))
        throw new Error(errData.error || 'Terjadi kesalahan')
      }

      toast.success(editing ? 'Pelanggan berhasil diupdate' : 'Pelanggan berhasil ditambahkan')
      setShowModal(false)
      setEditing(null)
      setForm({ ...EMPTY_FORM })
      fetchCustomers(pagination.page, search)
    } catch (err: any) {
      toast.error(err.message || 'Gagal menyimpan pelanggan')
    } finally {
      setSaving(false)
    }
  }

  const confirmDelete = (customer: Customer, e?: React.MouseEvent) => {
    if (e) e.stopPropagation()
    setDeleteTarget(customer)
  }

  const handleDelete = async () => {
    if (!deleteTarget) return
    setDeleting(true)
    try {
      const res = await fetch(`/api/customers/${deleteTarget.id}`, {
        method: 'DELETE',
      })
      if (!res.ok) {
        const errData = await res.json().catch(() => ({}))
        throw new Error(errData.error || 'Gagal menghapus pelanggan')
      }
      toast.success('Pelanggan berhasil dihapus')
      setDeleteTarget(null)
      fetchCustomers(pagination.page, search)
    } catch (err: any) {
      toast.error(err.message || 'Gagal menghapus pelanggan')
    } finally {
      setDeleting(false)
    }
  }

  const openDetail = (customer: Customer) => {
    setSelectedCustomer(customer)
  }

  const closeDetail = () => {
    setSelectedCustomer(null)
    setCustomerOrders([])
  }

  // =========================================================================
  // Helpers
  // =========================================================================

  const formatDate = (dateStr: string | null | undefined) => {
    if (!dateStr) return '-'
    return new Date(dateStr).toLocaleDateString('id-ID', {
      day: '2-digit',
      month: 'short',
      year: 'numeric',
    })
  }

  const formatDateTime = (dateStr: string | null | undefined) => {
    if (!dateStr) return '-'
    return new Date(dateStr).toLocaleDateString('id-ID', {
      day: '2-digit',
      month: 'short',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    })
  }

  const getStatusBadge = (status: string) => {
    const map: Record<string, { label: string; color: string }> = {
      pending: { label: 'Menunggu', color: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300' },
      confirmed: { label: 'Dikonfirmasi', color: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300' },
      preparing: { label: 'Diproses', color: 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-300' },
      ready: { label: 'Siap', color: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' },
      served: { label: 'Disajikan', color: 'bg-teal-100 text-teal-800 dark:bg-teal-900/30 dark:text-teal-300' },
      completed: { label: 'Selesai', color: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300' },
      cancelled: { label: 'Dibatalkan', color: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300' },
    }
    const info = map[status] || { label: status, color: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300' }
    return <span className={`badge text-xs px-2 py-0.5 rounded-full font-medium ${info.color}`}>{info.label}</span>
  }

  const getPaymentBadge = (status: string) => {
    const map: Record<string, { label: string; color: string }> = {
      unpaid: { label: 'Belum Bayar', color: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300' },
      paid: { label: 'Lunas', color: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' },
      refunded: { label: 'Refund', color: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300' },
    }
    const info = map[status] || { label: status, color: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300' }
    return <span className={`badge text-xs px-2 py-0.5 rounded-full font-medium ${info.color}`}>{info.label}</span>
  }

  // =========================================================================
  // Loading state
  // =========================================================================

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
      </div>
    )
  }

  // =========================================================================
  // Render
  // =========================================================================

  return (
    <div>
      {/* ----------------------------------------------------------------- */}
      {/* Stats Cards                                                       */}
      {/* ----------------------------------------------------------------- */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
        {/* Total Pelanggan */}
        <div className="card flex items-center gap-4">
          <div className="flex-shrink-0 w-12 h-12 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
            <UserCheck className="w-6 h-6 text-blue-600 dark:text-blue-400" />
          </div>
          <div>
            <p className="text-sm text-gray-500 dark:text-gray-400">Total Pelanggan</p>
            <p className="text-2xl font-bold text-gray-900 dark:text-white">
              {stats.totalCustomers}
            </p>
          </div>
        </div>

        {/* Baru Bulan Ini */}
        <div className="card flex items-center gap-4">
          <div className="flex-shrink-0 w-12 h-12 rounded-lg bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
            <UserPlus className="w-6 h-6 text-green-600 dark:text-green-400" />
          </div>
          <div>
            <p className="text-sm text-gray-500 dark:text-gray-400">Baru Bulan Ini</p>
            <p className="text-2xl font-bold text-gray-900 dark:text-white">
              {stats.newThisMonth}
            </p>
          </div>
        </div>

        {/* Top Spender */}
        <div className="card flex items-center gap-4">
          <div className="flex-shrink-0 w-12 h-12 rounded-lg bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center">
            <Trophy className="w-6 h-6 text-orange-600 dark:text-orange-400" />
          </div>
          <div>
            <p className="text-sm text-gray-500 dark:text-gray-400">Top Spender</p>
            {stats.topSpender ? (
              <>
                <p className="text-base font-bold text-gray-900 dark:text-white truncate max-w-[180px]">
                  {stats.topSpender.name}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  {formatCurrency(stats.topSpender.totalSpent)}
                </p>
              </>
            ) : (
              <p className="text-sm text-gray-400 dark:text-gray-500">Belum ada data</p>
            )}
          </div>
        </div>
      </div>

      {/* ----------------------------------------------------------------- */}
      {/* Header                                                            */}
      {/* ----------------------------------------------------------------- */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Pelanggan</h1>
          <p className="text-gray-600 dark:text-gray-300 mt-1">
            Kelola data pelanggan dan lihat riwayat pesanan mereka.
          </p>
        </div>
        <button onClick={openCreate} className="btn-primary text-sm">
          <Plus className="w-4 h-4 inline mr-1" /> Tambah Pelanggan
        </button>
      </div>

      {/* ----------------------------------------------------------------- */}
      {/* Search                                                            */}
      {/* ----------------------------------------------------------------- */}
      <div className="relative mb-4">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500" />
        <input
          type="text"
          placeholder="Cari nama, no. HP, atau email..."
          className="input-field pl-10"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      {/* ----------------------------------------------------------------- */}
      {/* Customers Table                                                   */}
      {/* ----------------------------------------------------------------- */}
      <div className="card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/50">
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">
                  Nama
                </th>
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">
                  No. HP
                </th>
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300 hidden md:table-cell">
                  Email
                </th>
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">
                  Total Order
                </th>
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300">
                  Total Belanja
                </th>
                <th className="text-left py-3 px-4 font-medium text-gray-600 dark:text-gray-300 hidden lg:table-cell">
                  Terakhir Order
                </th>
                <th className="text-right py-3 px-4 font-medium text-gray-600 dark:text-gray-300">
                  Aksi
                </th>
              </tr>
            </thead>
            <tbody>
              {customers.length > 0 ? (
                customers.map((customer) => (
                  <tr
                    key={customer.id}
                    onClick={() => openDetail(customer)}
                    className="border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 cursor-pointer transition-colors"
                  >
                    <td className="py-3 px-4">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 bg-primary-100 dark:bg-primary-900/30 rounded-full flex items-center justify-center text-primary-700 dark:text-primary-300 font-medium text-xs flex-shrink-0">
                          {getInitials(customer.name)}
                        </div>
                        <span className="font-medium text-gray-900 dark:text-white truncate max-w-[200px]">
                          {customer.name}
                        </span>
                      </div>
                    </td>
                    <td className="py-3 px-4 text-gray-600 dark:text-gray-300">
                      {customer.phone}
                    </td>
                    <td className="py-3 px-4 text-gray-600 dark:text-gray-300 hidden md:table-cell">
                      {customer.email || '-'}
                    </td>
                    <td className="py-3 px-4 text-gray-600 dark:text-gray-300">
                      {customer.totalOrders}
                    </td>
                    <td className="py-3 px-4 font-medium text-gray-900 dark:text-white">
                      {formatCurrency(customer.totalSpent)}
                    </td>
                    <td className="py-3 px-4 text-gray-500 dark:text-gray-400 text-xs hidden lg:table-cell">
                      {formatDate(customer.lastOrderAt)}
                    </td>
                    <td className="py-3 px-4 text-right">
                      <div className="flex items-center justify-end gap-1">
                        <button
                          onClick={(e) => openEdit(customer, e)}
                          className="btn-ghost p-1.5"
                          title="Edit pelanggan"
                        >
                          <Pencil className="w-4 h-4" />
                        </button>
                        <button
                          onClick={(e) => confirmDelete(customer, e)}
                          className="btn-ghost p-1.5 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/30"
                          title="Hapus pelanggan"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={7} className="py-16 text-center">
                    <div className="flex flex-col items-center gap-2">
                      <User className="w-10 h-10 text-gray-300 dark:text-gray-600" />
                      <p className="text-gray-500 dark:text-gray-400">
                        {search
                          ? 'Tidak ada pelanggan yang cocok dengan pencarian.'
                          : 'Belum ada pelanggan. Klik "Tambah Pelanggan" untuk menambahkan.'}
                      </p>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
        {customers.length > 0 && (
          <Pagination
            pagination={pagination}
            onPageChange={(page) => fetchCustomers(page, search)}
            itemLabel="pelanggan"
          />
        )}
      </div>

      {/* ----------------------------------------------------------------- */}
      {/* Create / Edit Modal                                               */}
      {/* ----------------------------------------------------------------- */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl w-full max-w-md p-6 max-h-[90vh] overflow-y-auto">
            {/* Modal header */}
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold dark:text-white">
                {editing ? 'Edit Pelanggan' : 'Tambah Pelanggan'}
              </h3>
              <button
                onClick={() => {
                  setShowModal(false)
                  setEditing(null)
                }}
              >
                <X className="w-5 h-5 text-gray-400 dark:text-gray-500" />
              </button>
            </div>

            {/* Form */}
            <form onSubmit={handleSave} className="space-y-4">
              {/* Nama */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                  Nama <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  className="input-field"
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  placeholder="Nama lengkap pelanggan"
                  required
                />
              </div>

              {/* No. HP */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                  No. HP <span className="text-red-500">*</span>
                </label>
                <input
                  type="tel"
                  className="input-field"
                  value={form.phone}
                  onChange={(e) => setForm({ ...form, phone: e.target.value })}
                  placeholder="08xxxxxxxxxx"
                  required
                />
              </div>

              {/* Email */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                  Email
                </label>
                <input
                  type="email"
                  className="input-field"
                  value={form.email}
                  onChange={(e) => setForm({ ...form, email: e.target.value })}
                  placeholder="email@contoh.com"
                />
              </div>

              {/* Alamat */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                  Alamat
                </label>
                <textarea
                  className="input-field min-h-[80px] resize-y"
                  value={form.address}
                  onChange={(e) => setForm({ ...form, address: e.target.value })}
                  placeholder="Alamat lengkap (opsional)"
                  rows={3}
                />
              </div>

              {/* Catatan */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">
                  Catatan
                </label>
                <textarea
                  className="input-field min-h-[80px] resize-y"
                  value={form.notes}
                  onChange={(e) => setForm({ ...form, notes: e.target.value })}
                  placeholder="Catatan tentang pelanggan (opsional)"
                  rows={3}
                />
              </div>

              {/* Actions */}
              <div className="flex gap-2 justify-end pt-2">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false)
                    setEditing(null)
                  }}
                  className="btn-secondary"
                >
                  Batal
                </button>
                <button type="submit" disabled={saving} className="btn-primary">
                  {saving ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : editing ? (
                    'Simpan Perubahan'
                  ) : (
                    'Tambah Pelanggan'
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ----------------------------------------------------------------- */}
      {/* Customer Detail Modal                                             */}
      {/* ----------------------------------------------------------------- */}
      {selectedCustomer && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl w-full max-w-2xl p-6 max-h-[90vh] overflow-y-auto">
            {/* Modal header */}
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-lg font-semibold dark:text-white">Detail Pelanggan</h3>
              <button onClick={closeDetail}>
                <X className="w-5 h-5 text-gray-400 dark:text-gray-500" />
              </button>
            </div>

            {/* Profile section */}
            <div className="flex items-start gap-4 mb-6">
              <div className="w-14 h-14 bg-primary-100 dark:bg-primary-900/30 rounded-full flex items-center justify-center text-primary-700 dark:text-primary-300 font-bold text-lg flex-shrink-0">
                {getInitials(selectedCustomer.name)}
              </div>
              <div className="flex-1 min-w-0">
                <h4 className="text-xl font-bold text-gray-900 dark:text-white truncate">
                  {selectedCustomer.name}
                </h4>
                <div className="mt-2 space-y-1">
                  <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                    <Phone className="w-4 h-4 text-gray-400 dark:text-gray-500 flex-shrink-0" />
                    <span>{selectedCustomer.phone}</span>
                  </div>
                  {selectedCustomer.email && (
                    <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                      <Mail className="w-4 h-4 text-gray-400 dark:text-gray-500 flex-shrink-0" />
                      <span>{selectedCustomer.email}</span>
                    </div>
                  )}
                  {selectedCustomer.address && (
                    <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                      <MapPin className="w-4 h-4 text-gray-400 dark:text-gray-500 flex-shrink-0" />
                      <span>{selectedCustomer.address}</span>
                    </div>
                  )}
                  {selectedCustomer.notes && (
                    <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                      <FileText className="w-4 h-4 text-gray-400 dark:text-gray-500 flex-shrink-0" />
                      <span className="italic">{selectedCustomer.notes}</span>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Customer stats */}
            <div className="grid grid-cols-3 gap-3 mb-6">
              <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-3 text-center">
                <div className="flex items-center justify-center mb-1">
                  <ShoppingBag className="w-4 h-4 text-blue-500" />
                </div>
                <p className="text-lg font-bold text-gray-900 dark:text-white">
                  {selectedCustomer.totalOrders}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">Total Order</p>
              </div>
              <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-3 text-center">
                <div className="flex items-center justify-center mb-1">
                  <Trophy className="w-4 h-4 text-green-500" />
                </div>
                <p className="text-lg font-bold text-gray-900 dark:text-white">
                  {formatCurrency(selectedCustomer.totalSpent)}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">Total Belanja</p>
              </div>
              <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-3 text-center">
                <div className="flex items-center justify-center mb-1">
                  <Calendar className="w-4 h-4 text-orange-500" />
                </div>
                <p className="text-sm font-bold text-gray-900 dark:text-white">
                  {formatDate(selectedCustomer.lastOrderAt)}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">Terakhir Order</p>
              </div>
            </div>

            {/* Order history */}
            <div>
              <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-3">
                Riwayat Pesanan
              </h4>

              {ordersLoading ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
                </div>
              ) : customerOrders.length > 0 ? (
                <>
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/50">
                          <th className="text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-300 text-xs">
                            No. Order
                          </th>
                          <th className="text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-300 text-xs">
                            Total
                          </th>
                          <th className="text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-300 text-xs">
                            Status
                          </th>
                          <th className="text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-300 text-xs">
                            Bayar
                          </th>
                          <th className="text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-300 text-xs">
                            Tanggal
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {customerOrders.map((order) => (
                          <tr
                            key={order.id}
                            className="border-b border-gray-100 dark:border-gray-700"
                          >
                            <td className="py-2 px-3 font-mono text-xs text-gray-700 dark:text-gray-300">
                              {order.orderNumber}
                            </td>
                            <td className="py-2 px-3 font-medium text-gray-900 dark:text-white text-xs">
                              {formatCurrency(order.total)}
                            </td>
                            <td className="py-2 px-3">{getStatusBadge(order.status)}</td>
                            <td className="py-2 px-3">{getPaymentBadge(order.paymentStatus)}</td>
                            <td className="py-2 px-3 text-xs text-gray-500 dark:text-gray-400">
                              {formatDateTime(order.createdAt)}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  <Pagination
                    pagination={ordersPagination}
                    onPageChange={(page) =>
                      fetchCustomerOrders(selectedCustomer.id, page)
                    }
                    itemLabel="pesanan"
                  />
                </>
              ) : (
                <div className="text-center py-8">
                  <ShoppingBag className="w-8 h-8 text-gray-300 dark:text-gray-600 mx-auto mb-2" />
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    Belum ada riwayat pesanan.
                  </p>
                </div>
              )}
            </div>

            {/* Footer actions */}
            <div className="flex justify-end gap-2 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
              <button onClick={closeDetail} className="btn-secondary text-sm">
                Tutup
              </button>
              <button
                onClick={() => {
                  closeDetail()
                  openEdit(selectedCustomer)
                }}
                className="btn-primary text-sm"
              >
                <Pencil className="w-4 h-4 inline mr-1" /> Edit Pelanggan
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ----------------------------------------------------------------- */}
      {/* Delete Confirmation Dialog                                        */}
      {/* ----------------------------------------------------------------- */}
      {deleteTarget && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl w-full max-w-sm p-6">
            <div className="text-center">
              <div className="w-12 h-12 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
                <Trash2 className="w-6 h-6 text-red-600 dark:text-red-400" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                Hapus Pelanggan
              </h3>
              <p className="text-sm text-gray-600 dark:text-gray-300 mb-6">
                Apakah Anda yakin ingin menghapus{' '}
                <span className="font-semibold">{deleteTarget.name}</span>? Tindakan ini tidak
                dapat dibatalkan.
              </p>
            </div>
            <div className="flex gap-2 justify-end">
              <button
                onClick={() => setDeleteTarget(null)}
                className="btn-secondary"
                disabled={deleting}
              >
                Batal
              </button>
              <button
                onClick={handleDelete}
                disabled={deleting}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
              >
                {deleting ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  'Ya, Hapus'
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
