import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Grocery } from '../types';
import { groceryApi } from '../services/api';
import AddGroceryModal from './AddGroceryModal';
import ConfirmDeleteModal from './ConfirmDeleteModal';

const GroceryList: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [groceries, setGroceries] = useState<Grocery[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingGrocery, setEditingGrocery] = useState<Grocery | null>(null);
  const [deletingGrocery, setDeletingGrocery] = useState<Grocery | null>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);

  useEffect(() => {
    fetchGroceries();
    
    // Check if we should auto-open the modal
    if (searchParams.get('add') === 'true') {
      setIsModalOpen(true);
      // Remove the parameter from URL
      setSearchParams({});
    }
  }, [searchParams, setSearchParams]);

  const fetchGroceries = async () => {
    try {
      setLoading(true);
      const response = await groceryApi.getAll();
      setGroceries(response.data);
    } catch (err) {
      setError('Failed to fetch groceries');
      console.error('Error fetching groceries:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (grocery: Grocery) => {
    setEditingGrocery(grocery);
    setIsModalOpen(true);
  };

  const handleDelete = (grocery: Grocery) => {
    setDeletingGrocery(grocery);
  };

  const confirmDelete = async () => {
    if (!deletingGrocery) return;

    try {
      setDeleteLoading(true);
      await groceryApi.delete(deletingGrocery.id);
      setDeletingGrocery(null);
      fetchGroceries(); // Refresh the list
    } catch (err) {
      console.error('Error deleting grocery:', err);
      setError('Failed to delete grocery. Please try again.');
    } finally {
      setDeleteLoading(false);
    }
  };

  const handleGroceryAdded = () => {
    fetchGroceries(); // Refresh the list
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setEditingGrocery(null);
  };

  const handleCloseDeleteModal = () => {
    setDeletingGrocery(null);
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-900">Groceries</h1>
        <button 
          onClick={() => {
            setEditingGrocery(null);
            setIsModalOpen(true);
          }}
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        >
          Add New Grocery
        </button>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
          {error}
        </div>
      )}

      <div className="bg-white shadow rounded-lg overflow-hidden">
        {groceries.length === 0 ? (
          <div className="text-center py-12">
            <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 48 48">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
            </svg>
            <h3 className="mt-2 text-sm font-medium text-gray-900">No groceries</h3>
            <p className="mt-1 text-sm text-gray-500">Get started by adding your first grocery item.</p>
          </div>
        ) : (
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Category
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Weight
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Organic
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {groceries.map((grocery) => (
                <tr key={grocery.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-gray-900">{grocery.name}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                      {grocery.category}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {grocery.weight ? `${grocery.weight}${grocery.weight_unit}` : '-'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      grocery.organic 
                        ? 'bg-green-100 text-green-800' 
                        : 'bg-gray-100 text-gray-800'
                    }`}>
                      {grocery.organic ? 'Organic' : 'Conventional'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button 
                      onClick={() => handleEdit(grocery)}
                      className="text-indigo-600 hover:text-indigo-900 mr-3"
                    >
                      Edit
                    </button>
                    <button 
                      onClick={() => handleDelete(grocery)}
                      className="text-red-600 hover:text-red-900"
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <AddGroceryModal
        isOpen={isModalOpen}
        onClose={handleCloseModal}
        onGroceryAdded={handleGroceryAdded}
        editGrocery={editingGrocery}
      />

      <ConfirmDeleteModal
        isOpen={!!deletingGrocery}
        onClose={handleCloseDeleteModal}
        onConfirm={confirmDelete}
        title="Delete Grocery"
        message={`Are you sure you want to delete "${deletingGrocery?.name}"? This action cannot be undone.`}
        isLoading={deleteLoading}
      />
    </div>
  );
};

export default GroceryList; 