'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Receipt, Search, Filter, Eye, DollarSign,
  Clock, CheckCircle, XCircle, ArrowRightLeft,
  ChevronDown, RefreshCcw
} from 'lucide-react';

interface POSOrder {
  id: string;
  orderNumber: string;
  status: string;
  orderType: string;
  tableNumber: string | null;
  subtotal: number;
  taxTotal: number;
  discountTotal: number;
  total: number;
  itemCount: number;
  createdAt: string;
  closedAt: string | null;
  items: any[];
  payments: any[];
}

const STATUS_CONFIG: Record<string, { label: string; color: string; icon: any }> = {
  open: { label: 'Open', color: 'bg-blue-500/20 text-blue-400', icon: Clock },
  closed: { label: 'Closed', color: 'bg-green-500/20 text-green-400', icon: CheckCircle },
  voided: { label: 'Voided', color: 'bg-red-500/20 text-red-400', icon: XCircle },
  transferred: { label: 'Transferred', color: 'bg-yellow-500/20 text-yellow-400', icon: ArrowRightLeft },
};

export default function POSOrdersPage() {
  const [orders, setOrders] = useState<POSOrder[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedOrder, setSelectedOrder] = useState<POSOrder | null>(null);

  const fetchOrders = useCallback(async () => {
    try {
      const params = new URLSearchParams();
      if (statusFilter !== 'all') params.set('status', statusFilter);
      const res = await fetch(`/api/pos/orders?${params}`);
      const data = await res.json();
      if (data.orders) setOrders(data.orders);
    } catch {
      console.error('Failed to fetch orders');
    } finally {
      setLoading(false);
    }
  }, [statusFilter]);

  useEffect(() => { fetchOrders(); }, [fetchOrders]);

  const filtered = searchTerm
    ? orders.filter(o => o.orderNumber.toLowerCase().includes(searchTerm.toLowerCase()))
    : orders;

  const totalRevenue = orders.filter(o => o.status === 'closed').reduce((s, o) => s + o.total, 0);
  const avgTicket = orders.filter(o => o.status === 'closed').length > 0
    ? totalRevenue / orders.filter(o => o.status === 'closed').length
    : 0;

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500" />
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <Receipt className="w-7 h-7 text-blue-400" />
            POS Orders
          </h1>
          <p className="text-gray-400 mt-1">View and manage all point-of-sale orders</p>
        </div>
        <button
          onClick={() => { setLoading(true); fetchOrders(); }}
          className="flex items-center gap-2 px-4 py-2 bg-white/5 hover:bg-white/10 border border-white/10 rounded-lg text-sm text-gray-300 transition-colors"
        >
          <RefreshCcw className="w-4 h-4" /> Refresh
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-black/40 border border-white/10 rounded-xl p-4">
          <p className="text-xs text-gray-500 mb-1">Total Orders</p>
          <p className="text-2xl font-bold text-white">{orders.length}</p>
        </div>
        <div className="bg-black/40 border border-white/10 rounded-xl p-4">
          <p className="text-xs text-gray-500 mb-1">Open</p>
          <p className="text-2xl font-bold text-blue-400">{orders.filter(o => o.status === 'open').length}</p>
        </div>
        <div className="bg-black/40 border border-white/10 rounded-xl p-4">
          <p className="text-xs text-gray-500 mb-1">Revenue (Closed)</p>
          <p className="text-2xl font-bold text-green-400">${totalRevenue.toFixed(2)}</p>
        </div>
        <div className="bg-black/40 border border-white/10 rounded-xl p-4">
          <p className="text-xs text-gray-500 mb-1">Avg Ticket</p>
          <p className="text-2xl font-bold text-orange-400">${avgTicket.toFixed(2)}</p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-3">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
          <input
            type="text"
            placeholder="Search by order number..."
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 bg-black/40 border border-white/10 rounded-lg text-sm text-white placeholder:text-gray-500 focus:outline-none focus:border-blue-500"
          />
        </div>
        <div className="flex gap-2">
          {['all', 'open', 'closed', 'voided'].map(s => (
            <button
              key={s}
              onClick={() => { setStatusFilter(s); setLoading(true); }}
              className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                statusFilter === s
                  ? 'bg-blue-600 text-white'
                  : 'bg-white/5 text-gray-400 hover:text-white'
              }`}
            >
              {s.charAt(0).toUpperCase() + s.slice(1)}
            </button>
          ))}
        </div>
      </div>

      {/* Orders Table */}
      <div className="bg-black/40 border border-white/10 rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-white/10">
              <th className="text-left px-4 py-3 text-gray-400 font-medium">Order #</th>
              <th className="text-left px-4 py-3 text-gray-400 font-medium">Type</th>
              <th className="text-left px-4 py-3 text-gray-400 font-medium">Table</th>
              <th className="text-center px-4 py-3 text-gray-400 font-medium">Items</th>
              <th className="text-right px-4 py-3 text-gray-400 font-medium">Total</th>
              <th className="text-center px-4 py-3 text-gray-400 font-medium">Status</th>
              <th className="text-right px-4 py-3 text-gray-400 font-medium">Time</th>
              <th className="text-right px-4 py-3 text-gray-400 font-medium">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(order => {
              const statusCfg = STATUS_CONFIG[order.status] || STATUS_CONFIG.open;
              const StatusIcon = statusCfg.icon;
              return (
                <tr key={order.id} className="border-b border-white/5 hover:bg-white/5 transition-colors">
                  <td className="px-4 py-3 font-mono text-white font-medium">{order.orderNumber}</td>
                  <td className="px-4 py-3 text-gray-400 capitalize">{order.orderType?.replace('_', ' ')}</td>
                  <td className="px-4 py-3 text-gray-400">{order.tableNumber || '—'}</td>
                  <td className="px-4 py-3 text-center text-gray-400">{order.itemCount}</td>
                  <td className="px-4 py-3 text-right font-mono text-white">${order.total.toFixed(2)}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${statusCfg.color}`}>
                      <StatusIcon className="w-3 h-3" />
                      {statusCfg.label}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-right text-gray-500 text-xs">
                    {new Date(order.createdAt).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
                  </td>
                  <td className="px-4 py-3 text-right">
                    <button
                      onClick={() => setSelectedOrder(order)}
                      className="p-1.5 hover:bg-white/10 rounded-lg transition-colors text-gray-400 hover:text-white"
                    >
                      <Eye className="w-4 h-4" />
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div className="text-center py-12 text-gray-500">
            <Receipt className="w-8 h-8 mx-auto mb-2 opacity-50" />
            <p>No orders found</p>
          </div>
        )}
      </div>

      {/* Order Detail Modal */}
      {selectedOrder && (
        <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50" onClick={() => setSelectedOrder(null)}>
          <div className="bg-gray-900 border border-white/10 rounded-2xl p-6 w-full max-w-lg max-h-[80vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold text-white">Order {selectedOrder.orderNumber}</h2>
              <button onClick={() => setSelectedOrder(null)} className="text-gray-400 hover:text-white">
                <XCircle className="w-5 h-5" />
              </button>
            </div>
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-3 text-sm">
                <div><span className="text-gray-500">Status:</span> <span className="text-white capitalize">{selectedOrder.status}</span></div>
                <div><span className="text-gray-500">Type:</span> <span className="text-white capitalize">{selectedOrder.orderType?.replace('_', ' ')}</span></div>
                <div><span className="text-gray-500">Table:</span> <span className="text-white">{selectedOrder.tableNumber || '—'}</span></div>
                <div><span className="text-gray-500">Items:</span> <span className="text-white">{selectedOrder.itemCount}</span></div>
              </div>
              <div className="border-t border-white/10 pt-3">
                <h3 className="text-sm font-medium text-gray-400 mb-2">Line Items</h3>
                {selectedOrder.items?.map((item: any, i: number) => (
                  <div key={i} className={`flex items-center justify-between py-1.5 text-sm ${item.voidedAt ? 'line-through opacity-50' : ''}`}>
                    <span className="text-white">{item.quantity}x {item.itemName}</span>
                    <span className="text-gray-400 font-mono">${(item.unitPrice * item.quantity).toFixed(2)}</span>
                  </div>
                ))}
              </div>
              <div className="border-t border-white/10 pt-3 space-y-1 text-sm">
                <div className="flex justify-between"><span className="text-gray-500">Subtotal</span><span className="text-white font-mono">${selectedOrder.subtotal.toFixed(2)}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Tax</span><span className="text-white font-mono">${selectedOrder.taxTotal.toFixed(2)}</span></div>
                {selectedOrder.discountTotal > 0 && (
                  <div className="flex justify-between"><span className="text-gray-500">Discount</span><span className="text-red-400 font-mono">-${selectedOrder.discountTotal.toFixed(2)}</span></div>
                )}
                <div className="flex justify-between font-bold text-base pt-1 border-t border-white/10"><span className="text-white">Total</span><span className="text-white font-mono">${selectedOrder.total.toFixed(2)}</span></div>
              </div>
              {selectedOrder.payments?.length > 0 && (
                <div className="border-t border-white/10 pt-3">
                  <h3 className="text-sm font-medium text-gray-400 mb-2">Payments</h3>
                  {selectedOrder.payments.map((p: any, i: number) => (
                    <div key={i} className={`flex items-center justify-between py-1.5 text-sm ${p.voidedAt ? 'line-through opacity-50' : ''}`}>
                      <span className="text-white capitalize">{p.method}{p.tipAmount > 0 ? ` (tip: $${p.tipAmount.toFixed(2)})` : ''}</span>
                      <span className="text-gray-400 font-mono">${p.amount.toFixed(2)}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
