'use client';

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Package,
  TrendingUp,
  AlertTriangle,
  Search,
  RefreshCw,
  Plus,
  Minus,
  DollarSign,
  ShoppingBag,
  BarChart3,
  Filter,
  Download,
  ArrowUp,
  ArrowDown,
} from 'lucide-react';
import { InternalHeader } from '@/components/ui/internal-header';

interface SwagVariant {
  id: string;
  sku: string;
  size: string;
  color: string;
  stock: number;
  reserved: number;
  price: number | null;
  isActive: boolean;
}

interface SwagProduct {
  id: string;
  sku: string;
  name: string;
  description: string;
  category: string;
  basePrice: number;
  imageUrl: string;
  isActive: boolean;
  variants: SwagVariant[];
}

interface InventoryStats {
  totalProducts: number;
  totalVariants: number;
  totalStock: number;
  lowStock: number;
  outOfStock: number;
}

interface Analytics {
  summary: {
    totalRevenue: number;
    totalOrders: number;
    avgOrderValue: number;
    totalItems: number;
    period: string;
  };
  topProducts: Array<{ id: string; name: string; quantity: number; revenue: number }>;
  categoryBreakdown: Record<string, { quantity: number; revenue: number }>;
}

export default function SwagInventoryPage() {
  const [products, setProducts] = useState<SwagProduct[]>([]);
  const [stats, setStats] = useState<InventoryStats | null>(null);
  const [analytics, setAnalytics] = useState<Analytics | null>(null);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [adjustingVariant, setAdjustingVariant] = useState<string | null>(null);
  const [adjustmentValue, setAdjustmentValue] = useState(0);

  const fetchData = async () => {
    try {
      const [invRes, analyticsRes] = await Promise.all([
        fetch('/api/swag/admin/inventory'),
        fetch('/api/swag/admin/analytics?days=30'),
      ]);
      const invData = await invRes.json();
      const analyticsData = await analyticsRes.json();
      
      setProducts(invData.products || []);
      setStats(invData.stats || null);
      setAnalytics(analyticsData || null);
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const adjustStock = async (variantId: string, adjustment: number) => {
    try {
      const res = await fetch('/api/swag/admin/inventory', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ variantId, adjustment }),
      });
      if (res.ok) {
        fetchData();
        setAdjustingVariant(null);
        setAdjustmentValue(0);
      }
    } catch (error) {
      console.error('Error adjusting stock:', error);
    }
  };

  const filteredProducts = products.filter(p => {
    const matchesSearch = p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         p.sku.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || p.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  const categories = ['all', ...new Set(products.map(p => p.category))];

  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">
                <Package className="w-8 h-8 text-brand" />
                Swag Inventory Management
              </h1>
              <p className="text-gray-400 mt-1">Track stock, manage orders, view analytics</p>
            </div>
            <div className="flex gap-3">
              <button
                onClick={fetchData}
                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>
              <a
                href="/swag-store"
                target="_blank"
                className="flex items-center gap-2 px-4 py-2 bg-brand-deep rounded-lg text-white hover:bg-brand-deep transition-colors"
              >
                <ShoppingBag className="w-4 h-4" />
                View Store
              </a>
            </div>
          </div>

          {/* Stats Cards */}
          {stats && (
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-8">
              <div className="glass-card rounded-xl p-4">
                <div className="flex items-center justify-between">
                  <Package className="w-8 h-8 text-brand" />
                  <span className="text-2xl font-bold text-white">{stats.totalProducts}</span>
                </div>
                <p className="text-gray-400 text-sm mt-2">Products</p>
              </div>
              <div className="glass-card rounded-xl p-4">
                <div className="flex items-center justify-between">
                  <BarChart3 className="w-8 h-8 text-brand-secondary-light" />
                  <span className="text-2xl font-bold text-white">{stats.totalVariants}</span>
                </div>
                <p className="text-gray-400 text-sm mt-2">Variants</p>
              </div>
              <div className="glass-card rounded-xl p-4">
                <div className="flex items-center justify-between">
                  <TrendingUp className="w-8 h-8 text-green-400" />
                  <span className="text-2xl font-bold text-white">{stats.totalStock}</span>
                </div>
                <p className="text-gray-400 text-sm mt-2">Total Stock</p>
              </div>
              <div className="glass-card rounded-xl p-4">
                <div className="flex items-center justify-between">
                  <AlertTriangle className="w-8 h-8 text-yellow-400" />
                  <span className="text-2xl font-bold text-white">{stats.lowStock}</span>
                </div>
                <p className="text-gray-400 text-sm mt-2">Low Stock</p>
              </div>
              <div className="glass-card rounded-xl p-4">
                <div className="flex items-center justify-between">
                  <AlertTriangle className="w-8 h-8 text-red-400" />
                  <span className="text-2xl font-bold text-white">{stats.outOfStock}</span>
                </div>
                <p className="text-gray-400 text-sm mt-2">Out of Stock</p>
              </div>
            </div>
          )}

          {/* Analytics Section */}
          {analytics && (
            <div className="grid md:grid-cols-2 gap-6 mb-8">
              <div className="glass-card rounded-xl p-6">
                <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                  <DollarSign className="w-5 h-5 text-brand" />
                  Revenue Summary (30 days)
                </h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-gray-400 text-sm">Total Revenue</p>
                    <p className="text-2xl font-bold text-brand">${analytics.summary.totalRevenue.toFixed(2)}</p>
                  </div>
                  <div>
                    <p className="text-gray-400 text-sm">Total Orders</p>
                    <p className="text-2xl font-bold text-white">{analytics.summary.totalOrders}</p>
                  </div>
                  <div>
                    <p className="text-gray-400 text-sm">Avg Order Value</p>
                    <p className="text-2xl font-bold text-brand-secondary-light">${analytics.summary.avgOrderValue.toFixed(2)}</p>
                  </div>
                  <div>
                    <p className="text-gray-400 text-sm">Items Sold</p>
                    <p className="text-2xl font-bold text-white">{analytics.summary.totalItems}</p>
                  </div>
                </div>
              </div>

              <div className="glass-card rounded-xl p-6">
                <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                  <TrendingUp className="w-5 h-5 text-brand" />
                  Top Products
                </h3>
                <div className="space-y-3">
                  {analytics.topProducts.slice(0, 5).map((product, idx) => (
                    <div key={product.id} className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <span className="text-gray-500 text-sm">#{idx + 1}</span>
                        <span className="text-white truncate max-w-[200px]">{product.name}</span>
                      </div>
                      <div className="text-right">
                        <span className="text-brand font-semibold">${product.revenue.toFixed(2)}</span>
                        <span className="text-gray-500 text-sm ml-2">({product.quantity} sold)</span>
                      </div>
                    </div>
                  ))}
                </div>
              </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 name or SKU..."
                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">
              {categories.map((cat) => (
                <button
                  key={cat}
                  onClick={() => setSelectedCategory(cat)}
                  className={`px-4 py-2 rounded-lg capitalize transition-all ${
                    selectedCategory === cat
                      ? 'bg-brand-deep text-white'
                      : 'bg-white/5 text-gray-400 hover:bg-white/10'
                  }`}
                >
                  {cat}
                </button>
              ))}
            </div>
          </div>

          {/* Products Table */}
          <div className="glass-card rounded-xl overflow-hidden">
            {loading ? (
              <div className="p-8 text-center text-gray-400">Loading inventory...</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">Product</th>
                      <th className="text-left p-4 text-gray-400 font-medium">SKU</th>
                      <th className="text-left p-4 text-gray-400 font-medium">Variant</th>
                      <th className="text-center p-4 text-gray-400 font-medium">Stock</th>
                      <th className="text-center p-4 text-gray-400 font-medium">Reserved</th>
                      <th className="text-center p-4 text-gray-400 font-medium">Available</th>
                      <th className="text-right p-4 text-gray-400 font-medium">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/5">
                    {filteredProducts.flatMap((product) =>
                      product.variants.map((variant) => {
                        const available = variant.stock - variant.reserved;
                        const stockStatus = available === 0 ? 'out' : available <= 10 ? 'low' : 'ok';
                        return (
                          <tr key={variant.id} className="hover:bg-white/5">
                            <td className="p-4">
                              <span className="text-white font-medium">{product.name}</span>
                            </td>
                            <td className="p-4">
                              <span className="text-gray-400 font-mono text-sm">{variant.sku}</span>
                            </td>
                            <td className="p-4">
                              <span className="text-white">{variant.size} / {variant.color}</span>
                            </td>
                            <td className="p-4 text-center">
                              <span className="text-white font-semibold">{variant.stock}</span>
                            </td>
                            <td className="p-4 text-center">
                              <span className="text-yellow-400">{variant.reserved}</span>
                            </td>
                            <td className="p-4 text-center">
                              <span className={`font-semibold ${
                                stockStatus === 'out' ? 'text-red-400' :
                                stockStatus === 'low' ? 'text-yellow-400' : 'text-green-400'
                              }`}>
                                {available}
                              </span>
                            </td>
                            <td className="p-4 text-right">
                              {adjustingVariant === variant.id ? (
                                <div className="flex items-center justify-end gap-2">
                                  <input
                                    type="number"
                                    value={adjustmentValue}
                                    onChange={(e) => setAdjustmentValue(parseInt(e.target.value) || 0)}
                                    className="w-20 px-2 py-1 bg-white/10 border border-white/20 rounded text-white text-center"
                                  />
                                  <button
                                    onClick={() => adjustStock(variant.id, adjustmentValue)}
                                    className="px-3 py-1 bg-brand-deep text-white rounded hover:bg-brand-deep"
                                  >
                                    Save
                                  </button>
                                  <button
                                    onClick={() => {
                                      setAdjustingVariant(null);
                                      setAdjustmentValue(0);
                                    }}
                                    className="px-3 py-1 bg-white/10 text-white rounded hover:bg-white/20"
                                  >
                                    Cancel
                                  </button>
                                </div>
                              ) : (
                                <div className="flex items-center justify-end gap-2">
                                  <button
                                    onClick={() => adjustStock(variant.id, -1)}
                                    className="p-1 bg-red-500/20 text-red-400 rounded hover:bg-red-500/30"
                                  >
                                    <Minus className="w-4 h-4" />
                                  </button>
                                  <button
                                    onClick={() => adjustStock(variant.id, 1)}
                                    className="p-1 bg-green-500/20 text-green-400 rounded hover:bg-green-500/30"
                                  >
                                    <Plus className="w-4 h-4" />
                                  </button>
                                  <button
                                    onClick={() => {
                                      setAdjustingVariant(variant.id);
                                      setAdjustmentValue(0);
                                    }}
                                    className="px-2 py-1 bg-white/10 text-white rounded hover:bg-white/20 text-sm"
                                  >
                                    Adjust
                                  </button>
                                </div>
                              )}
                            </td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}
