import { useState, useEffect } from 'react';
import { Plus, FileText } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { Button } from '@/components/ui/button';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { StatusBadge } from '@/components/common/StatusBadge';
import { treasuryService } from '@/services/treasuryService';
import { TreasuryEntryDTO } from '@/types/treasury';
import { toast } from 'sonner';
import { formatCurrency } from '@/utils/locale';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { TreasuryEntryFormModal } from '../components/TreasuryEntryFormModal';

export function TreasuryEntriesPage() {
  const [entries, setEntries] = useState<TreasuryEntryDTO[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [isFormOpen, setIsFormOpen] = useState(false);

  useEffect(() => {
    loadEntries();
  }, [page]);

  const loadEntries = async () => {
    try {
      setLoading(true);
      const response = await treasuryService.getTreasuryEntries({
        page,
        size: 20,
        sortBy: 'transactionDate',
        sortDirection: 'DESC',
      });
      setEntries(response.content);
      setTotalPages(response.totalPages);
    } catch (error) {
      toast.error('Erro ao carregar entradas de tesouraria');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      accessorKey: 'transactionDate',
      header: 'Data',
      cell: ({ row }: any) => format(new Date(row.original.transactionDate), 'dd/MM/yyyy', { locale: ptBR }),
    },
    {
      accessorKey: 'type',
      header: 'Tipo',
      cell: ({ row }: any) => (
        <StatusBadge
          status={row.original.type}
          labels={{
            PAYMENT_AUTHORIZATION: 'Autorização',
            PAYMENT_EXECUTION: 'Execução',
            CASH_DEPOSIT: 'Depósito',
            CASH_WITHDRAWAL: 'Saque',
          }}
        />
      ),
    },
    {
      accessorKey: 'amount',
      header: 'Valor',
      cell: ({ row }: any) => formatCurrency(row.original.amount),
    },
    {
      accessorKey: 'status',
      header: 'Status',
      cell: ({ row }: any) => (
        <StatusBadge
          status={row.original.status}
          labels={{
            DRAFT: 'Rascunho',
            PENDING_APPROVAL: 'Pendente',
            APPROVED: 'Aprovado',
            REJECTED: 'Rejeitado',
            EXECUTED: 'Executado',
          }}
        />
      ),
    },
    {
      accessorKey: 'documentReference',
      header: 'Referência',
    },
  ];

  return (
    <>
      <PageHeader
        title="Entradas de Tesouraria"
        description="Rastreamento completo de todas as movimentações de tesouraria"
      >
        <Button onClick={() => setIsFormOpen(true)}>
          <Plus className="h-4 w-4 mr-2" />
          Nova Entrada
        </Button>
      </PageHeader>

      <div className="container mx-auto py-6">
        <ServerDataTable
          data={entries}
          columns={columns}
          loading={loading}
          pagination={{
            page,
            totalPages,
            onPageChange: setPage,
          }}
          searchPlaceholder="Buscar entradas..."
        />
      </div>

      <TreasuryEntryFormModal
        open={isFormOpen}
        onClose={() => setIsFormOpen(false)}
        onSuccess={loadEntries}
      />
    </>
  );
}

