import React from 'react';
import { Models } from 'appwrite';

interface ProdutoListProps {
  produtos: Models.Document[];
  loading: boolean;
  error: string | null;
  totalProdutos: number;
  currentPage: number;
  pageSize: number;
  onEdit: (produto: Models.Document) => void;
  onDelete: (id: string) => Promise<boolean>;
  onRefresh: () => void;
  onPrevPage: () => void;
  onNextPage: () => void;
  onSearch: (nome: string) => void;
}

const ProdutoList: React.FC<ProdutoListProps> = ({
  produtos,
  loading,
  error,
  totalProdutos,
  currentPage,
  pageSize,
  onEdit,
  onDelete,
  onRefresh,
  onPrevPage,
  onNextPage,
  onSearch
}) => {
  const totalPages = Math.ceil(totalProdutos / pageSize);
  const startItem = (currentPage - 1) * pageSize + 1;
  const endItem = Math.min(currentPage * pageSize, totalProdutos);
  const [search, setSearch] = React.useState('');

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    onSearch(search);
  };

  const handleDelete = async (id: string) => {
    if (confirm('Tem certeza que deseja deletar este produto?')) {
      await onDelete(id);
    }
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold">Lista de Produtos</h1>
        <div className="flex items-center gap-2">
          <form onSubmit={handleSearch} className="flex gap-2">
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="border border-gray-300 rounded px-3 py-1 bg-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="Buscar nome"
            />
            <button
              type="submit"
              className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors cursor-pointer"
              disabled={loading}
            >
              🔍 Buscar
            </button>
          </form>
          <button
            onClick={onRefresh}
            disabled={loading}
            className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 transition-colors cursor-pointer"
          >
            {loading ? '⏳' : '🔄'} Atualizar
          </button>
        </div>
      </div>

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

      {loading ? (
        <div className="flex justify-center items-center min-h-screen">
          <div className="text-lg">Carregando produtos...</div>
        </div>
      ) : (
        <>
          <div className="bg-white shadow-md rounded-lg overflow-hidden">
            <table className="min-w-full table-auto">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Preço Original
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Preço Atual
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Catálogo
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Empresa
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Ações
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {produtos.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-6 py-4 text-center text-gray-500">
                      📭 Nenhum produto encontrado.
                    </td>
                  </tr>
                ) : (
                  produtos.map((produto) => (
                    <tr key={produto.$id}>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                        {produto['preco-original']}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {produto['preco-atual']}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {produto['catalogo-produto-id']}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {produto['empresa-id']}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button
                          onClick={() => onEdit(produto)}
                          className="px-3 py-1 text-sm bg-yellow-100 text-yellow-800 rounded hover:bg-yellow-200 transition-colors cursor-pointer mr-2"
                        >
                          ✏️ Editar
                        </button>
                        <button
                          onClick={() => handleDelete(produto.$id)}
                          className="px-3 py-1 text-sm bg-red-100 text-red-800 rounded hover:bg-red-200 transition-colors cursor-pointer"
                        >
                          🗑️ Deletar
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          <div className="mt-4 flex justify-between items-center">
            <div className="text-sm text-gray-600">
              {totalProdutos > 0 ? (
                <>Mostrando {startItem} - {endItem} de {totalProdutos} produtos</>
              ) : (
                'Total de produtos: 0'
              )}
            </div>

            {totalPages > 1 && (
              <div className="flex gap-2">
                <button
                  onClick={onPrevPage}
                  disabled={currentPage <= 1}
                  className="px-3 py-1 border rounded disabled:opacity-50 cursor-pointer"
                >
                  ◀️ Anterior
                </button>
                <span className="px-3 py-1 text-gray-700">Página {currentPage} de {totalPages}</span>
                <button
                  onClick={onNextPage}
                  disabled={currentPage >= totalPages}
                  className="px-3 py-1 border rounded disabled:opacity-50 cursor-pointer"
                >
                  Próxima ▶️
                </button>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
};

export default ProdutoList;
