'use client';

import { useState, useEffect, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowLeft, Mail, Phone, ShoppingBag, Calendar,
  Edit2, Star, Tag, Loader2, Save, X, ChevronLeft, ChevronRight,
} from 'lucide-react';
import { getCustomer, updateCustomer, type Customer } from '@client/api/customers';
import CustomerLoyaltyCard from '@client/components/loyalty/CustomerLoyaltyCard';
import { listOrders, type Order, type OrderListResponse } from '@client/api/orders';
import { listBookings, type Booking, type BookingListResponse } from '@client/api/bookings';
import { formatOid } from '@client/utils/formatOid';
import { toast } from 'sonner';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

type TFn = (key: string, fallback?: string, vars?: Record<string, string | number>) => string;

const STATUS_BADGE: Record<string, string> = {
  confirmed: 'badge-success', pending: 'badge-warning', completed: 'badge-success',
  cancelled: 'badge-danger', seated: 'badge-info', noshow: 'badge-danger',
  kitchen: 'badge-info', ready: 'badge-success', delivered: 'badge-success',
  processing: 'badge-info', rider: 'badge-info', failed: 'badge-danger', escalated: 'badge-danger',
};

const PAGE_SIZE = 10;

function fmtDate(s: string | undefined, lang: string) {
  if (!s) return '—';
  try { return new Date(s).toLocaleDateString(lang, { month: 'short', day: 'numeric', year: 'numeric' }); } catch { return '—'; }
}

function fmtDateShort(s: string | undefined, lang: string) {
  if (!s) return '—';
  try { return new Date(s).toLocaleDateString(lang, { month: 'short', day: 'numeric' }); } catch { return '—'; }
}

function Paginator({ page, pages, total, onPrev, onNext, loading, t }: { page: number; pages: number; total: number; onPrev: () => void; onNext: () => void; loading: boolean; t: (key: string, fallback: string) => string }) {
  if (pages <= 1) return null;
  return (
    <div className="flex items-center justify-between px-5 py-2.5" style={{ borderTop: '1px solid hsl(var(--border))' }}>
      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
        {t('customers.page_of', 'Page')} {page} {t('customers.page_of_total', 'of')} {pages} ({total} {t('customers.total', 'total')})
      </span>
      <div className="flex gap-1">
        <button className="btn-ghost p-1" disabled={page <= 1 || loading} onClick={onPrev}><ChevronLeft size={14} /></button>
        <button className="btn-ghost p-1" disabled={page >= pages || loading} onClick={onNext}><ChevronRight size={14} /></button>
      </div>
    </div>
  );
}

