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 ActionButton from './ActionButton';
import TableActions from './TableActions'; // Adicionar esta importação

interface Props {
  carrinhos: Models.Document[];
  loading: boolean;
  isChangingPage?: boolean;
  error: string | null;
  totalCarrinhos: number;
  currentPage: number;
  pageSize: number;
  onEdit: (doc: Models.Document) => void;
  onDelete: (id: string) => Promise<boolean>;
  onRefresh: () => void;
  onPrevPage: () => void;
  onNextPage: () => void;
  onSearch: (usuario: string) => void;
}

const columns: Column<Models.Document>[] = [
  {
    key: 'usuarios',
    header: 'Usuário',
    render: row => {
      const usuario = (row as any).usuarios;
      if (usuario && typeof usuario === 'object') {
        return (
          usuario['nome-civil'] || usuario['nome-social'] || usuario.$id || ''
        );
      }
      return usuario;
    }
  },
  {
    key: 'itens',
    header: 'Itens',
    render: row => ((row as any).itens || []).join(', ')
  },
  {
    key: 'quantidades',
    header: 'Quantidades',
    className: 'text-center',
    render: row => {
      const quantidades = (row as any).quantidades;
      const valor = Array.isArray(quantidades) 
        ? quantidades.join(', ')
        : typeof quantidades === 'number'
        ? quantidades.toString()
        : '1';
      return <div className="text-center font-medium">{valor}</div>;
    }
  }
];

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

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

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

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

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

export default CarrinhoList;
