import React, { useEffect, useRef, useState } from "react";
import axios from "axios";
import SidebarCalendarAena from "../../UI/Templates/SidebarCalendarAena";
import { getDeltia, getNavigatorYears } from "../../../API/timesheets";
import { MONTHS_GR } from "./AenaSingle/AenaTypes";
import DuaLoader from "../../UI/Loader/DuaLoader/DuaLoader";

type Props = {
    userId: string;
    activeRole: string;
    isOpen: boolean;
};

type YearCalendar = {
    year: number;
    months: any[];
};

const AenaCalendarLoader = ({ userId, activeRole, isOpen }: Props) => {
    const [calendars, setCalendars] = useState<YearCalendar[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const hasFetched = useRef(false);
    const abortRef   = useRef<AbortController | null>(null);

    useEffect(() => {
        if (!isOpen || hasFetched.current) return;
        hasFetched.current = true;

        abortRef.current?.abort();
        abortRef.current = new AbortController();
        let cancelled = false;

        const load = async () => {
            setIsLoading(true);
            try {
                const yearsRes = await getNavigatorYears(userId, activeRole);
                if (cancelled) return;

                const years: number[] = (yearsRes.data as string[])
                    .map(Number)
                    .sort((a, b) => b - a);

                const results = await Promise.all(
                    years.map(async (year) => {
                        try {
                            const res = await getDeltia(userId, String(year), activeRole, abortRef.current!.signal);

                            const excelInfo     = res.data.a1_excel_file ?? null;
                            const hasExcel      = Boolean(excelInfo?.A1_excel?.months?.length);
                            const excelUploaded = new Set<number>(
                                hasExcel ? (excelInfo.A1_excel.months ?? []).map(Number) : []
                            );
                            const excelActive   = new Set<number>(
                                hasExcel ? (excelInfo.months ?? []).map(Number) : []
                            );

                            const pdfByMonth = new Map<number, any>(
                                (res.data.a1_pdf_files ?? []).map((d: any) => [d.month_id, d])
                            );

                            const months = MONTHS_GR.map((name: string, i: number) => {
                                const monthI   = i + 1;
                                const entry    = pdfByMonth.get(monthI);
                                const rawCodes = entry?.project_codes;
                                const projects = typeof rawCodes === 'string'
                                    ? rawCodes.split(',').map((s: string) => s.trim()).filter(Boolean)
                                    : Array.isArray(rawCodes)
                                        ? rawCodes
                                        : [];

                                return {
                                    index:  monthI,
                                    name,
                                    has_submitted: hasExcel
                                        ? (excelActive.has(monthI)
                                            ? (excelUploaded.has(monthI) ? true : false)
                                            : undefined)
                                        : (entry?.file ? true : entry ? false : undefined),
                                    projects,
                                };
                            });

                            return { year, months };
                        } catch (e) {
                            if (axios.isCancel(e)) return null;
                            console.error(`[AenaCalendarLoader] year ${year}`, e);
                            return null;
                        }
                    })
                );

                if (!cancelled) {
                    setCalendars(results.filter(Boolean) as YearCalendar[]);
                }
            } catch (e) {
                if (axios.isCancel(e)) return;
                console.error('[AenaCalendarLoader]', e);
            } finally {
                if (!cancelled) setIsLoading(false);
            }
        };

        load();
        return () => { cancelled = true; abortRef.current?.abort(); };
    }, [isOpen, userId, activeRole]);

    if (isLoading) return    <div className="dua-loader-portal"><DuaLoader/></div>;

    if (!calendars.length) return null;

    return (
        <>
            {calendars.map(({ year, months }) => (
                <SidebarCalendarAena
                    key={`calendar-${userId}-${year}`}
                    userId={String(userId)}
                    year={year}
                    months={months}
                />
            ))}
        </>
    );
};

export default AenaCalendarLoader;
