import React from 'react';
import SearchBar from './SearchBar';
import RefreshButton from './RefreshButton';
import ListHeader from './ListHeader';
import DataTable, { Column } from './DataTable';
import Pagination from './Pagination';
import TableActions from './TableActions';
import { EnderecoDocument } from '@/types/legacyEntities';

interface EnderecoListProps {
  enderecos: EnderecoDocument[];
  loading: boolean;
  isChangingPage?: boolean;
  error: string | null;
  totalEnderecos: number;
  currentPage: number;
  pageSize: number;
  onEdit: (endereco: EnderecoDocument) => void;
  onDelete: (id: string) => Promise<boolean>;
  onRefresh: () => void;
  onPrevPage: () => void;
  onNextPage: () => void;
  onSearch: (termo: string) => void;
}

const columns: Column<EnderecoDocument>[] = [
  { key: 'titulo', header: 'Titulo' },
  { key: 'cep', header: 'CEP' },
  { key: 'cidade', header: 'Cidade' },
  { key: 'estado', header: 'Estado' },
  { key: 'pais', header: 'Pais' },
];

const EnderecoList: React.FC<EnderecoListProps> = ({
  enderecos,
  loading,
  isChangingPage = false,
  error,
  totalEnderecos,
  currentPage,
  pageSize,
  onEdit,
  onDelete,
  onRefresh,
  onPrevPage,
  onNextPage,
  onSearch,
}) => {
  const totalPages = Math.ceil(totalEnderecos / pageSize);
  const startItem = (currentPage - 1) * pageSize + 1;
  const endItem = Math.min(currentPage * pageSize, totalEnderecos);

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

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

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

  return (
    <div className="container mx-auto px-4 py-8">
      <ListHeader title="Lista de Enderecos">
        <SearchBar
          value={search}
          onChange={setSearch}
          onSearch={handleSearch}
          placeholder="Buscar titulo, CEP ou cidade"
        />
        <RefreshButton onClick={onRefresh} loading={loading} />
      </ListHeader>

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

      {isChangingPage && (
        <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">Carregando pagina...</span>
          </div>
        </div>
      )}

      {loading ? (
        <div className="flex justify-center items-center min-h-screen">
          <div className="text-lg">Carregando enderecos...</div>
        </div>
      ) : (
        <>
          <DataTable
            columns={columns}
            data={enderecos}
            actions={(endereco) => (
              <TableActions
                onEdit={() => onEdit(endereco)}
                onDelete={() => handleDelete(endereco.$id)}
              />
            )}
          />

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

            <Pagination
              page={currentPage}
              total={totalPages}
              onPrev={onPrevPage}
              onNext={onNextPage}
              isChangingPage={isChangingPage}
            />
          </div>
        </>
      )}
    </div>
  );
};

export default EnderecoList;
