import { useState, useEffect } from 'react';
import { TrendingUp, TrendingDown, Wallet } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { treasuryService } from '@/services/treasuryService';
import { CashFlowDTO, CashAccountDTO } from '@/types/treasury';
import { toast } from 'sonner';
import { formatCurrency } from '@/utils/locale';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

export function CashFlowPage() {
  const [cashFlows, setCashFlows] = useState<CashFlowDTO[]>([]);
  const [accounts, setAccounts] = useState<CashAccountDTO[]>([]);
  const [selectedAccountId, setSelectedAccountId] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(0);
  const [totalPages, setTotalPages] = useState(0);

  useEffect(() => {
    loadAccounts();
  }, []);

  useEffect(() => {
    if (selectedAccountId) {
      loadCashFlows();
    }
  }, [selectedAccountId, page]);

  const loadAccounts = async () => {
    try {
      const data = await treasuryService.getCashAccounts();
      setAccounts(data);
      if (data.length > 0 && !selectedAccountId) {
        setSelectedAccountId(data[0].id);
      }
    } catch (error) {
      toast.error('Erro ao carregar contas');
    }
  };

  const loadCashFlows = async () => {
    if (!selectedAccountId) return;
    try {
      setLoading(true);
      const response = await treasuryService.getCashFlows({
        cashAccountId: selectedAccountId,
        page,
        size: 20,
        sortBy: 'transactionDate',
        sortDirection: 'DESC',
      });
      setCashFlows(response.content);
      setTotalPages(response.totalPages);
    } catch (error) {
      toast.error('Erro ao carregar fluxo de caixa');
    } 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) => (
        <div className="flex items-center gap-2">
          {row.original.type === 'INFLOW' ? (
            <TrendingUp className="h-4 w-4 text-green-500" />
          ) : (
            <TrendingDown className="h-4 w-4 text-red-500" />
          )}
          <span>{row.original.type === 'INFLOW' ? 'Entrada' : 'Saída'}</span>
        </div>
      ),
    },
    {
      accessorKey: 'amount',
      header: 'Valor',
      cell: ({ row }: any) => formatCurrency(row.original.amount),
    },
    {
      accessorKey: 'balanceAfter',
      header: 'Saldo Após',
      cell: ({ row }: any) => formatCurrency(row.original.balanceAfter),
    },
    {
      accessorKey: 'description',
      header: 'Descrição',
    },
  ];

  return (
    <>
      <PageHeader
        title="Fluxo de Caixa"
        description="Acompanhe entradas e saídas de caixa"
      />

      <div className="container mx-auto py-6 space-y-4">
        <div className="flex items-center gap-4">
          <label className="text-sm font-medium">Conta:</label>
          <Select value={selectedAccountId} onValueChange={setSelectedAccountId}>
            <SelectTrigger className="w-[300px]">
              <SelectValue placeholder="Selecione uma conta" />
            </SelectTrigger>
            <SelectContent>
              {accounts.map((account) => (
                <SelectItem key={account.id} value={account.id}>
                  {account.name} ({account.code})
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <ServerDataTable
          data={cashFlows}
          columns={columns}
          loading={loading}
          pagination={{
            page,
            totalPages,
            onPageChange: setPage,
          }}
          searchPlaceholder="Buscar no fluxo de caixa..."
        />
      </div>
    </>
  );
}

