'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Boxes, Plus, Package, Tag, DollarSign,
  Loader2, Search, Filter, AlertTriangle
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface Product {
  id: string;
  sku: string;
  name: string;
  description?: string;
  category?: string;
  costPrice: number;
  sellPrice: number;
  reorderLevel: number;
  isActive: boolean;
  supplier?: { name: string; code: string };
  inventoryItems?: Array<{ quantity: number; status: string }>;
}

interface Supplier {
  id: string;
  name: string;
  code: string;
}

export default function ProductsPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [suppliers, setSuppliers] = useState<Supplier[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterCategory, setFilterCategory] = useState<string>('all');
  const [formData, setFormData] = useState({
    sku: '',
    name: '',
    description: '',
    category: '',
    costPrice: '',
    sellPrice: '',
    reorderLevel: '10',
    supplierId: '',
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const [prodRes, suppRes] = await Promise.all([
        fetch('/api/erp/inventory?type=products'),
        fetch('/api/erp/inventory?type=suppliers'),
      ]);
      const prodData = await prodRes.json();
      const suppData = await suppRes.json();
      setProducts(prodData.products || []);
      setSuppliers(suppData.suppliers || []);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.sku || !formData.name || !formData.costPrice || !formData.sellPrice) return;

    setSubmitting(true);
    try {
      const res = await fetch('/api/erp/inventory', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'product',
          data: {
            sku: formData.sku,
            name: formData.name,
            description: formData.description || null,
            category: formData.category || null,
            costPrice: parseFloat(formData.costPrice),
            sellPrice: parseFloat(formData.sellPrice),
            reorderLevel: parseInt(formData.reorderLevel) || 10,
            supplierId: formData.supplierId || null,
            isActive: true,
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({
          sku: '',
          name: '',
          description: '',
          category: '',
          costPrice: '',
          sellPrice: '',
          reorderLevel: '10',
          supplierId: '',
        });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to create product:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const formatCurrency = (value: number) =>
    new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value || 0);

  const getStockStatus = (product: Product) => {
    const item = product.inventoryItems?.[0];
    if (!item) return { status: 'no-stock', qty: 0 };
    return { status: item.status, qty: item.quantity };
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'in-stock': return 'bg-green-500/10 text-green-400';
      case 'low-stock': return 'bg-yellow-500/10 text-yellow-400';
      case 'out-of-stock': return 'bg-red-500/10 text-red-400';
      default: return 'bg-gray-500/10 text-gray-400';
    }
  };

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

  const filteredProducts = products.filter(prod => {
    const matchesSearch = (prod.name?.toLowerCase() || '').includes(searchTerm.toLowerCase()) ||
                          (prod.sku?.toLowerCase() || '').includes(searchTerm.toLowerCase());
    const matchesFilter = filterCategory === 'all' || prod.category === filterCategory;
    return matchesSearch && matchesFilter;
  });

  const totalProducts = products.length;
  const lowStockCount = products.filter(p => getStockStatus(p).status === 'low-stock').length;
  const outOfStockCount = products.filter(p => getStockStatus(p).status === 'out-of-stock').length;

  return (
    <div className="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">
            <Boxes className="w-7 h-7 text-brand" />
            Products
          </h1>
          <p className="text-gray-400 mt-1">Manage your product catalog</p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-brand-deep hover:bg-brand-deep text-white rounded-lg transition-colors"
        >
          <Plus className="w-4 h-4" />
          Add Product
        </button>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Products</p>
          <p className="text-xl font-bold text-white">{totalProducts}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">In Stock</p>
          <p className="text-xl font-bold text-green-400">
            {products.filter(p => getStockStatus(p).status === 'in-stock').length}
          </p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-yellow-400" />
            <p className="text-sm text-gray-400">Low Stock</p>
          </div>
          <p className="text-xl font-bold text-yellow-400">{lowStockCount}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-red-400" />
            <p className="text-sm text-gray-400">Out of Stock</p>
          </div>
          <p className="text-xl font-bold text-red-400">{outOfStockCount}</p>
        </div>
      </div>

      {/* Filters */}
      <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-4 h-4 text-gray-500" />
          <input
            type="text"
            placeholder="Search products..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:border-brand-deep focus:outline-none"
          />
        </div>
        <select
          value={filterCategory}
          onChange={(e) => setFilterCategory(e.target.value)}
          className="px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
        >
          {categories.map((cat) => (
            <option key={cat || 'uncategorized'} value={cat}>
              {cat === 'all' ? 'All Categories' : cat || 'Uncategorized'}
            </option>
          ))}
        </select>
      </div>

      {/* Products Grid */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filteredProducts.length === 0 ? (
            <div className="col-span-full text-center py-12 text-gray-500 bg-white/5 border border-white/10 rounded-lg">
              No products found
            </div>
          ) : (
            filteredProducts.map((product, index) => {
              const stock = getStockStatus(product);
              return (
                <motion.div
                  key={product.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.03 }}
                  className="p-4 bg-white/5 border border-white/10 rounded-lg hover:border-brand-deep/30 transition-colors"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-brand-deep/10 rounded-lg">
                        <Package className="w-5 h-5 text-brand" />
                      </div>
                      <div>
                        <p className="text-xs font-mono text-gray-500">{product.sku}</p>
                        <h3 className="font-semibold text-white">{product.name}</h3>
                      </div>
                    </div>
                    <span className={`text-xs px-2 py-1 rounded ${getStatusColor(stock.status)}`}>
                      {stock.qty} units
                    </span>
                  </div>
                  {product.description && (
                    <p className="text-sm text-gray-400 mb-3 line-clamp-2">{product.description}</p>
                  )}
                  <div className="flex items-center justify-between text-sm">
                    <div className="flex items-center gap-4">
                      <span className="text-gray-500">Cost: {formatCurrency(product.costPrice)}</span>
                      <span className="text-brand">Sell: {formatCurrency(product.sellPrice)}</span>
                    </div>
                    {product.category && (
                      <span className="text-xs px-2 py-0.5 bg-brand-secondary/10 text-brand-secondary-light rounded">
                        {product.category}
                      </span>
                    )}
                  </div>
                  {product.supplier && (
                    <p className="text-xs text-gray-500 mt-2">Supplier: {product.supplier.name}</p>
                  )}
                </motion.div>
              );
            })
          )}
        </div>
      )}

      {/* Add Product Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="Add New Product"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">SKU</label>
              <input
                type="text"
                value={formData.sku}
                onChange={(e) => setFormData({ ...formData, sku: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
                placeholder="e.g., PRD-001"
                required
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Category</label>
              <input
                type="text"
                value={formData.category}
                onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
                placeholder="e.g., Electronics"
              />
            </div>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Product Name</label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
              required
            />
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Description</label>
            <textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none resize-none"
              rows={2}
            />
          </div>
          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">Cost Price</label>
              <input
                type="number"
                step="0.01"
                value={formData.costPrice}
                onChange={(e) => setFormData({ ...formData, costPrice: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
                required
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Sell Price</label>
              <input
                type="number"
                step="0.01"
                value={formData.sellPrice}
                onChange={(e) => setFormData({ ...formData, sellPrice: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
                required
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Reorder Level</label>
              <input
                type="number"
                value={formData.reorderLevel}
                onChange={(e) => setFormData({ ...formData, reorderLevel: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
              />
            </div>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Supplier</label>
            <select
              value={formData.supplierId}
              onChange={(e) => setFormData({ ...formData, supplierId: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
            >
              <option value="">Select supplier (optional)...</option>
              {suppliers.map((sup) => (
                <option key={sup.id} value={sup.id}>
                  {sup.name}
                </option>
              ))}
            </select>
          </div>
          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={() => setShowModal(false)}
              className="px-4 py-2 text-gray-400 hover:text-white transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting || !formData.sku || !formData.name || !formData.costPrice || !formData.sellPrice}
              className="px-4 py-2 bg-brand-deep hover:bg-brand-deep disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg transition-colors flex items-center gap-2"
            >
              {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
              Add Product
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
