import React, { useState, useEffect } from 'react';
import { Package, Edit, Trash2, Plus } from 'lucide-react';

export default function InventoryDetail() {
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');

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

  const fetchItems = async () => {
    setLoading(true);
    try {
      const result = await window.mcp.callTool('clover_list_items', {
        expand: 'categories',
        limit: 100,
      });
      setItems(result.items || []);
    } catch (error) {
      console.error('Failed to fetch items:', error);
    } finally {
      setLoading(false);
    }
  };

  const deleteItem = async (itemId: string) => {
    if (!confirm('Delete this item?')) return;

    try {
      await window.mcp.callTool('clover_delete_item', { itemId });
      fetchItems();
    } catch (error) {
      alert('Failed to delete item');
    }
  };

  const filteredItems = items.filter((item) =>
    item.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-900">Inventory Items</h1>
        <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),
              });
              fetchItems();
            }
          }}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
        >
          <Plus className="w-5 h-5" />
          Add Item
        </button>
      </div>

      <div className="bg-white rounded-lg shadow p-6 mb-6">
        <input
          type="text"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          placeholder="Search items..."
          className="w-full px-4 py-2 border border-gray-300 rounded-lg"
        />
      </div>

      {loading ? (
        <div className="text-center py-12 text-gray-500">Loading items...</div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredItems.map((item) => (
            <div key={item.id} className="bg-white rounded-lg shadow p-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex-1">
                  <h3 className="text-lg font-semibold text-gray-900 mb-1">
                    {item.name}
                  </h3>
                  <p className="text-2xl font-bold text-blue-600">
                    ${(item.price / 100).toFixed(2)}
                  </p>
                </div>
                <Package className="w-8 h-8 text-gray-400" />
              </div>

              <div className="space-y-2 mb-4">
                {item.sku && (
                  <p className="text-sm text-gray-600">SKU: {item.sku}</p>
                )}
                {item.stockCount !== undefined && (
                  <p className="text-sm text-gray-600">
                    Stock: {item.stockCount}
                  </p>
                )}
                {item.hidden && (
                  <span className="inline-block px-2 py-1 text-xs bg-red-100 text-red-800 rounded">
                    Hidden
                  </span>
                )}
              </div>

              <div className="flex gap-2">
                <button
                  onClick={() => alert('Edit feature coming soon')}
                  className="flex-1 px-3 py-2 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 flex items-center justify-center gap-2"
                >
                  <Edit className="w-4 h-4" />
                  Edit
                </button>
                <button
                  onClick={() => deleteItem(item.id)}
                  className="px-3 py-2 bg-red-100 text-red-700 rounded hover:bg-red-200"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
