"use client";

import { getDadosFaturas } from "@/actions/pageParabensCodigoDeBarrasPix";
import { useState } from "react";
import { QRCodeCanvas } from "qrcode.react";
import {
    FaBarcode,
    FaMoneyBillWave,
    FaQrcode,
    FaFilePdf,
    FaChevronDown,
    FaSpinner,
} from "react-icons/fa";
import { toast } from "react-toastify";
import { IResponseBuscarDadosFaturas } from "@/utils/Interfaces/interfacesBuscarDadosFaturas";
import { baixarPdfBase64 } from "@/utils/functions";

interface Props {
    faturaId: string;
}

export default function FaturaDropdown({ faturaId }: Props) {
    const [open, setOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const [codigoPix, setCodigoPix] = useState<string | null>(null);
    const [dadosFaturas, setDadosFaturas] = useState<IResponseBuscarDadosFaturas>();

    async function handlePix(boleto: any, gerarQrCodee?: boolean) {
        if (!gerarQrCodee) {
            if (!boleto.CodigoQrcode) {
                toast.error("Código Pix não disponível.");
                return;
            }

            await navigator.clipboard.writeText(boleto.CodigoQrcode);
            toast.success("Código Pix copiado com sucesso!");
        } else {
            if (boleto.CodigoQrcode) {
                setCodigoPix(boleto.CodigoQrcode);
            } else {
                toast.error("QR Code não disponível.");
            }
        }
    }

    async function handleBoleto(boleto: any) {
        if (!boleto.LinhaDigitavel) {
            toast.error("Código de barras não disponível.");
            return;
        }

        await navigator.clipboard.writeText(boleto.LinhaDigitavel);
        toast.success("Código de barras copiado com sucesso!");
    }

    async function handleGerarPdf(boletos: any[]) {
        const boletosComPdf = boletos.filter(b => b.ArquivoBoleto);

        if (boletosComPdf.length === 0) {
            toast.error("Nenhum arquivo PDF disponível.");
            return;
        }

        baixarPdfBase64(
            boletosComPdf.map(b => ({
                base64: b.ArquivoBoleto,
                nome: b.NomeArquivo,
            }))
        );

        toast.success(
            boletosComPdf.length > 1
                ? `${boletosComPdf.length} boletos baixados com sucesso!`
                : "Boleto baixado com sucesso!"
        );
    }

    async function getCodigoDeBarras(tipo: "pix" | "boleto" | "GerarPdf", gerarQrCodee?: boolean) {
        setLoading(true);
        setCodigoPix(null);
        setOpen(false);

        try {
            let data = dadosFaturas;

            const precisaBuscar =
                !data ||
                (tipo === "pix" && !data.Boletos?.[0]?.CodigoQrcode) ||
                (tipo === "boleto" && !data.Boletos?.[0]?.LinhaDigitavel) ||
                (tipo === "GerarPdf" && !data.Boletos?.[0]?.ArquivoBoleto);

            if (precisaBuscar) {
                data = await getDadosFaturas(faturaId);
                setDadosFaturas(data);
            }

            if (!data?.Boletos?.[0]) {
                toast.error("Nenhum boleto encontrado.");
                return;
            }

            const boleto = data.Boletos[0];

            if (tipo === "pix") {
                await handlePix(boleto, gerarQrCodee);
            } else if (tipo === "boleto") {
                await handleBoleto(boleto);
            } else if (tipo === "GerarPdf") {
                await handleGerarPdf(data.Boletos);
            }

        } catch (err: any) {
            toast.error(err.message || "Erro ao processar solicitação");
        } finally {
            setLoading(false);
        }
    }

    function closeDropdown() {
        setOpen(!open);
        setCodigoPix(null);
    }

    return (
        <div className="relative flex flex-col items-center justify-center gap-2">
            <button
                onClick={() => closeDropdown()}
                disabled={loading}
                className="mt-4 flex items-center justify-center gap-2 bg-plamev-blue-500 hover:bg-plamev-blue-600 text-white font-bold py-2 px-4 rounded-lg transition-all w-[250px] h-[54px]"
            >   
                {loading ? (
                    <>
                        <FaSpinner className="w-5 h-5 animate-spin" />
                        Processando...
                    </>
                ) : (
                    <>
                        Opções de pagamento
                        <FaChevronDown
                            className={`w-4 h-4 transition-transform ${open ? "rotate-180" : ""}`}
                        />
                    </>
                )}
            </button>

            {codigoPix && (
                <div className="p-4 flex flex-col items-center justify-center mt-4">
                    <QRCodeCanvas
                        value={codigoPix}
                        size={200}
                        includeMargin={true}
                        className="self-center"
                    />
                    <p className="text-sm text-center mt-2 text-gray-700">
                        Escaneie o QR Code com o app do seu banco
                    </p>
                </div>
            )}

            {open && !loading && (
                <div className="absolute top-full mt-[2px] w-52 bg-white border border-gray-200 rounded-lg shadow-lg z-50">
                    <ul className="py-1">
                        <li>
                            <button
                                onClick={() => getCodigoDeBarras("pix", false)}
                                className="flex items-center w-full px-4 py-2 text-gray-700 hover:bg-gray-100"
                            >
                                <FaBarcode className="w-4 h-4 mr-2" />
                                Código Pix
                            </button>
                        </li>
                        <li>
                            <button
                                onClick={() => getCodigoDeBarras("pix", true)}
                                className="flex items-center w-full px-4 py-2 text-gray-700 hover:bg-gray-100"
                            >
                                <FaQrcode className="w-4 h-4 mr-2" />
                                QR Code
                            </button>
                        </li>
                        <li>
                            <button
                                onClick={() => getCodigoDeBarras("boleto", false)}
                                className="flex items-center w-full px-4 py-2 text-gray-700 hover:bg-gray-100"
                            >
                                <FaBarcode className="w-4 h-4 mr-2" />
                                Código de Barras
                            </button>
                        </li>
                        <li>
                            <button
                                onClick={() => getCodigoDeBarras("GerarPdf", false)}
                                className="flex items-center w-full px-4 py-2 text-gray-700 hover:bg-gray-100"
                            >
                                <FaFilePdf className="w-4 h-4 mr-2" />
                                Baixar PDF
                            </button>
                        </li>
                    </ul>
                </div>
            )}
        </div>

    );
}
