import React, { useState, useEffect } from 'react';
import { Package, DollarSign, TrendingDown, Archive } from 'lucide-react';

export default function InventoryDashboard() {
  const [stats, setStats] = useState<any>(null);
  const [loading, setLoading] = useState(true);

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

  const fetchStats = async () => {
    setLoading(true);
    try {
      const itemsResult = await window.mcp.callTool('clover_list_items', {
        limit: 1000,
      });
      const items = itemsResult.items || [];

      const totalItems = items.length;
      const visibleItems = items.filter((i: any) => !i.hidden).length;
      const lowStockItems = items.filter((i: any) => (i.stockCount || 0) < 10).length;
      const totalValue = items.reduce(
        (sum: number, i: any) => sum + (i.price || 0) * (i.stockCount || 0),
        0
      );

      setStats({
        totalItems,
        visibleItems,
        lowStockItems,
        totalValue,
      });
    } catch (error) {
      console.error('Failed to fetch inventory stats:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-gray-500">Loading inventory...</div>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <h1 className="text-3xl font-bold text-gray-900 mb-6">Inventory Dashboard</h1>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <StatCard
          icon={<Package className="w-8 h-8 text-blue-600" />}
          title="Total Items"
          value={stats?.totalItems || 0}
          bgColor="bg-blue-50"
        />
        <StatCard
          icon={<Archive className="w-8 h-8 text-green-600" />}
          title="Visible Items"
          value={stats?.visibleItems || 0}
          bgColor="bg-green-50"
        />
        <StatCard
          icon={<TrendingDown className="w-8 h-8 text-red-600" />}
          title="Low Stock"
          value={stats?.lowStockItems || 0}
          bgColor="bg-red-50"
        />
        <StatCard
          icon={<DollarSign className="w-8 h-8 text-purple-600" />}
          title="Total Value"
          value={`$${((stats?.totalValue || 0) / 100).toFixed(2)}`}
          bgColor="bg-purple-50"
        />
      </div>

      <div className="bg-white rounded-lg shadow p-6">
        <h2 className="text-xl font-semibold mb-4">Quick Actions</h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <button
            onClick={() => window.mcp.showApp('inventory-detail')}
            className="px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            View Items
          </button>
          <button
            onClick={() => window.mcp.showApp('category-manager')}
            className="px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700"
          >
            Categories
          </button>
          <button
            onClick={async () => {
              const name = prompt('Item name:');
              const price = prompt('Price (in cents):');
              if (name && price) {
                await window.mcp.callTool('clover_create_item', {
                  name,
                  price: parseInt(price),
                });
                fetchStats();
              }
            }}
            className="px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
          >
            Add Item
          </button>
          <button
            onClick={() => window.mcp.callTool('clover_list_item_stocks', {})}
            className="px-4 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
          >
            Stock Report
          </button>
        </div>
      </div>
    </div>
  );
}

function StatCard({
  icon,
  title,
  value,
  bgColor,
}: {
  icon: React.ReactNode;
  title: string;
  value: string | number;
  bgColor: string;
}) {
  return (
    <div className={`${bgColor} rounded-lg p-6 shadow-sm`}>
      <div className="flex items-center justify-between mb-3">{icon}</div>
      <h3 className="text-gray-600 text-sm font-medium mb-1">{title}</h3>
      <p className="text-2xl font-bold text-gray-900">{value}</p>
    </div>
  );
}