export default function CustomerDetailPage() {
  const { t, currentLang } = useLanguage();
  usePageHeader(t('customers.profile_title', 'Customer Profile'), t('customers.profile_subtitle', 'Complete profile, order history, and reservations'));
  const params = useParams();
  const id = params?.id as string;

  const [customer, setCustomer] = useState<Customer | null>(null);
  const [loading, setLoading] = useState(true);
  const [note, setNote] = useState('');
  const [editingNote, setEditingNote] = useState(false);
  const [savingNote, setSavingNote] = useState(false);

  const [orders, setOrders] = useState<Order[]>([]);
  const [ordersLoading, setOrdersLoading] = useState(false);
  const [ordersPage, setOrdersPage] = useState(1);
  const [ordersTotal, setOrdersTotal] = useState(0);
  const [ordersPages, setOrdersPages] = useState(0);

  const [bookings, setBookings] = useState<Booking[]>([]);
  const [bookingsLoading, setBookingsLoading] = useState(false);
  const [bookingsPage, setBookingsPage] = useState(1);
  const [bookingsTotal, setBookingsTotal] = useState(0);
  const [bookingsPages, setBookingsPages] = useState(0);

  const fetchOrders = useCallback(async (customerId: string, pg: number) => {
    setOrdersLoading(true);
    let result: OrderListResponse;
    try {
      result = await listOrders({ customer_id: customerId, page: String(pg), limit: String(PAGE_SIZE), sort_field: 'created_at', sort_dir: 'desc' });
    } catch {
      toast.error(t('customers.load_orders_error', 'Failed to load orders'));
      result = { orders: [], total: 0, page: pg, limit: PAGE_SIZE, pages: 0 };
    }
    setOrders(result.orders);
    setOrdersPage(result.page);
    setOrdersTotal(result.total);
    setOrdersPages(result.pages);
    setOrdersLoading(false);
  }, []);

  const fetchBookings = useCallback(async (customerId: string, pg: number) => {
    setBookingsLoading(true);
    let result: BookingListResponse;
    try {
      result = await listBookings({ customer_id: customerId, page: String(pg), limit: String(PAGE_SIZE), sort_dir: 'desc' });
    } catch {
      toast.error(t('customers.load_reservations_error', 'Failed to load reservations'));
      result = { bookings: [], total: 0, page: pg, limit: PAGE_SIZE, pages: 0 };
    }
    setBookings(result.bookings);
    setBookingsPage(result.page);
    setBookingsTotal(result.total);
    setBookingsPages(result.pages);
    setBookingsLoading(false);
  }, []);

  useEffect(() => {
    if (!id) return;
    setLoading(true);
    getCustomer(id)
      .then(({ customer: c }) => {
        setCustomer(c);
        setNote(c.notes ?? '');
      })
      .catch(() => { /* customer stays null */ })
      .finally(() => setLoading(false));
    fetchOrders(id, 1);
    fetchBookings(id, 1);
  }, [id, fetchOrders, fetchBookings]);

  const handleSaveNote = async () => {
    if (!customer) return;
    setSavingNote(true);
    try {
      await updateCustomer(customer.id, { notes: note });
      const { customer: refreshed } = await getCustomer(customer.id);
      setCustomer(refreshed);
      setNote(refreshed.notes ?? '');
      setEditingNote(false);
      toast.success(t('customers.note_saved', 'Note saved'));
    } catch {
      toast.error(t('customers.save_note_error', 'Failed to save note'));
    } finally {
      setSavingNote(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="animate-spin" size={28} style={{ color: 'hsl(var(--primary))' }} />
      </div>
    );
  }

  if (!customer) {
    return (
      <div className="text-center py-20">
        <p className="text-lg font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('customers.not_found', 'Customer not found')}</p>
        <Link href="/customers" className="btn-primary mt-4 inline-flex">{t('customers.back_to_list', 'Back to Customers')}</Link>
      </div>
    );
  }

  const initials = customer.name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase();
  const avgOrderValue = customer.totalOrders > 0 ? customer.totalSpend / customer.totalOrders : 0;

  return (
    <>
      {/* Back + Header */}
      <div className="flex items-center gap-3 mb-6">
        <Link href="/customers" className="btn-ghost p-1.5"><ArrowLeft size={16} /></Link>
        <div className="flex items-center gap-3">
          <div
            className="w-12 h-12 rounded-full flex items-center justify-center text-white font-bold text-sm"
            style={{ background: 'linear-gradient(135deg, hsl(var(--primary)), hsl(22, 89%, 36%))' }}
          >
            {initials}
          </div>
          <div>
            <h2 className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{customer.name}</h2>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('customers.member_since', 'Member since')} {fmtDate(customer.createdAt, currentLang)}
            </p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        {/* Left Sidebar */}
        <div className="space-y-5">
          {/* Contact + Stats */}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('customers.contact_info', 'Contact Info')}</h3>
            <div className="space-y-3 text-sm">
              {customer.email && (
                <div className="flex items-center gap-3">
                  <Mail size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  <span style={{ color: 'hsl(var(--foreground))' }}>{customer.email}</span>
                </div>
              )}
              {customer.phone && (
                <div className="flex items-center gap-3">
                  <Phone size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  <span style={{ color: 'hsl(var(--foreground))' }}>{customer.phone}</span>
                </div>
              )}
              {!customer.email && !customer.phone && (
                <p className="text-xs italic" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('customers.no_contact_details', 'No contact details on record')}</p>
              )}
            </div>

            <div className="grid grid-cols-2 gap-3 mt-5">
              {[
                { label: t('customers.total_orders', 'Total Orders'), value: String(customer.totalOrders) },
                { label: t('customers.total_spent', 'Total Spent'), value: `$${Number(customer.totalSpend).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` },
                { label: t('customers.avg_order_value', 'Avg Order Value'), value: `$${avgOrderValue.toFixed(2)}` },
                { label: t('customers.total_reservations', 'Reservations'), value: String(customer.totalReservations) },
                { label: t('customers.last_visit', 'Last Visit'), value: fmtDateShort(customer.lastVisit, currentLang) },
                { label: t('customers.total_visits', 'Total Visits'), value: customer.totalVisits ? String(customer.totalVisits) : '—' },
                { label: t('customers.member_since_label', 'Member Since'), value: fmtDate(customer.createdAt, currentLang) },
              ].map(item => (
                <div key={item.label} className="p-3 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.label}</p>
                  <p className="text-sm font-bold tabular-nums mt-0.5" style={{ color: 'hsl(var(--foreground))' }}>{item.value}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Loyalty */}
          <CustomerLoyaltyCard customerId={id} />

          {/* Preferences */}
          {customer.preferences && customer.preferences.length > 0 && (
            <div className="card p-5">
              <h3 className="font-semibold mb-3 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
                <Star size={14} /> {t('customers.preferences', 'Preferences')}
              </h3>
              <div className="flex flex-wrap gap-1.5">
                {customer.preferences.map(p => <span key={p} className="badge badge-info text-xs">{p}</span>)}
              </div>
            </div>
          )}

          {/* Tags */}
          {customer.tags && customer.tags.length > 0 && (
            <div className="card p-5">
              <h3 className="font-semibold mb-3 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
                <Tag size={14} /> {t('customers.tags', 'Tags')}
              </h3>
              <div className="flex flex-wrap gap-1.5">
                {customer.tags.map(t => <span key={t} className="badge badge-neutral text-xs">{t}</span>)}
              </div>
            </div>
          )}

          {/* Notes */}
          <div className="card p-5">
            <div className="flex items-center justify-between mb-3">
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('customers.internal_notes', 'Internal Notes')}</h3>
              {!editingNote && (
                <button onClick={() => setEditingNote(true)} className="btn-ghost text-xs px-2 py-1">
                  <Edit2 size={12} /> {t('customers.edit_note', 'Edit')}
                </button>
              )}
            </div>
            {editingNote ? (
              <div className="space-y-2">
                <textarea
                  value={note}
                  onChange={e => setNote(e.target.value)}
                  className="w-full p-3 rounded-lg text-sm resize-none"
                  style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground))', border: '1px solid hsl(var(--border))' }}
                  rows={4}
                  placeholder={t('customers.notes_placeholder', 'Add internal notes about this customer...')}
                />
                <div className="flex gap-2">
                  <button onClick={handleSaveNote} disabled={savingNote} className="btn-primary text-xs px-3 py-1.5">
                    {savingNote
                      ? <span className="w-3 h-3 border-2 border-white/30 border-t-white rounded-full animate-spin inline-block" />
                      : <><Save size={11} /> {t('customers.save_note', 'Save')}</>}
                  </button>
                  <button onClick={() => { setEditingNote(false); setNote(customer.notes ?? ''); }} className="btn-secondary text-xs px-3 py-1.5">
                    <X size={11} /> {t('customers.cancel_note', 'Cancel')}
                  </button>
                </div>
              </div>
            ) : (
              <p className="text-sm" style={{ color: note ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}>
                {note || t('customers.no_notes', 'No notes yet. Click Edit to add notes.')}
              </p>
            )}
          </div>
        </div>

        {/* Right: Orders + Bookings */}
        <div className="lg:col-span-2 space-y-5">
          {/* Orders */}
          <div className="card overflow-hidden">
            <div className="px-5 py-3.5 flex items-center justify-between" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
              <h3 className="font-semibold flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
                <ShoppingBag size={15} /> {t('customers.orders', 'Orders')}
                <span className="badge badge-neutral text-xs">{ordersTotal}</span>
              </h3>
              <Link href={`/order-management?customer_id=${id}`} className="text-xs font-semibold" style={{ color: 'hsl(var(--primary))' }}>{t('customers.view_all', 'View All')}</Link>
            </div>
            {ordersLoading ? (
              <div className="flex items-center justify-center py-10">
                <Loader2 className="animate-spin" size={20} style={{ color: 'hsl(var(--primary))' }} />
              </div>
            ) : orders.length === 0 ? (
              <div className="px-5 py-10 text-center">
                <ShoppingBag size={32} className="mx-auto mb-2 opacity-20" style={{ color: 'hsl(var(--muted-foreground))' }} />
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('customers.no_orders', 'No orders yet')}</p>
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                        {[
                          t('customers.order_no', 'Order #'),
                          t('customers.order_date', 'Date'),
                          t('customers.order_channel', 'Channel'),
                          t('customers.order_items', 'Items'),
                          t('customers.order_total', 'Total'),
                          t('customers.order_status', 'Status')
                        ].map(h => (
                          <th key={h} className="text-left px-5 py-2.5 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {orders.map((order, idx) => (
                        <tr
                          key={order.id}
                          className="table-row-hover"
                          style={{ borderBottom: idx < orders.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}
                        >
                          <td className="px-5 py-3 font-mono font-bold text-xs" style={{ color: 'hsl(var(--foreground))' }}>
                            <div className="flex items-center gap-1.5">
                              <span>{formatOid(order.orderNumber, order.id, order.restaurantId)}</span>
                              {((order.loyaltyPointsEarned ?? 0) > 0 || (order.loyaltyPointsRedeemed ?? 0) > 0) && (
                                <span
                                  className="inline-flex items-center gap-0.5 text-[10px] font-bold px-1.5 py-0.5 rounded-full"
                                  style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
                                  title={
                                    (order.loyaltyPointsEarned ?? 0) > 0 && (order.loyaltyPointsRedeemed ?? 0) > 0
                                      ? `${order.loyaltyPointsEarned} ${t('customers.points_earned_short', 'earned')} · ${order.loyaltyPointsRedeemed} ${t('customers.points_redeemed_short', 'redeemed')}`
                                      : (order.loyaltyPointsEarned ?? 0) > 0
                                        ? `${order.loyaltyPointsEarned} ${t('customers.points_earned_short', 'pts earned')}`
                                        : `${order.loyaltyPointsRedeemed} ${t('customers.points_redeemed_short', 'pts redeemed')}`
                                  }
                                >
                                  <Star size={9} fill="currentColor" />
                                  {(order.loyaltyPointsEarned ?? 0) > 0 ? (order.loyaltyPointsEarned ?? 0) : (order.loyaltyPointsRedeemed ?? 0)}
                                </span>
                              )}
                            </div>
                          </td>
                          <td className="px-5 py-3 text-xs whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            {fmtDate(order.createdAt, currentLang)}
                          </td>
                          <td className="px-5 py-3 text-xs capitalize" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            {order.channel}
                          </td>
                          <td className="px-5 py-3 text-xs max-w-[200px] truncate" style={{ color: 'hsl(var(--foreground))' }}>
                            {order.items.map(i => `${i.quantity}× ${i.name}`).join(', ') || '—'}
                          </td>
                          <td className="px-5 py-3 text-xs font-semibold whitespace-nowrap" style={{ color: 'hsl(var(--primary))' }}>
                            ${Number(order.total).toFixed(2)}
                          </td>
                          <td className="px-5 py-3">
                            <span className={`badge ${STATUS_BADGE[order.status] ?? 'badge-neutral'} text-xs capitalize`}>{order.status}</span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <Paginator
                  page={ordersPage}
                  pages={ordersPages}
                  total={ordersTotal}
                  loading={ordersLoading}
                  onPrev={() => fetchOrders(id, ordersPage - 1)}
                  onNext={() => fetchOrders(id, ordersPage + 1)}
                  t={t}
                />
              </>
            )}
          </div>

          {/* Bookings */}
          <div className="card overflow-hidden">
            <div className="px-5 py-3.5 flex items-center justify-between" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
              <h3 className="font-semibold flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
                <Calendar size={15} /> {t('customers.reservations', 'Reservations')}
                <span className="badge badge-neutral text-xs">{bookingsTotal}</span>
              </h3>
              <Link href="/table-booking-management" className="text-xs font-semibold" style={{ color: 'hsl(var(--primary))' }}>{t('customers.view_all', 'View All')}</Link>
            </div>
            {bookingsLoading ? (
              <div className="flex items-center justify-center py-10">
                <Loader2 className="animate-spin" size={20} style={{ color: 'hsl(var(--primary))' }} />
              </div>
            ) : bookings.length === 0 ? (
              <div className="px-5 py-10 text-center">
                <Calendar size={32} className="mx-auto mb-2 opacity-20" style={{ color: 'hsl(var(--muted-foreground))' }} />
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('customers.no_reservations', 'No reservations yet')}</p>
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                        {[
                          t('customers.booking_date', 'Date'),
                          t('customers.booking_time', 'Time'),
                          t('customers.booking_party', 'Party'),
                          t('customers.booking_occasion', 'Occasion'),
                          t('customers.booking_status', 'Status'),
                          t('customers.booking_requests', 'Special Requests')
                        ].map(h => (
                          <th key={h} className="text-left px-5 py-2.5 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {bookings.map((booking, idx) => (
                        <tr
                          key={booking.id}
                          className="table-row-hover"
                          style={{ borderBottom: idx < bookings.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}
                        >
                          <td className="px-5 py-3 text-xs whitespace-nowrap" style={{ color: 'hsl(var(--foreground))' }}>
                            {booking.date ? fmtDate(booking.date, currentLang) : '—'}
                          </td>
                          <td className="px-5 py-3 text-xs whitespace-nowrap" style={{ color: 'hsl(var(--foreground))' }}>
                            {booking.time || '—'}
                          </td>
                          <td className="px-5 py-3 text-xs text-center font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
                            {booking.partySize}
                          </td>
                          <td className="px-5 py-3 text-xs capitalize" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            {booking.occasion || '—'}
                          </td>
                          <td className="px-5 py-3">
                            <span className={`badge ${STATUS_BADGE[booking.status] ?? 'badge-neutral'} text-xs capitalize`}>{booking.status}</span>
                          </td>
                          <td className="px-5 py-3 text-xs max-w-[200px] truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            {booking.specialRequests || '—'}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <Paginator
                  page={bookingsPage}
                  pages={bookingsPages}
                  total={bookingsTotal}
                  loading={bookingsLoading}
                  onPrev={() => fetchBookings(id, bookingsPage - 1)}
                  onNext={() => fetchBookings(id, bookingsPage + 1)}
                  t={t}
                />
              </>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
