'use client';

import { useEffect, useState } from 'react';
import {
  Search,
  Loader2,
  MoreHorizontal,
  Building2,
  Package,
  Truck,
  CheckCircle,
  XCircle,
  Clock,
} from 'lucide-react';

interface SalesOrder {
  id: string;
  orderNumber: string;
  customerId: string;
  status: string;
  orderDate: string;
  expectedDelivery: string | null;
  subtotal: number;
  shipping: number;
  tax: number;
  total: number;
  customer: { name: string };
  items: Array<{ id: string }>;
}

const statusConfig: Record<string, { icon: React.ComponentType<{ className?: string }>; color: string; label: string }> = {
  pending: { icon: Clock, color: 'text-yellow-400 bg-yellow-500/20', label: 'Pending' },
  confirmed: { icon: CheckCircle, color: 'text-blue-400 bg-blue-500/20', label: 'Confirmed' },
  processing: { icon: Package, color: 'text-brand-secondary-light bg-brand-secondary/20', label: 'Processing' },
  shipped: { icon: Truck, color: 'text-brand bg-brand-deep/20', label: 'Shipped' },
  delivered: { icon: CheckCircle, color: 'text-green-400 bg-green-500/20', label: 'Delivered' },
  cancelled: { icon: XCircle, color: 'text-red-400 bg-red-500/20', label: 'Cancelled' },
};

export default function SalesOrdersPage() {
  const [orders, setOrders] = useState<SalesOrder[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState('');

  useEffect(() => {
    const fetchOrders = async () => {
      try {
        const res = await fetch('/api/erp/crm?type=sales-orders');
        if (res.ok) {
          const data = await res.json();
          setOrders(data.salesOrders || []);
        }
      } catch (err) {
        console.error('Failed to fetch orders:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchOrders();
  }, []);

  const filteredOrders = orders.filter((o) => {
    const matchesSearch =
      o.orderNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
      o.customer.name.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = !filterStatus || o.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-brand-deep" />
      </div>
    );
  }

  const openOrdersTotal = orders
    .filter((o) => !['delivered', 'cancelled'].includes(o.status))
    .reduce((sum, o) => sum + o.total, 0);

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Sales Orders</h1>
          <p className="text-gray-400">
            Open Orders: <span className="text-brand font-semibold">${openOrdersTotal.toLocaleString()}</span>
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl p-4">
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search orders..."
              className="w-full pl-10 pr-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50"
            />
          </div>
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)}
            className="px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
          >
            <option value="">All Statuses</option>
            {Object.entries(statusConfig).map(([key, cfg]) => (
              <option key={key} value={key}>{cfg.label}</option>
            ))}
          </select>
        </div>
      </div>

      {/* Orders Table */}
      <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-brand-bg-surface/30 bg-white/5">
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-400">Order #</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-400">Customer</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Status</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Items</th>
                <th className="text-right py-3 px-4 text-sm font-medium text-gray-400">Total</th>
                <th className="text-right py-3 px-4 text-sm font-medium text-gray-400">Order Date</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-brand-bg-surface/20">
              {filteredOrders.length === 0 ? (
                <tr>
                  <td colSpan={7} className="py-12 text-center text-gray-500">
                    No orders found
                  </td>
                </tr>
              ) : (
                filteredOrders.map((order) => {
                  const statusInfo = statusConfig[order.status] || statusConfig.pending;
                  const StatusIcon = statusInfo.icon;

                  return (
                    <tr key={order.id} className="hover:bg-white/5 transition-colors">
                      <td className="py-3 px-4 font-medium text-white">{order.orderNumber}</td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2 text-gray-300">
                          <Building2 className="w-4 h-4 text-gray-500" />
                          {order.customer.name}
                        </div>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs ${statusInfo.color}`}>
                          <StatusIcon className="w-3 h-3" />
                          {statusInfo.label}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-center text-gray-400">{order.items.length}</td>
                      <td className="py-3 px-4 text-right text-green-400 font-medium">
                        ${order.total.toLocaleString()}
                      </td>
                      <td className="py-3 px-4 text-right text-gray-500">
                        {new Date(order.orderDate).toLocaleDateString()}
                      </td>
                      <td className="py-3 px-4 text-center">
                        <button className="p-1 text-gray-500 hover:text-brand">
                          <MoreHorizontal className="w-5 h-5" />
                        </button>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
