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 UsuarioListProps {
  usuarios: Models.Document[];
  loading: boolean;
  isChangingPage?: boolean;
  error: string | null;
  totalUsuarios: number;
  currentPage: number;
  pageSize: number;
  onEdit: (user: Models.Document) => void;
  onDelete: (id: string) => Promise<boolean>;
  onRefresh: () => void;
  onPrevPage: () => void;
  onNextPage: () => void;
  onSearch: (term: string) => void;
}

const columns: Column<Models.Document>[] = [
  { key: 'nome-civil', header: 'Nome Civil' },
  { key: 'nome-social', header: 'Nome Social' },
  { key: 'email', header: 'Email' },
  {
    key: 'empresas',
    header: 'Empresa',
    render: row => {
      const empresa = (row as any).empresas;
      if (empresa && typeof empresa === 'object') {
        return (
          empresa['razao-social'] || empresa['nome-fantasia'] || empresa.$id || ''
        );
      }
      return empresa;
    },
  },
  { key: 'cpf', header: 'CPF' },
];

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

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

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

  return (
    <div className="container mx-auto px-4 py-8">
      <ListHeader title="Lista de Usuários">
        <SearchBar
          value={search}
          onChange={setSearch}
          onSearch={handleSearch}
          placeholder="Buscar nome ou email"
        />
        <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 usuários...</div>
        </div>
      ) : (
        <>
          <DataTable
            columns={columns}
            data={usuarios}
            actions={(u) => (
              <TableActions
                onEdit={() => onEdit(u)}
                onDelete={() => handleDelete(u.$id)}
              />
            )}
          />

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

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

export default UsuarioList;
