import React from 'react';
import { Models } from 'appwrite';
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';

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

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 endereço?')) {
      await onDelete(id);
    }
  };

  const columns: Column<Models.Document>[] = [
    { key: 'titulo', header: 'Título' },
    { key: 'cep', header: 'CEP' },
    { key: 'cidade', header: 'Cidade' },
    { key: 'estado', header: 'Estado' },
    { key: 'pais', header: 'País' },
  ];

  return (
    <div className="container mx-auto px-4 py-8">
      <ListHeader title="Lista de Endereços">
        <SearchBar
          value={search}
          onChange={setSearch}
          onSearch={handleSearch}
          placeholder="Buscar título, 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 página...</span>
          </div>
        </div>
      )}

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

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

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

export default EnderecoList;
