import { useState, useEffect } from 'react';
import { CheckCircle, XCircle } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { StatusBadge } from '@/components/common/StatusBadge';
import { Button } from '@/components/ui/button';
import { treasuryService } from '@/services/treasuryService';
import { PaymentAuthorizationDTO } from '@/types/treasury';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { useAuth } from '@/contexts/AuthContext';

export function PaymentAuthorizationsPage() {
  const { user } = useAuth();
  const [authorizations, setAuthorizations] = useState<PaymentAuthorizationDTO[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (user?.id) {
      loadAuthorizations();
    }
  }, [user?.id]);

  const loadAuthorizations = async () => {
    try {
      setLoading(true);
      if (!user?.id) {
        return;
      }
      const data = await treasuryService.getPendingApprovals(user.id);
      setAuthorizations(data);
    } catch (error) {
      toast.error('Erro ao carregar autorizações');
    } finally {
      setLoading(false);
    }
  };

  const handleApprove = async (id: string) => {
    try {
      if (!user?.id) return;
      await treasuryService.approvePayment(id, {
        approverId: user.id,
        comments: 'Aprovado',
      });
      toast.success('Pagamento aprovado');
      loadAuthorizations();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao aprovar pagamento');
    }
  };

  const handleReject = async (id: string) => {
    try {
      if (!user?.id) return;
      await treasuryService.rejectPayment(id, {
        approverId: user.id,
        reason: 'Rejeitado pelo usuário',
      });
      toast.success('Pagamento rejeitado');
      loadAuthorizations();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao rejeitar pagamento');
    }
  };

  const columns = [
    {
      accessorKey: 'requestedAt',
      header: 'Data Solicitação',
      cell: ({ row }: any) => format(new Date(row.original.requestedAt), 'dd/MM/yyyy HH:mm', { locale: ptBR }),
    },
    {
      accessorKey: 'currentApprovalLevel',
      header: 'Nível Atual',
      cell: ({ row }: any) => `${row.original.currentApprovalLevel}/${row.original.requiredApprovalLevel}`,
    },
    {
      accessorKey: 'status',
      header: 'Status',
      cell: ({ row }: any) => (
        <StatusBadge
          status={row.original.status}
        />
      ),
    },
    {
      accessorKey: 'actions',
      header: 'Ações',
      cell: ({ row }: any) => {
        const auth = row.original;
        if (auth.status === 'PENDING' || auth.status === 'PARTIALLY_APPROVED') {
          return (
            <div className="flex gap-2">
              <Button
                size="sm"
                variant="outline"
                onClick={() => handleApprove(auth.id)}
              >
                <CheckCircle className="h-4 w-4 mr-1" />
                Aprovar
              </Button>
              <Button
                size="sm"
                variant="outline"
                onClick={() => handleReject(auth.id)}
              >
                <XCircle className="h-4 w-4 mr-1" />
                Rejeitar
              </Button>
            </div>
          );
        }
        return null;
      },
    },
  ];

  return (
    <>
      <PageHeader
        title="Autorizações de Pagamento"
        description="Gerencie aprovações hierárquicas de pagamentos"
      />

      <div className="container mx-auto py-6">
        <ServerDataTable
          data={authorizations}
          columns={columns}
          loading={loading}
          searchPlaceholder="Buscar autorizações..."
        />
      </div>
    </>
  );
}
