'use client'

import React, { useEffect, useState } from "react";
import { getApproveProcedures } from "@/actions/pageApproveProcedures";
import CardProcedureApprove from "../_components/CardProcedimentosAprovacao";
import { useRouter, useSearchParams } from "next/navigation";
import moment from "moment";
import Image from "next/image";

import ImageDogTriste from "../../../../public/assets/Images/Image/notfound404.png"

const Page = () => {
    const [dadosProcedimentos, setDadosProcedimentos] = useState<IResponseAtendimentosPendentes>({ AtendimentosPendentes: [] });
    const [latitude, setLatitude] = useState<number | null>(null);
    const [longitude, setLongitude] = useState<number | null>(null);
    const [loadingLocation, setLoadingLocation] = useState<boolean>(true);
    const [showEmptyMessage, setShowEmptyMessage] = useState<boolean>(false);
    const [procedimentosTratados, setProcedimentosTratados] = useState<number[]>([]);

    const router = useRouter();
    const searchParams = useSearchParams();
    const clientesId = searchParams.get("cliente");

    const handleProcedimentoFinalizado = (id: number) => {
        setProcedimentosTratados((prev) => {
            if (prev.includes(id)) return prev;

            const atualizados = [...prev, id];

            const totalProcedimentos = dadosProcedimentos.AtendimentosPendentes
                .flatMap((atendimento) => atendimento.ListaProcedimentos)
                .length;

            if (atualizados.length === totalProcedimentos) {
                router.push(`/procedimentos-parabens`);
            }

            return atualizados;
        });
    };

    useEffect(() => {
        (async () => {
            if (clientesId) {
                try {
                    const res = await getApproveProcedures(clientesId);
                    setDadosProcedimentos(res);
                } catch (err) {
                    console.error("Erro ao consultar procedimentos:", err);
                }
            }
        })();
    }, [clientesId]);

    useEffect(() => {
        if (
            Array.isArray(dadosProcedimentos?.AtendimentosPendentes) &&
            dadosProcedimentos.AtendimentosPendentes.length === 0
        ) {
            const timer = setTimeout(() => {
                setShowEmptyMessage(true);
            }, 10000);

            return () => clearTimeout(timer);
        } else {
            setShowEmptyMessage(false);
        }
    }, [dadosProcedimentos]);

    useEffect(() => {
        if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    setLatitude(position.coords.latitude);
                    setLongitude(position.coords.longitude);
                    setLoadingLocation(false);
                },
                (error) => {
                    console.error("Erro ao obter localização:", error);
                    setLoadingLocation(false);
                }
            );
        } else {
            setLoadingLocation(false);
        }
    }, []);

    if (loadingLocation) {
        return (
            <div className="flex justify-center items-center h-screen">
                <h2 className="m-0 p-0 text-center text-plamev-blue-500 text-[28px] md:text-[32px] lg:text-[32px] mb-[50px] --grandstander">
                    Para confirmar os atendimentos, permita o acesso à sua localização.
                </h2>
            </div>
        );
    }

    return (
        <div className="my-[32px]">
            <div className="flex flex-col justify-center items-start px-8 mt-[10px] w-full sm:w-[850px] m-auto">
                {Array.isArray(dadosProcedimentos?.AtendimentosPendentes) && dadosProcedimentos.AtendimentosPendentes.length > 0 && (
                    <h2 className="m-0 p-0 text-plamev-blue-500 text-[28px] md:text-[32px] lg:text-[32px] mb-[50px]">
                        Aprovar Procedimentos
                    </h2>
                )}

                <div className="flex flex-wrap justify-between max-w-5xl mx-auto">
                    {Array.isArray(dadosProcedimentos?.AtendimentosPendentes) && dadosProcedimentos.AtendimentosPendentes.length > 0 ? (
                        dadosProcedimentos.AtendimentosPendentes.map((item, index) => (
                            <React.Fragment key={index}>
                                <div className="flex flex-col md:flex-row justify-between w-full">
                                    <span className="font-semibold">Número de atendimento:</span>
                                    <span>{item.Atendimentos.NumeroAtendimento}</span>
                                </div>

                                <div className="flex flex-col md:flex-row justify-between w-full">
                                    <span className="font-semibold">Data de atendimento:</span>
                                    <span>
                                        {item.Atendimentos.DataAtendimento
                                            ? moment(item.Atendimentos.DataAtendimento).format("DD/MM/YYYY H:mm:ss")
                                            : "-"}
                                    </span>
                                </div>

                                <div className="flex flex-col md:flex-row justify-between w-full">
                                    <span className="font-semibold">Pet:</span>
                                    <span>{item.Pets.Nome}</span>
                                </div>

                                <div className="flex flex-col md:flex-row justify-between w-full">
                                    <span className="font-semibold">Credenciado:</span>
                                    <span>{item.Atendimentos.CredenciadosNome}</span>
                                </div>

                                <div className="flex flex-col md:flex-row justify-between w-full">
                                    <span className="font-semibold">Veterinário:</span>
                                    <span>{item.Veterinarios.Nome}</span>
                                </div>

                                <div className="flex flex-col md:flex-row justify-between w-full mb-4">
                                    <span className="font-semibold">CRMV:</span>
                                    <span>{item.Veterinarios.CRMV}</span>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-5xl w-full">
                                    {item?.ListaProcedimentos?.map((procedimentos) => (
                                        <div key={procedimentos.Procedimentos.Id} className="flex items-stretch w-full">
                                            <CardProcedureApprove
                                                procedure={procedimentos.Procedimentos.Nome}
                                                atendimentoAValidar={item}
                                                itemProcedimento={procedimentos.AtendimentosProcedimentos}
                                                latitude={latitude}
                                                longitude={longitude}
                                                onProcedimentoFinalizado={handleProcedimentoFinalizado}
                                            />
                                        </div>
                                    ))}
                                </div>

                                {index < dadosProcedimentos.AtendimentosPendentes.length - 1 && (
                                    <hr className="border-dashed border-t border-gray-300 my-8 w-full" />
                                )}
                            </React.Fragment>
                        ))
                    ) : showEmptyMessage ? (
                        <div className="flex flex-col items-center justify-center w-full mt-10">
                            <h2 className="m-0 p-0 text-center text-plamev-blue-500 text-[28px] md:text-[32px] lg:text-[32px] mb-[50px] --grandstander">
                                Nenhum procedimento pendente para aprovação.
                            </h2>
                            <Image
                                src={ImageDogTriste}
                                alt="Nenhum procedimento encontrado"
                                className=""
                            />
                        </div>
                    ) : (
                       <div className="flex flex-col items-center justify-center w-full mt-10">
                            <h2 className="text-plamev-blue-500 text-[28px]">Procurando Procedimentos...</h2>
                            <Image
                                src={ImageDogTriste}
                                alt="Nenhum procedimento encontrado"
                                className=""
                            />
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

export default Page;
