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 PedidoListProps {
  pedidos: Models.Document[];
  loading: boolean;
  isChangingPage?: boolean;
  error: string | null;
  totalPedidos: number;
  currentPage: number;
  pageSize: number;
  onEdit: (doc: Models.Document) => void;
  onDelete: (id: string) => Promise<boolean>;
  onRefresh: () => void;
  onPrevPage: () => void;
  onNextPage: () => void;
  onSearch: (term: string) => void;
  onFilterStatus: (status: string) => void;
  statusOptions: string[];
}

const PedidoList: React.FC<PedidoListProps> = ({
  pedidos,
  loading,
  isChangingPage = false,
  error,
  totalPedidos,
  currentPage,
  pageSize,
  onEdit,
  onDelete,
  onRefresh,
  onPrevPage,
  onNextPage,
  onSearch,
  onFilterStatus,
  statusOptions,
}) => {
  const totalPages = Math.ceil(totalPedidos / pageSize);
  const startItem = (currentPage - 1) * pageSize + 1;
  const endItem = Math.min(currentPage * pageSize, totalPedidos);
  const [search, setSearch] = React.useState('');
  const [status, setStatus] = React.useState('');

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

  const columns: Column<Models.Document>[] = [
    {
      key: 'comprador',
      header: 'Comprador',
      render: row => {
        const comp = (row as any).comprador;
        if (comp && typeof comp === 'object') {
          return comp['nome-civil'] || comp['nome-fantasia'] || comp.$id;
        }
        return comp;
      },
    },
    {
      key: 'vendedor',
      header: 'Vendedor',
      render: row => {
        const vend = (row as any).vendedor;
        if (vend && typeof vend === 'object') {
          return vend['nome-civil'] || vend['nome-fantasia'] || vend.$id;
        }
        return vend;
      },
    },
    {
      key: 'valor-total',
      header: 'Valor Total',
      render: row =>
        Number((row as any)['valor-total'] || 0).toLocaleString('pt-BR', {
          style: 'currency',
          currency: 'BRL',
        }),
    },
    { key: 'status', header: 'Status' },
  ];

  return (
    <div className="container mx-auto px-4 py-8">
      <ListHeader title="Lista de Pedidos">
        <SearchBar
          value={search}
          onChange={setSearch}
          onSearch={() => onSearch(search)}
          placeholder="Buscar comprador"
        />
        <select
          value={status}
          onChange={e => {
            setStatus(e.target.value);
            onFilterStatus(e.target.value);
          }}
          className="px-3 py-2 border border-gray-300 rounded-md text-gray-900 bg-white focus:ring-2 focus:ring-blue-500 focus:border-transparent h-10"
        >
          <option value="">Todos</option>
          {statusOptions.map(s => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
        <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 pedidos...</div>
        </div>
      ) : (
        <>
          <DataTable
            columns={columns}
            data={pedidos}
            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">
              {totalPedidos > 0 ? (
                <>Mostrando {startItem} - {endItem} de {totalPedidos} pedidos</>
              ) : (
                'Total de pedidos: 0'
              )}
            </div>

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

export default PedidoList;
