'use client';

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Package,
  Truck,
  CheckCircle,
  Clock,
  XCircle,
  Search,
  RefreshCw,
  Eye,
  Download,
  Filter,
} from 'lucide-react';
import { InternalHeader } from '@/components/ui/internal-header';

interface SwagOrder {
  id: string;
  orderNumber: string;
  customerName: string;
  customerEmail: string;
  status: string;
  paymentStatus: string;
  subtotal: number;
  tax: number;
  shipping: number;
  total: number;
  trackingNumber: string | null;
  createdAt: string;
  items: Array<{
    id: string;
    quantity: number;
    unitPrice: number;
    totalPrice: number;
    product: { name: string };
    variant: { size: string; color: string };
  }>;
}

const STATUS_COLORS: Record<string, string> = {
  pending: 'bg-yellow-500/20 text-yellow-400',
  confirmed: 'bg-blue-500/20 text-blue-400',
  processing: 'bg-brand-secondary/20 text-brand-secondary-light',
  shipped: 'bg-brand-deep/20 text-brand',
  delivered: 'bg-green-500/20 text-green-400',
  cancelled: 'bg-red-500/20 text-red-400',
};

const STATUS_ICONS: Record<string, typeof Clock> = {
  pending: Clock,
  confirmed: CheckCircle,
  processing: Package,
  shipped: Truck,
  delivered: CheckCircle,
  cancelled: XCircle,
};

