import React, { useEffect, useState } from 'react';
import { Search, Plus, Edit, Trash2, Package, AlertTriangle, TrendingDown, X } from 'lucide-react';
import inventoryService, { InventoryItem, ReorderRequest } from '../../features/inventory/services/inventoryService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import Pagination from '../../shared/components/Pagination';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';

const InventoryManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [items, setItems] = useState<InventoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingItem, setEditingItem] = useState<InventoryItem | null>(null);
  const [showReorderModal, setShowReorderModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState<InventoryItem | null>(null);
  const [reorderRequests, setReorderRequests] = useState<ReorderRequest[]>([]);
  const [lowStockItems, setLowStockItems] = useState<InventoryItem[]>([]);
  
  const [filters, setFilters] = useState({
    search: '',
    category: '',
    low_stock: false,
    is_active: '',
  });
  
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const itemsPerPage = 20;

  const [formData, setFormData] = useState({
    name: '',
    description: '',
    category: 'cleaning_supplies',
    unit: 'piece',
    minimum_quantity: 0,
    maximum_quantity: 0,
    reorder_quantity: 0,
    unit_cost: 0,
    supplier: '',
    supplier_contact: '',
    storage_location: '',
    barcode: '',
    sku: '',
    notes: '',
    is_active: true,
    is_tracked: true,
  });

  const categories = [
    { value: 'cleaning_supplies', label: 'Cleaning Supplies' },
    { value: 'linens', label: 'Linens' },
    { value: 'toiletries', label: 'Toiletries' },
    { value: 'amenities', label: 'Amenities' },
    { value: 'maintenance', label: 'Maintenance' },
    { value: 'food_beverage', label: 'Food & Beverage' },
    { value: 'other', label: 'Other' },
  ];

  const units = [
    { value: 'piece', label: 'Piece' },
    { value: 'box', label: 'Box' },
    { value: 'bottle', label: 'Bottle' },
    { value: 'roll', label: 'Roll' },
    { value: 'pack', label: 'Pack' },
    { value: 'liter', label: 'Liter' },
    { value: 'kilogram', label: 'Kilogram' },
    { value: 'meter', label: 'Meter' },
    { value: 'other', label: 'Other' },
  ];

  useEffect(() => {
    setCurrentPage(1);
  }, [filters]);

  useEffect(() => {
    fetchItems();
    fetchLowStockItems();
    fetchReorderRequests();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, currentPage]);

  const fetchItems = async () => {
    try {
      setLoading(true);
      const params: Record<string, unknown> = {
        page: currentPage,
        limit: itemsPerPage,
      };
      
      if (filters.category) params.category = filters.category;
      if (filters.low_stock) params.low_stock = true;
      if (filters.is_active !== '') params.is_active = filters.is_active === 'true';

      const response = await inventoryService.getInventoryItems(params);
      
      if (response.status === 'success' && response.data) {
        let itemList = response.data.items || [];
        
        if (filters.search) {
          itemList = itemList.filter((item: InventoryItem) =>
            item.name.toLowerCase().includes(filters.search.toLowerCase()) ||
            item.description?.toLowerCase().includes(filters.search.toLowerCase()) ||
            item.sku?.toLowerCase().includes(filters.search.toLowerCase()) ||
            item.barcode?.toLowerCase().includes(filters.search.toLowerCase())
          );
        }
        
        setItems(itemList);
        setTotalPages(response.data.pagination?.total_pages || 1);
        setTotalItems(response.data.pagination?.total || 0);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load inventory items');
    } finally {
      setLoading(false);
    }
  };

  const fetchLowStockItems = async () => {
    try {
      const response = await inventoryService.getLowStockItems();
      if (response.status === 'success' && response.data) {
        setLowStockItems(response.data.items || []);
      }
    } catch (error) {
      // Silently fail - not critical
    }
  };

  const fetchReorderRequests = async () => {
    try {
      const response = await inventoryService.getReorderRequests({ status: 'pending' });
      if (response.status === 'success' && response.data) {
        setReorderRequests(response.data.requests || []);
      }
    } catch (error) {
      // Silently fail - not critical
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      if (editingItem) {
        await inventoryService.updateInventoryItem(editingItem.id, formData);
        toast.success('Inventory item updated successfully');
      } else {
        await inventoryService.createInventoryItem(formData);
        toast.success('Inventory item created successfully');
      }
      
      setShowModal(false);
      resetForm();
      fetchItems();
      fetchLowStockItems();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to save inventory item');
    }
  };

  const handleEdit = (item: InventoryItem) => {
    setEditingItem(item);
    setFormData({
      name: item.name,
      description: item.description || '',
      category: item.category,
      unit: item.unit,
      minimum_quantity: item.minimum_quantity,
      maximum_quantity: item.maximum_quantity || 0,
      reorder_quantity: item.reorder_quantity || 0,
      unit_cost: item.unit_cost || 0,
      supplier: item.supplier || '',
      supplier_contact: '',
      storage_location: item.storage_location || '',
      barcode: item.barcode || '',
      sku: item.sku || '',
      notes: '',
      is_active: item.is_active,
      is_tracked: item.is_tracked,
    });
    setShowModal(true);
  };

  const handleDelete = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this inventory item?')) {
      return;
    }

    try {
      await inventoryService.updateInventoryItem(id, { is_active: false });
      toast.success('Inventory item deactivated successfully');
      fetchItems();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to delete inventory item');
    }
  };

  const resetForm = () => {
    setEditingItem(null);
    setFormData({
      name: '',
      description: '',
      category: 'cleaning_supplies',
      unit: 'piece',
      minimum_quantity: 0,
      maximum_quantity: 0,
      reorder_quantity: 0,
      unit_cost: 0,
      supplier: '',
      supplier_contact: '',
      storage_location: '',
      barcode: '',
      sku: '',
      notes: '',
      is_active: true,
      is_tracked: true,
    });
  };

  const openReorderModal = (item: InventoryItem) => {
    setSelectedItem(item);
    setShowReorderModal(true);
  };

  const handleCreateReorder = async (quantity: number, priority: string, notes: string) => {
    if (!selectedItem) return;

    try {
      await inventoryService.createReorderRequest({
        item_id: selectedItem.id,
        requested_quantity: quantity,
        priority,
        notes,
      });
      toast.success('Reorder request created successfully');
      setShowReorderModal(false);
      setSelectedItem(null);
      fetchReorderRequests();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to create reorder request');
    }
  };

  const getStockStatus = (item: InventoryItem) => {
    if (!item.is_tracked) return { color: 'bg-slate-100 text-slate-700', label: 'Not Tracked' };
    if (item.is_low_stock) return { color: 'bg-red-100 text-red-800', label: 'Low Stock' };
    if (item.maximum_quantity && item.current_quantity >= item.maximum_quantity) {
      return { color: 'bg-blue-100 text-blue-800', label: 'Max Stock' };
    }
    return { color: 'bg-green-100 text-green-800', label: 'In Stock' };
  };

  if (loading && items.length === 0) {
    return <Loading fullScreen text="Loading inventory..." />;
  }

  return (
    <div className="space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 animate-fade-in">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="h-1 w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
            <h1 className="text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              Inventory Management
            </h1>
          </div>
          <p className="text-slate-600 mt-3 text-lg font-light">Manage hotel inventory and supplies</p>
        </div>
        <button
          onClick={() => {
            resetForm();
            setShowModal(true);
          }}
          className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl"
        >
          <Plus className="w-5 h-5" />
          Add Item
        </button>
      </div>

      {/* Alerts */}
      {lowStockItems.length > 0 && (
        <div className="bg-gradient-to-r from-red-50 to-orange-50 border-2 border-red-200 rounded-xl p-4 animate-fade-in">
          <div className="flex items-center gap-3">
            <AlertTriangle className="w-6 h-6 text-red-600" />
            <div>
              <h3 className="font-semibold text-red-900">Low Stock Alert</h3>
              <p className="text-red-700 text-sm">
                {lowStockItems.length} item{lowStockItems.length > 1 ? 's' : ''} below minimum quantity
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-5">
          <div className="relative group">
            <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5 group-focus-within:text-amber-500 transition-colors" />
            <input
              type="text"
              placeholder="Search items..."
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              className="w-full pl-12 pr-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 placeholder-slate-400 font-medium shadow-sm hover:shadow-md"
            />
          </div>
          <select
            value={filters.category}
            onChange={(e) => setFilters({ ...filters, category: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All Categories</option>
            {categories.map((cat) => (
              <option key={cat.value} value={cat.value}>
                {cat.label}
              </option>
            ))}
          </select>
          <select
            value={filters.is_active}
            onChange={(e) => setFilters({ ...filters, is_active: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All Status</option>
            <option value="true">Active</option>
            <option value="false">Inactive</option>
          </select>
          <label className="flex items-center gap-3 px-4 py-3.5 bg-gradient-to-r from-slate-50 to-white border-2 border-slate-200 rounded-xl cursor-pointer hover:border-amber-400 transition-all">
            <input
              type="checkbox"
              checked={filters.low_stock}
              onChange={(e) => setFilters({ ...filters, low_stock: e.target.checked })}
              className="w-5 h-5 text-amber-600 rounded focus:ring-amber-500"
            />
            <span className="text-slate-700 font-medium">Low Stock Only</span>
          </label>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 animate-fade-in">
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Total Items</p>
              <p className="text-3xl font-bold text-slate-900 mt-2">{totalItems}</p>
            </div>
            <Package className="w-12 h-12 text-amber-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Low Stock</p>
              <p className="text-3xl font-bold text-red-600 mt-2">{lowStockItems.length}</p>
            </div>
            <AlertTriangle className="w-12 h-12 text-red-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Pending Orders</p>
              <p className="text-3xl font-bold text-orange-600 mt-2">{reorderRequests.length}</p>
            </div>
            <TrendingDown className="w-12 h-12 text-orange-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Active Items</p>
              <p className="text-3xl font-bold text-green-600 mt-2">
                {items.filter((i) => i.is_active).length}
              </p>
            </div>
            <Package className="w-12 h-12 text-green-500" />
          </div>
        </div>
      </div>

      {/* Items Table */}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 overflow-hidden animate-fade-in">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gradient-to-r from-slate-50 to-gray-50 border-b-2 border-slate-200">
              <tr>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Item
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Category
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Quantity
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Location
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Cost
                </th>
                <th className="px-6 py-4 text-right text-xs font-semibold text-slate-700 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-slate-200">
              {items.map((item) => {
                const stockStatus = getStockStatus(item);
                return (
                  <tr key={item.id} className="hover:bg-slate-50 transition-colors">
                    <td className="px-6 py-4">
                      <div>
                        <div className="font-semibold text-slate-900">{item.name}</div>
                        {item.description && (
                          <div className="text-sm text-slate-500 mt-1">{item.description}</div>
                        )}
                        {item.sku && (
                          <div className="text-xs text-slate-400 mt-1">SKU: {item.sku}</div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className="px-3 py-1 bg-slate-100 text-slate-700 rounded-full text-sm font-medium">
                        {categories.find((c) => c.value === item.category)?.label || item.category}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-slate-900 font-semibold">
                        {item.current_quantity} {units.find((u) => u.value === item.unit)?.label || item.unit}
                      </div>
                      {item.is_tracked && (
                        <div className="text-xs text-slate-500 mt-1">
                          Min: {item.minimum_quantity}
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      <span className={`px-3 py-1 rounded-full text-sm font-medium ${stockStatus.color}`}>
                        {stockStatus.label}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-slate-600">
                      {item.storage_location || '—'}
                    </td>
                    <td className="px-6 py-4 text-slate-900 font-semibold">
                      {item.unit_cost ? formatCurrency(item.unit_cost) : '—'}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex items-center justify-end gap-2">
                        {item.is_low_stock && (
                          <button
                            onClick={() => openReorderModal(item)}
                            className="p-2 text-orange-600 hover:bg-orange-50 rounded-lg transition-colors"
                            title="Reorder"
                          >
                            <TrendingDown className="w-5 h-5" />
                          </button>
                        )}
                        <button
                          onClick={() => handleEdit(item)}
                          className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                          title="Edit"
                        >
                          <Edit className="w-5 h-5" />
                        </button>
                        <button
                          onClick={() => handleDelete(item.id)}
                          className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                          title="Delete"
                        >
                          <Trash2 className="w-5 h-5" />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {items.length === 0 && !loading && (
          <div className="text-center py-12">
            <Package className="w-16 h-16 text-slate-400 mx-auto mb-4" />
            <p className="text-slate-600 text-lg">No inventory items found</p>
          </div>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={setCurrentPage}
        />
      )}

      {/* Create/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
          <div className="bg-white rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="sticky top-0 bg-white border-b border-slate-200 px-6 py-4 flex items-center justify-between">
              <h2 className="text-2xl font-bold text-slate-900">
                {editingItem ? 'Edit Inventory Item' : 'Add Inventory Item'}
              </h2>
              <button
                onClick={() => {
                  setShowModal(false);
                  resetForm();
                }}
                className="p-2 hover:bg-slate-100 rounded-lg transition-colors"
              >
                <X className="w-6 h-6" />
              </button>
            </div>
            <form onSubmit={handleSubmit} className="p-6 space-y-6">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Item Name *
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    required
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Category *
                  </label>
                  <select
                    value={formData.category}
                    onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    required
                  >
                    {categories.map((cat) => (
                      <option key={cat.value} value={cat.value}>
                        {cat.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">
                  Description
                </label>
                <textarea
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                  rows={3}
                />
              </div>

              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Unit *
                  </label>
                  <select
                    value={formData.unit}
                    onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    required
                  >
                    {units.map((unit) => (
                      <option key={unit.value} value={unit.value}>
                        {unit.label}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Min Quantity *
                  </label>
                  <input
                    type="number"
                    value={formData.minimum_quantity}
                    onChange={(e) => setFormData({ ...formData, minimum_quantity: parseFloat(e.target.value) || 0 })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    min="0"
                    step="0.01"
                    required
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Max Quantity
                  </label>
                  <input
                    type="number"
                    value={formData.maximum_quantity}
                    onChange={(e) => setFormData({ ...formData, maximum_quantity: parseFloat(e.target.value) || 0 })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    min="0"
                    step="0.01"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Unit Cost
                  </label>
                  <input
                    type="number"
                    value={formData.unit_cost}
                    onChange={(e) => setFormData({ ...formData, unit_cost: parseFloat(e.target.value) || 0 })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                    min="0"
                    step="0.01"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Storage Location
                  </label>
                  <input
                    type="text"
                    value={formData.storage_location}
                    onChange={(e) => setFormData({ ...formData, storage_location: e.target.value })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    Supplier
                  </label>
                  <input
                    type="text"
                    value={formData.supplier}
                    onChange={(e) => setFormData({ ...formData, supplier: e.target.value })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">
                    SKU
                  </label>
                  <input
                    type="text"
                    value={formData.sku}
                    onChange={(e) => setFormData({ ...formData, sku: e.target.value })}
                    className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100"
                  />
                </div>
              </div>

              <div className="flex items-center gap-6">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.is_active}
                    onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                    className="w-5 h-5 text-amber-600 rounded"
                  />
                  <span className="text-slate-700 font-medium">Active</span>
                </label>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.is_tracked}
                    onChange={(e) => setFormData({ ...formData, is_tracked: e.target.checked })}
                    className="w-5 h-5 text-amber-600 rounded"
                  />
                  <span className="text-slate-700 font-medium">Track Quantity</span>
                </label>
              </div>

              <div className="flex gap-4 pt-4 border-t border-slate-200">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="flex-1 px-6 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all"
                >
                  {editingItem ? 'Update Item' : 'Create Item'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Reorder Modal - Simplified version */}
      {showReorderModal && selectedItem && (
        <ReorderModal
          item={selectedItem}
          onClose={() => {
            setShowReorderModal(false);
            setSelectedItem(null);
          }}
          onSubmit={handleCreateReorder}
        />
      )}
    </div>
  );
};

// Simple Reorder Modal Component
const ReorderModal: React.FC<{
  item: InventoryItem;
  onClose: () => void;
  onSubmit: (quantity: number, priority: string, notes: string) => void;
}> = ({ item, onClose, onSubmit }) => {
  const [quantity, setQuantity] = useState(item.reorder_quantity || item.minimum_quantity);
  const [priority, setPriority] = useState('normal');
  const [notes, setNotes] = useState('');

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
      <div className="bg-white rounded-2xl shadow-2xl max-w-md w-full">
        <div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
          <h2 className="text-xl font-bold text-slate-900">Create Reorder Request</h2>
          <button onClick={onClose} className="p-2 hover:bg-slate-100 rounded-lg">
            <X className="w-5 h-5" />
          </button>
        </div>
        <div className="p-6 space-y-4">
          <div>
            <p className="text-slate-600">Item: <span className="font-semibold">{item.name}</span></p>
            <p className="text-sm text-slate-500">Current: {item.current_quantity} | Min: {item.minimum_quantity}</p>
          </div>
          <div>
            <label className="block text-sm font-semibold text-slate-700 mb-2">Quantity *</label>
            <input
              type="number"
              value={quantity}
              onChange={(e) => setQuantity(parseFloat(e.target.value) || 0)}
              className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400"
              min="1"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-semibold text-slate-700 mb-2">Priority</label>
            <select
              value={priority}
              onChange={(e) => setPriority(e.target.value)}
              className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400"
            >
              <option value="low">Low</option>
              <option value="normal">Normal</option>
              <option value="high">High</option>
              <option value="urgent">Urgent</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-semibold text-slate-700 mb-2">Notes</label>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              className="w-full px-4 py-2 border-2 border-slate-200 rounded-xl focus:border-amber-400"
              rows={3}
            />
          </div>
          <div className="flex gap-4 pt-4">
            <button
              onClick={onClose}
              className="flex-1 px-6 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200"
            >
              Cancel
            </button>
            <button
              onClick={() => onSubmit(quantity, priority, notes)}
              className="flex-1 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700"
            >
              Create Request
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default InventoryManagementPage;

