import React from 'react';
import { LaboratorioBff } from '@/services/laboratorioApiService';
import SearchBar from './SearchBar';
import DataTable, { Column } from './DataTable';
import Pagination from './Pagination';
import TableActions from './TableActions';

interface LaboratorioListProps {
  laboratorios: LaboratorioBff[];
  loading: boolean;
  isCreating?: boolean;
  error: string | null;
  totalLaboratorios: number;
  currentPage: number;
  isChangingPage: boolean;
  pageSize: number;
  onEdit: (lab: LaboratorioBff) => void;
  onDelete: (id: string) => Promise<boolean>;
  onPrevPage: () => void;
  onNextPage: () => void;
  onSearch: (nome: string) => void;
}

const LaboratorioList: React.FC<LaboratorioListProps> = ({
  laboratorios,
  loading,
  isCreating = false,
  error,
  totalLaboratorios,
  currentPage,
  isChangingPage,
  pageSize,
  onEdit,
  onDelete,
  onPrevPage,
  onNextPage,
  onSearch
}) => {
  const totalPages = Math.ceil(totalLaboratorios / pageSize);
  const startItem = (currentPage - 1) * pageSize + 1;
  const endItem = Math.min(currentPage * pageSize, totalLaboratorios);

  const [search, setSearch] = React.useState('');

  const handleSearch = () => {
    onSearch(search);
  };

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

  const columns: Column<LaboratorioBff>[] = [
    { key: 'nome', header: 'Nome' },
    { key: 'createdAt', header: 'Data de Criação', render: row => row.createdAt ? new Date(row.createdAt).toLocaleDateString('pt-BR') : '-' },
  ];

  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 Laboratórios</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>
      )}

      {isCreating && (
        <div className="bg-blue-50 border border-blue-200 rounded-md p-3 mb-4">
          <div className="flex items-center">
            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
            <span className="text-blue-800 text-sm">Criando novo laboratório...</span>
          </div>
        </div>
      )}

      {loading ? (
        <div className="flex justify-center items-center min-h-screen">
          <div className="text-lg">Carregando laboratórios...</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">
                    Nome
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    ID
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Data de Criação
                  </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">
                {laboratorios.length === 0 ? (
                  <tr>
                    <td colSpan={4} className="px-6 py-4 text-center text-gray-500">
                      📭 Nenhum laboratório encontrado.
                    </td>
                  </tr>
                ) : (
                  laboratorios.map((lab) => (
                    <tr key={lab.$id}>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                        {lab.nome || 'N/A'}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {lab.$id}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {new Date(lab.$createdAt).toLocaleDateString('pt-BR')}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button
                          onClick={() => onEdit(lab)}
                          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(lab.$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="pagination-container">
            <div className="text-sm text-gray-600">
              {totalLaboratorios > 0 ? (
                <>Mostrando {startItem} - {endItem} de {totalLaboratorios} laboratórios</>
              ) : (
                'Total de laboratórios: 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 LaboratorioList;