export default function SwagOrdersPage() {
  const [orders, setOrders] = useState<SwagOrder[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedOrder, setSelectedOrder] = useState<SwagOrder | null>(null);
  const [filterStatus, setFilterStatus] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');

  const fetchOrders = async () => {
    try {
      const params = new URLSearchParams();
      if (filterStatus !== 'all') params.set('status', filterStatus);
      params.set('limit', '100');
      
      const res = await fetch(`/api/swag/orders?${params}`);
      const data = await res.json();
      setOrders(data.orders || []);
    } catch (error) {
      console.error('Error fetching orders:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const filteredOrders = orders.filter(o =>
    o.orderNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
    o.customerName.toLowerCase().includes(searchQuery.toLowerCase()) ||
    o.customerEmail.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const stats = {
    total: orders.length,
    pending: orders.filter(o => o.status === 'pending').length,
    processing: orders.filter(o => ['confirmed', 'processing'].includes(o.status)).length,
    shipped: orders.filter(o => o.status === 'shipped').length,
    completed: orders.filter(o => o.status === 'delivered').length,
    revenue: orders.filter(o => o.paymentStatus === 'paid').reduce((sum, o) => sum + o.total, 0),
  };

  return (
    <div className="min-h-screen bg-brand-bg">
      <InternalHeader />
      
      <main className="pt-20 pb-16 px-4 sm:px-6 lg:px-8">
        <div className="max-w-7xl mx-auto">
          {/* Header */}
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-8">
            <div>
              <h1 className="text-3xl font-bold text-white flex items-center gap-3">
                <Truck className="w-8 h-8 text-brand" />
                Swag Orders
              </h1>
              <p className="text-gray-400 mt-1">Manage and track customer orders</p>
            </div>
            <button
              onClick={fetchOrders}
              className="flex items-center gap-2 px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white hover:bg-white/10 transition-colors"
            >
              <RefreshCw className="w-4 h-4" />
              Refresh
            </button>
          </div>

          {/* Stats */}
          <div className="grid grid-cols-2 md:grid-cols-6 gap-4 mb-8">
            <div className="glass-card rounded-xl p-4">
              <p className="text-gray-400 text-sm">Total Orders</p>
              <p className="text-2xl font-bold text-white">{stats.total}</p>
            </div>
            <div className="glass-card rounded-xl p-4">
              <p className="text-gray-400 text-sm">Pending</p>
              <p className="text-2xl font-bold text-yellow-400">{stats.pending}</p>
            </div>
            <div className="glass-card rounded-xl p-4">
              <p className="text-gray-400 text-sm">Processing</p>
              <p className="text-2xl font-bold text-brand-secondary-light">{stats.processing}</p>
            </div>
            <div className="glass-card rounded-xl p-4">
              <p className="text-gray-400 text-sm">Shipped</p>
              <p className="text-2xl font-bold text-brand">{stats.shipped}</p>
            </div>
            <div className="glass-card rounded-xl p-4">
              <p className="text-gray-400 text-sm">Delivered</p>
              <p className="text-2xl font-bold text-green-400">{stats.completed}</p>
            </div>
            <div className="glass-card rounded-xl p-4">
              <p className="text-gray-400 text-sm">Revenue</p>
              <p className="text-2xl font-bold text-brand">${stats.revenue.toFixed(2)}</p>
            </div>
          </div>

          {/* Search & Filter */}
          <div className="flex flex-col md:flex-row gap-4 mb-6">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Search by order #, name, or email..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
              />
            </div>
            <div className="flex gap-2 overflow-x-auto">
              {['all', 'pending', 'confirmed', 'processing', 'shipped', 'delivered'].map((status) => (
                <button
                  key={status}
                  onClick={() => setFilterStatus(status)}
                  className={`px-4 py-2 rounded-lg capitalize whitespace-nowrap transition-all ${
                    filterStatus === status
                      ? 'bg-brand-deep text-white'
                      : 'bg-white/5 text-gray-400 hover:bg-white/10'
                  }`}
                >
                  {status}
                </button>
              ))}
            </div>
          </div>

          {/* Orders Table */}
          <div className="glass-card rounded-xl overflow-hidden">
            {loading ? (
              <div className="p-8 text-center text-gray-400">Loading orders...</div>
            ) : filteredOrders.length === 0 ? (
              <div className="p-8 text-center text-gray-400">No orders found</div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-white/5">
                    <tr>
                      <th className="text-left p-4 text-gray-400 font-medium">Order #</th>
                      <th className="text-left p-4 text-gray-400 font-medium">Customer</th>
                      <th className="text-left p-4 text-gray-400 font-medium">Items</th>
                      <th className="text-center p-4 text-gray-400 font-medium">Status</th>
                      <th className="text-right p-4 text-gray-400 font-medium">Total</th>
                      <th className="text-left p-4 text-gray-400 font-medium">Date</th>
                      <th className="text-right p-4 text-gray-400 font-medium">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/5">
                    {filteredOrders.map((order) => {
                      const StatusIcon = STATUS_ICONS[order.status] || Clock;
                      return (
                        <tr key={order.id} className="hover:bg-white/5">
                          <td className="p-4">
                            <span className="text-brand font-mono font-semibold">{order.orderNumber}</span>
                          </td>
                          <td className="p-4">
                            <div>
                              <p className="text-white font-medium">{order.customerName}</p>
                              <p className="text-gray-400 text-sm">{order.customerEmail}</p>
                            </div>
                          </td>
                          <td className="p-4">
                            <span className="text-white">{order.items.length} items</span>
                          </td>
                          <td className="p-4 text-center">
                            <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm capitalize ${STATUS_COLORS[order.status]}`}>
                              <StatusIcon className="w-4 h-4" />
                              {order.status}
                            </span>
                          </td>
                          <td className="p-4 text-right">
                            <span className="text-white font-semibold">${order.total.toFixed(2)}</span>
                          </td>
                          <td className="p-4">
                            <span className="text-gray-400 text-sm">
                              {new Date(order.createdAt).toLocaleDateString()}
                            </span>
                          </td>
                          <td className="p-4 text-right">
                            <button
                              onClick={() => setSelectedOrder(order)}
                              className="p-2 bg-white/10 text-white rounded hover:bg-white/20"
                            >
                              <Eye className="w-4 h-4" />
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* Order Detail Modal */}
          {selectedOrder && (
            <div
              className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4"
              onClick={() => setSelectedOrder(null)}
            >
              <div
                className="bg-brand-bg border border-white/10 rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto"
                onClick={(e) => e.stopPropagation()}
              >
                <div className="p-6">
                  <div className="flex items-center justify-between mb-6">
                    <h2 className="text-2xl font-bold text-white">Order {selectedOrder.orderNumber}</h2>
                    <button
                      onClick={() => setSelectedOrder(null)}
                      className="text-gray-400 hover:text-white"
                    >
                      <XCircle className="w-6 h-6" />
                    </button>
                  </div>

                  <div className="grid md:grid-cols-2 gap-6 mb-6">
                    <div>
                      <h3 className="text-gray-400 text-sm mb-2">Customer</h3>
                      <p className="text-white font-medium">{selectedOrder.customerName}</p>
                      <p className="text-gray-400">{selectedOrder.customerEmail}</p>
                    </div>
                    <div>
                      <h3 className="text-gray-400 text-sm mb-2">Status</h3>
                      <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm capitalize ${STATUS_COLORS[selectedOrder.status]}`}>
                        {selectedOrder.status}
                      </span>
                    </div>
                  </div>

                  <div className="mb-6">
                    <h3 className="text-gray-400 text-sm mb-3">Items</h3>
                    <div className="space-y-3">
                      {selectedOrder.items.map((item) => (
                        <div key={item.id} className="flex justify-between items-center bg-white/5 rounded-lg p-3">
                          <div>
                            <p className="text-white font-medium">{item.product.name}</p>
                            <p className="text-gray-400 text-sm">{item.variant.size} / {item.variant.color}</p>
                          </div>
                          <div className="text-right">
                            <p className="text-white">x{item.quantity}</p>
                            <p className="text-brand">${item.totalPrice.toFixed(2)}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="border-t border-white/10 pt-4">
                    <div className="flex justify-between mb-2">
                      <span className="text-gray-400">Subtotal</span>
                      <span className="text-white">${selectedOrder.subtotal.toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between mb-2">
                      <span className="text-gray-400">Tax</span>
                      <span className="text-white">${selectedOrder.tax.toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between mb-2">
                      <span className="text-gray-400">Shipping</span>
                      <span className="text-white">${selectedOrder.shipping.toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between text-lg font-bold">
                      <span className="text-white">Total</span>
                      <span className="text-brand">${selectedOrder.total.toFixed(2)}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </main>
    </div>
  );
}
