'use client';

import { ATAButton } from '@/components/agent-hierarchy/ata-flyout';
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Package, Boxes, Truck, ShoppingCart, AlertTriangle,
  TrendingUp, ArrowRight, Plus, DollarSign, MapPin, Loader2
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface InventoryData {
  summary: {
    totalProducts: number;
    totalStock: number;
    stockValue: number;
    lowStockCount: number;
    outOfStockCount: number;
    pendingOrdersCount: number;
    pendingOrdersValue: number;
    locations: number;
  };
  lowStockAlerts: Array<{
    id: string;
    quantity: number;
    status: string;
    product: { sku: string; name: string; reorderLevel: number };
  }>;
  recentMovements: Array<{
    id: string;
    type: string;
    quantity: number;
    createdAt: string;
    product?: { sku: string; name: string };
  }>;
  pendingOrders: Array<{
    id: string;
    orderNumber: string;
    status: string;
    total: number;
    expectedDate: string;
  }>;
}

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

export default function InventoryDashboard() {
  const [data, setData] = useState<InventoryData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [suppliers, setSuppliers] = useState<Supplier[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [formData, setFormData] = useState({
    sku: '',
    name: '',
    description: '',
    category: '',
    supplierId: '',
    costPrice: '',
    sellPrice: '',
    reorderLevel: '10',
  });

  const fetchData = () => {
    setLoading(true);
    setError(null);
    fetch('/api/erp/inventory')
      .then((r) => {
        if (!r.ok) throw new Error('Failed to fetch inventory data');
        return r.json();
      })
      .then((d) => {
        if (d.success === false) throw new Error(d.error || 'Failed to fetch inventory data');
        setData(d);
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
    
    // Fetch suppliers
    fetch('/api/erp/inventory?type=suppliers')
      .then(r => r.json())
      .then(d => setSuppliers(d.suppliers || []))
      .catch(() => {});
  };

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

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.sku || !formData.name) 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 || 'General',
            supplierId: formData.supplierId || null,
            costPrice: formData.costPrice ? parseFloat(formData.costPrice) : 0,
            sellPrice: formData.sellPrice ? parseFloat(formData.sellPrice) : 0,
            reorderLevel: parseInt(formData.reorderLevel) || 10,
            isActive: true,
          },
        }),
      });
      
      if (res.ok) {
        setShowModal(false);
        setFormData({ sku: '', name: '', description: '', category: '', supplierId: '', costPrice: '', sellPrice: '', reorderLevel: '10' });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to add product:', error);
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="h-8 w-48 bg-white/10 rounded animate-pulse" />
        <div className="grid grid-cols-4 gap-4">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="h-32 bg-white/5 rounded-lg animate-pulse" />
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-bold text-white">Inventory Management</h1>
          <button onClick={fetchData} className="px-4 py-2 bg-brand-deep/20 text-brand rounded-lg">
            Retry
          </button>
        </div>
        <div className="glass-card p-8 border border-red-500/30 text-center">
          <AlertTriangle className="w-12 h-12 text-red-400 mx-auto mb-4" />
          <p className="text-red-400">{error}</p>
          <p className="text-gray-500 text-sm mt-2">Please try refreshing the page or check the database connection.</p>
        </div>
      </div>
    );
  }

  const summary = data?.summary || {} as InventoryData['summary'];

  const kpiCards = [
    {
      label: 'Total Products',
      value: summary.totalProducts || 0,
      icon: <Boxes className="w-5 h-5" />,
      color: 'green',
    },
    {
      label: 'Stock Value',
      value: formatCurrency(summary.stockValue),
      icon: <DollarSign className="w-5 h-5" />,
      color: 'cyan',
    },
    {
      label: 'Low Stock Alerts',
      value: summary.lowStockCount || 0,
      icon: <AlertTriangle className="w-5 h-5" />,
      color: summary.lowStockCount > 0 ? 'amber' : 'gray',
    },
    {
      label: 'Pending Orders',
      value: summary.pendingOrdersCount || 0,
      icon: <ShoppingCart className="w-5 h-5" />,
      color: 'purple',
    },
  ];

  const colorClasses: Record<string, { bg: string; text: string; border: string }> = {
    cyan: { bg: 'bg-brand-deep/10', text: 'text-brand', border: 'border-brand-deep/30' },
    green: { bg: 'bg-green-500/10', text: 'text-green-400', border: 'border-green-500/30' },
    purple: { bg: 'bg-brand-secondary/10', text: 'text-brand-secondary-light', border: 'border-brand-secondary/30' },
    amber: { bg: 'bg-amber-500/10', text: 'text-amber-400', border: 'border-amber-500/30' },
    gray: { bg: 'bg-gray-500/10', text: 'text-gray-400', border: 'border-gray-500/30' },
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Inventory Management</h1>
          <p className="text-gray-400 text-sm">Products, stock levels, and purchase orders</p>
        </div>
        <div className="flex items-center gap-3">
          <ATAButton agentId="agent-inventory" variant="compact" />
          <button 
            onClick={() => setShowModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-green-500/20 text-green-400 rounded-lg hover:bg-green-500/30 transition-colors border border-green-500/30"
          >
            <Plus className="w-4 h-4" />
            <span>Add Product</span>
          </button>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpiCards.map((card, idx) => (
          <motion.div
            key={card.label}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: idx * 0.1 }}
            className={`glass-card p-4 border ${colorClasses[card.color].border}`}
          >
            <div className="flex items-center justify-between mb-2">
              <span className="text-gray-400 text-sm">{card.label}</span>
              <div className={`p-1.5 rounded ${colorClasses[card.color].bg}`}>
                <span className={colorClasses[card.color].text}>{card.icon}</span>
              </div>
            </div>
            <span className="text-2xl font-bold text-white">{card.value}</span>
          </motion.div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Low Stock Alerts */}
        <div className="glass-card p-6 border border-white/10">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2 mb-4">
            <AlertTriangle className="w-5 h-5 text-amber-400" />
            Low Stock Alerts
          </h2>
          {data?.lowStockAlerts?.length ? (
            <div className="space-y-3">
              {data.lowStockAlerts.filter(item => item && item.id).map((item) => (
                <div key={item.id} className="flex items-center justify-between p-3 bg-amber-500/5 rounded-lg border border-amber-500/20">
                  <div>
                    <p className="text-white text-sm font-medium">{item.product?.name || 'Unknown Product'}</p>
                    <p className="text-gray-500 text-xs">SKU: {item.product?.sku || 'N/A'}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-amber-400 font-semibold">{item.quantity ?? 0} left</p>
                    <p className="text-gray-500 text-xs">Reorder at {item.product?.reorderLevel ?? 10}</p>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <Package className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>All stock levels healthy</p>
            </div>
          )}
        </div>

        {/* Recent Stock Movements */}
        <div className="glass-card p-6 border border-white/10">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2 mb-4">
            <TrendingUp className="w-5 h-5 text-brand" />
            Recent Movements
          </h2>
          {data?.recentMovements?.length ? (
            <div className="space-y-3">
              {data.recentMovements.filter(m => m && m.id).map((movement) => (
                <div key={movement.id} className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                  <div className="flex items-center gap-3">
                    <div className={`p-2 rounded ${movement.type === 'in' ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
                      <ArrowRight className={`w-4 h-4 ${movement.type === 'in' ? 'text-green-400 rotate-180' : 'text-red-400'}`} />
                    </div>
                    <div>
                      <p className="text-white text-sm font-medium">{movement.product?.name || 'Unknown'}</p>
                      <p className="text-gray-500 text-xs capitalize">{movement.type || 'movement'}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className={`font-semibold ${movement.type === 'in' ? 'text-green-400' : 'text-red-400'}`}>
                      {movement.type === 'in' ? '+' : '-'}{movement.quantity ?? 0}
                    </p>
                    <p className="text-gray-500 text-xs">
                      {movement.createdAt ? new Date(movement.createdAt).toLocaleDateString() : 'N/A'}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <TrendingUp className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>No recent movements</p>
            </div>
          )}
        </div>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="p-4 bg-white/5 rounded-lg border border-white/10">
          <div className="flex items-center gap-2 mb-1">
            <Package className="w-4 h-4 text-gray-400" />
            <p className="text-gray-500 text-xs">Total Units</p>
          </div>
          <p className="text-white font-semibold text-lg">{summary.totalStock || 0}</p>
        </div>
        <div className="p-4 bg-white/5 rounded-lg border border-white/10">
          <div className="flex items-center gap-2 mb-1">
            <MapPin className="w-4 h-4 text-gray-400" />
            <p className="text-gray-500 text-xs">Locations</p>
          </div>
          <p className="text-white font-semibold text-lg">{summary.locations || 1}</p>
        </div>
        <div className="p-4 bg-white/5 rounded-lg border border-white/10">
          <div className="flex items-center gap-2 mb-1">
            <Truck className="w-4 h-4 text-gray-400" />
            <p className="text-gray-500 text-xs">Pending Value</p>
          </div>
          <p className="text-brand-secondary-light font-semibold text-lg">{formatCurrency(summary.pendingOrdersValue)}</p>
        </div>
        <div className="p-4 bg-white/5 rounded-lg border border-white/10">
          <div className="flex items-center gap-2 mb-1">
            <AlertTriangle className="w-4 h-4 text-gray-400" />
            <p className="text-gray-500 text-xs">Out of Stock</p>
          </div>
          <p className="text-red-400 font-semibold text-lg">{summary.outOfStockCount || 0}</p>
        </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-green-500/50 focus:outline-none"
                placeholder="e.g., PROD-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-green-500/50 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-green-500/50 focus:outline-none"
              placeholder="e.g., Widget Pro 2000"
              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-green-500/50 focus:outline-none resize-none"
              rows={2}
              placeholder="Brief product description..."
            />
          </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-green-500/50 focus:outline-none"
            >
              <option value="" className="bg-brand-bg">Select supplier...</option>
              {suppliers.map((sup) => (
                <option key={sup.id} value={sup.id} className="bg-brand-bg">
                  {sup.name}
                </option>
              ))}
            </select>
          </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"
                min="0"
                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-green-500/50 focus:outline-none"
                placeholder="0.00"
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Sell Price</label>
              <input
                type="number"
                step="0.01"
                min="0"
                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-green-500/50 focus:outline-none"
                placeholder="0.00"
              />
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Reorder Level</label>
              <input
                type="number"
                min="0"
                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-green-500/50 focus:outline-none"
              />
            </div>
          </div>
          
          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={() => setShowModal(false)}
              className="flex-1 px-4 py-2 bg-white/5 text-gray-400 rounded-lg hover:bg-white/10 transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="flex-1 px-4 py-2 bg-green-500/20 text-green-400 rounded-lg hover:bg-green-500/30 transition-colors border border-green-500/30 disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
              {submitting ? 'Adding...' : 'Add Product'}
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
