import { useState, useEffect } from 'react';
import { CheckCircle, AlertCircle, 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 { BankReconciliationDTO, 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 { useAuth } from '@/contexts/AuthContext';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

export function BankReconciliationPage() {
  const { user } = useAuth();
  const [reconciliations, setReconciliations] = useState<BankReconciliationDTO[]>([]);
  const [accounts, setAccounts] = useState<CashAccountDTO[]>([]);
  const [selectedAccountId, setSelectedAccountId] = useState<string>('');
  const [loading, setLoading] = useState(true);

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

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

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

  const loadReconciliations = async () => {
    if (!selectedAccountId) return;
    try {
      setLoading(true);
      const data = await treasuryService.getBankReconciliations(selectedAccountId);
      setReconciliations(data);
    } catch (error) {
      toast.error('Erro ao carregar conciliações');
    } finally {
      setLoading(false);
    }
  };

  const handleReconcile = async (id: string) => {
    try {
      await treasuryService.reconcile(id);
      toast.success('Conciliação processada');
      loadReconciliations();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao processar conciliação');
    }
  };

  const handleFinalize = async (id: string) => {
    try {
      if (!user?.id) {
        toast.error('Usuário não autenticado');
        return;
      }
      await treasuryService.finalizeReconciliation(id, user.id);
      toast.success('Conciliação finalizada');
      loadReconciliations();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao finalizar conciliação');
    }
  };

  const columns = [
    {
      accessorKey: 'reconciliationDate',
      header: 'Data',
      cell: ({ row }: any) => format(new Date(row.original.reconciliationDate), 'dd/MM/yyyy', { locale: ptBR }),
    },
    {
      accessorKey: 'statementBalance',
      header: 'Saldo Extrato',
      cell: ({ row }: any) => formatCurrency(row.original.statementBalance),
    },
    {
      accessorKey: 'systemBalance',
      header: 'Saldo Sistema',
      cell: ({ row }: any) => formatCurrency(row.original.systemBalance),
    },
    {
      accessorKey: 'difference',
      header: 'Diferença',
      cell: ({ row }: any) => {
        const diff = row.original.difference;
        return (
          <span className={diff !== 0 ? 'text-red-500 font-semibold' : 'text-green-500'}>
            {formatCurrency(diff)}
          </span>
        );
      },
    },
    {
      accessorKey: 'status',
      header: 'Status',
      cell: ({ row }: any) => (
        <StatusBadge
          status={row.original.status}
          labels={{
            PENDING: 'Pendente',
            RECONCILED: 'Conciliado',
            DISCREPANCY: 'Discrepância',
          }}
        />
      ),
    },
    {
      accessorKey: 'actions',
      header: 'Ações',
      cell: ({ row }: any) => {
        const rec = row.original;
        if (rec.status === 'PENDING') {
          return (
            <div className="flex gap-2">
              <Button size="sm" variant="outline" onClick={() => handleReconcile(rec.id)}>
                <CheckCircle className="h-4 w-4 mr-1" />
                Conciliar
              </Button>
            </div>
          );
        } else if (rec.status === 'RECONCILED' || rec.status === 'DISCREPANCY') {
          return (
            <Button size="sm" variant="outline" onClick={() => handleFinalize(rec.id)}>
              Finalizar
            </Button>
          );
        }
        return null;
      },
    },
  ];

  return (
    <>
      <PageHeader
        title="Conciliação Bancária"
        description="Concilie extratos bancários com o sistema"
      />

      <div className="container mx-auto py-6 space-y-4">
        <div className="flex items-center gap-4">
          <label className="text-sm font-medium">Conta Bancária:</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={reconciliations}
          columns={columns}
          loading={loading}
          searchPlaceholder="Buscar conciliações..."
        />
      </div>
    </>
  );
}

