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 FaturaListProps {
  faturas: Models.Document[];
  loading: boolean;
  error: string | null;
  totalFaturas: number;
  currentPage: number;
  pageSize: number;
  onEdit: (fatura: Models.Document) => void;
  onDelete: (id: string) => Promise<boolean>;
  onRefresh: () => void;
  onPrevPage: () => void;
  onNextPage: () => void;
  onSearch: (nome: string) => void;
}

const FaturaList: React.FC<FaturaListProps> = ({
  faturas,
  loading,
  error,
  totalFaturas,
  currentPage,
  pageSize,
  onEdit,
  onDelete,
  onRefresh,
  onPrevPage,
  onNextPage,
  onSearch
}) => {
  const totalPages = Math.ceil(totalFaturas / pageSize);
  const startItem = (currentPage - 1) * pageSize + 1;
  const endItem = Math.min(currentPage * pageSize, totalFaturas);

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

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

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

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

  return (
    <div className="container mx-auto px-4 py-8">
      <ListHeader title="Lista de Faturas">
        <SearchBar
          value={search}
          onChange={setSearch}
          onSearch={handleSearch}
          placeholder="Buscar fatura"
        />
        <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>
      )}

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

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

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

export default FaturaList;
