import { useState, useEffect } from 'react';
import { Plus, Wallet, Building2, TrendingUp, TrendingDown } 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 { CashAccountDTO, CreateCashAccountDTO } from '@/types/treasury';
import { toast } from 'sonner';
import { formatCurrency } from '@/utils/locale';
import { CashAccountFormModal } from '../components/CashAccountFormModal';

export function CashAccountsPage() {
  const [accounts, setAccounts] = useState<CashAccountDTO[]>([]);
  const [loading, setLoading] = useState(true);
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [selectedAccount, setSelectedAccount] = useState<CashAccountDTO | null>(null);

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

  const loadAccounts = async () => {
    try {
      setLoading(true);
      const data = await treasuryService.getCashAccounts({ activeOnly: false });
      setAccounts(data);
    } catch (error) {
      toast.error('Erro ao carregar contas de caixa');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setSelectedAccount(null);
    setIsFormOpen(true);
  };

  const handleFormSubmit = async (data: CreateCashAccountDTO) => {
    try {
      if (selectedAccount) {
        // Update not implemented yet
        toast.info('Atualização ainda não implementada');
      } else {
        await treasuryService.createCashAccount(data);
        toast.success('Conta criada com sucesso');
      }
      setIsFormOpen(false);
      setSelectedAccount(null);
      loadAccounts();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao salvar conta');
    }
  };

  const columns = [
    {
      accessorKey: 'code',
      header: 'Código',
    },
    {
      accessorKey: 'name',
      header: 'Nome',
    },
    {
      accessorKey: 'type',
      header: 'Tipo',
      cell: (account: CashAccountDTO) => (
        <StatusBadge status={account.type} />
      ),
    },
    {
      accessorKey: 'category',
      header: 'Categoria',
      cell: (account: CashAccountDTO) => (
        <span className="text-sm">
          {account.category === 'CENTRAL_CUT' && 'Conta Única'}
          {account.category === 'TRANSIT' && 'Trânsito'}
          {account.category === 'SUB_ACCOUNT' && 'Sub-Conta'}
          {account.category === 'OTHER' && 'Outra'}
          {!account.category && '-'}
        </span>
      ),
    },
    {
      accessorKey: 'currency',
      header: 'Moeda',
    },
    {
      accessorKey: 'currentBalance',
      header: 'Saldo Atual',
      cell: (account: CashAccountDTO) => formatCurrency(account.currentBalance),
    },
    {
      accessorKey: 'availableBalance',
      header: 'Saldo Disponível',
      cell: (account: CashAccountDTO) => (
        <div className="flex items-center gap-2">
          {formatCurrency(account.availableBalance)}
          {account.availableBalance < account.currentBalance && (
            <TrendingDown className="h-4 w-4 text-yellow-500" />
          )}
        </div>
      ),
    },
    {
      accessorKey: 'isActive',
      header: 'Status',
      cell: (account: CashAccountDTO) => (
        <StatusBadge status={account.isActive ? 'ACTIVE' : 'INACTIVE'} />
      ),
    },
  ];

  return (
    <>
      <PageHeader
        title="Contas de Caixa e Bancárias"
        description="Gerencie contas de caixa e contas bancárias do Tesouro"
        actions={
          <Button onClick={handleCreate}>
            <Plus className="h-4 w-4 mr-2" />
            Nova Conta
          </Button>
        }
      />

      <div className="container mx-auto py-6">
        <ServerDataTable
          data={accounts}
          columns={columns}
          loading={loading}
          searchPlaceholder="Buscar por código ou nome..."
        />
      </div>

      <CashAccountFormModal
        open={isFormOpen}
        onOpenChange={setIsFormOpen}
        account={selectedAccount}
        onSubmit={handleFormSubmit}
      />
    </>
  );
}

