'use client';

import { useEffect, useState } from 'react';
import DashboardLayout from '@/components/layout/DashboardLayout';
import { API_URL } from '@/lib/api';

interface TallyInventoryItem {
  name: string;
  code: string;
  category: string;
  unit: string;
  currentStock: number;
  unitPrice: number;
  reorderLevel: number;
  lastSyncedAt: string;
}

export default function InventoryPage() {
  const [items, setItems] = useState<TallyInventoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [lastSynced, setLastSynced] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [filterCategory, setFilterCategory] = useState('All');

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

  const fetchInventory = async () => {
    setLoading(true);
    setError('');
    try {
      const res = await fetch(`${API_URL}/api/tally/inventory`);
      if (!res.ok) throw new Error('Failed to fetch inventory');
      const data = await res.json();
      setItems(data);
      setLastSynced(new Date().toLocaleString());
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error fetching inventory');
    } finally {
      setLoading(false);
    }
  };

  const categories = ['All', ...new Set(items.map((item) => item.category))];

  const getStockPriority = (qty: number, reorderLevel: number) => {
    if (qty === 0) return 0; // Out of stock - highest priority
    if (qty <= reorderLevel) return 1; // Low stock
    return 2; // In stock
  };

  const filteredItems = items
    .filter((item) => {
      const matchesSearch =
        item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.code.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesCategory = filterCategory === 'All' || item.category === filterCategory;
      return matchesSearch && matchesCategory;
    })
    .sort((a, b) => {
      // Sort by stock status first (out of stock → low → in stock)
      const priorityA = getStockPriority(a.currentStock, a.reorderLevel);
      const priorityB = getStockPriority(b.currentStock, b.reorderLevel);
      if (priorityA !== priorityB) return priorityA - priorityB;
      
      // Then by current stock (ascending, lower qty first)
      return a.currentStock - b.currentStock;
    });

  const getStockStatus = (qty: number, reorderLevel: number) => {
    if (qty === 0) return { text: 'Out of Stock', color: 'bg-red-100 text-red-800' };
    if (qty <= reorderLevel) return { text: 'Low Stock', color: 'bg-yellow-100 text-yellow-800' };
    return { text: 'In Stock', color: 'bg-green-100 text-green-800' };
  };

  return (
    <DashboardLayout>
      <div className="space-y-6 p-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Inventory</h1>
            <p className="text-sm text-gray-600 mt-1">Live inventory from Tally Prime</p>
          </div>
          <button
            onClick={fetchInventory}
            disabled={loading}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 font-medium"
          >
            {loading ? 'Syncing...' : 'Sync Now'}
          </button>
        </div>

        {/* Last Synced Info */}
        {lastSynced && (
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-800">
            Last synced: {lastSynced}
          </div>
        )}

        {/* Error Message */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-800">
            {error}
          </div>
        )}

        {/* Search and Filter */}
        <div className="flex gap-4 items-end">
          <div className="flex-1">
            <label className="block text-sm font-medium text-gray-700 mb-2">Search</label>
            <input
              type="text"
              placeholder="Search by name or code..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            {searchTerm && (
              <p className="text-xs text-gray-500 mt-1">Found {filteredItems.length} items</p>
            )}
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Category</label>
            <select
              value={filterCategory}
              onChange={(e) => setFilterCategory(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {categories.map((cat) => (
                <option key={cat} value={cat}>
                  {cat}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Inventory Table */}
        {loading ? (
          <div className="text-center text-gray-500 py-12">Loading inventory...</div>
        ) : filteredItems.length === 0 ? (
          <div className="text-center text-gray-500 py-12">No items found</div>
        ) : (
          <div className="overflow-x-auto bg-white rounded-lg border border-gray-200">
            <table className="w-full">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="px-6 py-3 text-left text-sm font-semibold text-gray-900">Code</th>
                  <th className="px-6 py-3 text-left text-sm font-semibold text-gray-900">Name</th>
                  <th className="px-6 py-3 text-left text-sm font-semibold text-gray-900">Category</th>
                  <th className="px-6 py-3 text-center text-sm font-semibold text-gray-900">Stock</th>
                  <th className="px-6 py-3 text-center text-sm font-semibold text-gray-900">Unit</th>
                  <th className="px-6 py-3 text-right text-sm font-semibold text-gray-900">Unit Price</th>
                  <th className="px-6 py-3 text-center text-sm font-semibold text-gray-900">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {filteredItems.map((item, idx) => {
                  const status = getStockStatus(item.currentStock, item.reorderLevel);
                  return (
                    <tr key={idx} className="hover:bg-gray-50">
                      <td className="px-6 py-3 text-sm font-mono text-gray-900">{item.code}</td>
                      <td className="px-6 py-3 text-sm text-gray-900">{item.name}</td>
                      <td className="px-6 py-3 text-sm text-gray-600">{item.category || '—'}</td>
                      <td className="px-6 py-3 text-sm text-center font-semibold text-gray-900">
                        {item.currentStock}
                      </td>
                      <td className="px-6 py-3 text-sm text-center text-gray-600">{item.unit}</td>
                      <td className="px-6 py-3 text-sm text-right text-gray-900">
                        AED {item.unitPrice.toFixed(2)}
                      </td>
                      <td className="px-6 py-3 text-center">
                        <span className={`px-3 py-1 rounded-full text-xs font-medium ${status.color}`}>
                          {status.text}
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {/* Summary */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <p className="text-sm text-gray-600">Total Items</p>
            <p className="text-2xl font-bold text-gray-900">{filteredItems.length}</p>
          </div>
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <p className="text-sm text-gray-600">Low Stock Items</p>
            <p className="text-2xl font-bold text-yellow-600">
              {filteredItems.filter((i) => i.currentStock > 0 && i.currentStock <= i.reorderLevel).length}
            </p>
          </div>
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <p className="text-sm text-gray-600">Out of Stock</p>
            <p className="text-2xl font-bold text-red-600">
              {filteredItems.filter((i) => i.currentStock === 0).length}
            </p>
          </div>
        </div>
      </div>
    </DashboardLayout>
  );
}
