"use client"
import { useAppSelector } from "@/lib/hooks";
import { useDimensions } from "@/lib/hooks/dimension";
import { useLocale } from "@/lib/hooks/useLocale";
import { useGetEmployeeMovementQuery, useGetMppRecruitmentQuery, useGetResignCategoryQuery, useGetResignReasonQuery, useGetResignSummaryQuery, useGetResignTypeQuery, useLazyGetMonthlyEmployeeQuery } from "@/services/api";
import { BarChart, Bar, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from "recharts";
import { Loader, LucideLoader2 } from "lucide-react";
import React from "react";
import { useRef } from "react";
import { Tooltip as ReactTooltip } from "react-tooltip";
import { PageLoader } from "@/components/Loader";

export default function TurnoverPage() {
    const { t } = useLocale();
    const filter = useAppSelector(state => state.filter.filter);
    const resignRef = useRef<HTMLDivElement>(null);
    const recruitmentRef = useRef<HTMLDivElement>(null);
    const {width, height} = useDimensions(resignRef);
    const {width: recruitmentWidth} = useDimensions(recruitmentRef);
    const {data: resignSummary, isLoading: isLoadingResignSummary, isFetching: isFetchingResignSummary} = useGetResignSummaryQuery(filter);
    const {data: resignType, isLoading: isLoadingResignType, isFetching: isFetchingResignType} = useGetResignTypeQuery(filter);
    const {data: resignCategory, isLoading: isLoadingResignCategory, isFetching: isFetchingResignCategory} = useGetResignCategoryQuery(filter);
    const {data: resignReason, isLoading: isLoadingResignReason, isFetching: isFetchingResignReason} = useGetResignReasonQuery(filter);
    const {data: employeeMovement, isLoading: isLoadingEmployeeMovement, isFetching: isFetchingEmployeeMovement} = useGetEmployeeMovementQuery(filter);
    const {data: mppRecruitment, isLoading: isLoadingMppRecruitment, isFetching: isFetchingMppRecruitment} = useGetMppRecruitmentQuery(filter);
    
    // Lazy query for monthly employee data to calculate active employees
    const [getMonthlyEmployee, {isLoading: isLoadingActiveEmployees}] = useLazyGetMonthlyEmployeeQuery();

    // State for active employee data by organization
    const [activeEmployeesByOrg, setActiveEmployeesByOrg] = React.useState<{[key: string]: number}>({});

    // Combine all loading states (both initial loading and refetching)
    const isLoading = isLoadingResignSummary || isLoadingResignType || 
                     isLoadingResignCategory || isLoadingResignReason || 
                     isLoadingEmployeeMovement || isLoadingMppRecruitment ||
                     isLoadingActiveEmployees ||
                     isFetchingResignSummary || isFetchingResignType || 
                     isFetchingResignCategory || isFetchingResignReason || 
                     isFetchingEmployeeMovement || isFetchingMppRecruitment;

    const [turnOverRatio, setTurnOverRatio] = React.useState(0);
    const [resign, setResign] = React.useState(0);
    const [active, setActive] = React.useState(0);

    // Recruitment data state
    const [recruitmentRatio, setRecruitmentRatio] = React.useState(0);
    const [totalRecruitment, setTotalRecruitment] = React.useState(0);
    const [totalActiveEmployees, setTotalActiveEmployees] = React.useState(0);

    const [totalResignType, setTotalResignType] = React.useState(0);
    const [totalResignReason, setTotalResignReason] = React.useState(0);
    
    // MPP Recruitment data state
    const [mppRecruitmentSummary, setMppRecruitmentSummary] = React.useState<{
        organization_code: string;
        organization_name: string;
        recruited: number;
        remaining: number;
    }[]>([]);

    // Limited resignation data state for chart display
    const [limitedResignSummary, setLimitedResignSummary] = React.useState<{
        organization_code: string;
        organization_name: string;
        count: number;
        active: number;
    }[]>([]);

    // Function to calculate active employees for each organization
    const calculateActiveEmployees = React.useCallback(async (organizations: {organization_code: string, organization_name: string}[]) => {
        console.log('🔍 calculateActiveEmployees called with:', { organizations: organizations.map(o => o.organization_code), filter });
        const activeEmployeesMap: {[key: string]: number} = {};
        
        for (const org of organizations) {
            try {
                const result = await getMonthlyEmployee({
                    ...filter,
                    organization_code: org.organization_code
                });
                
                console.log(`📊 Monthly employee data for ${org.organization_code}:`, result.data);
                
                if (result.data && result.data.length > 0) {
                    // Find the record that matches the end_date from filter
                    let matchingData = null;
                    
                    if (filter.end_date) {
                        // Convert filter end_date to match the format in the API response
                        const filterEndDate = new Date(filter.end_date);
                        const filterYear = filterEndDate.getFullYear();
                        const filterMonth = filterEndDate.getMonth() + 1; // getMonth() returns 0-11
                        
                        console.log(`🎯 Looking for data matching: ${filterYear}-${filterMonth.toString().padStart(2, '0')}`);
                        
                        matchingData = result.data.find(item => {
                            const itemDate = new Date(item.date);
                            const itemYear = itemDate.getFullYear();
                            const itemMonth = itemDate.getMonth() + 1;
                            console.log(`📅 Checking item: ${itemYear}-${itemMonth.toString().padStart(2, '0')} (count: ${item.count})`);
                            return itemYear === filterYear && itemMonth === filterMonth;
                        });
                    }
                    
                    // If no matching date found, use the latest data as fallback
                    if (!matchingData) {
                        matchingData = result.data[result.data.length - 1];
                        console.log(`⚠️ No matching date found for ${org.organization_code}, using latest:`, matchingData);
                    } else {
                        console.log(`✅ Found matching data for ${org.organization_code}:`, matchingData);
                    }
                    
                    activeEmployeesMap[org.organization_code] = matchingData.count;
                } else {
                    console.log(`❌ No data found for ${org.organization_code}`);
                    activeEmployeesMap[org.organization_code] = 0;
                }
            } catch (error) {
                console.error(`Error fetching active employees for ${org.organization_code}:`, error);
                activeEmployeesMap[org.organization_code] = 0;
            }
        }
        
        console.log('🎉 Final activeEmployeesMap:', activeEmployeesMap);
        setActiveEmployeesByOrg(activeEmployeesMap);
        return activeEmployeesMap;
    }, [getMonthlyEmployee, filter]);

    React.useEffect(() => {
        if(resignSummary){
            const totalResign = resignSummary.reduce((acc, curr) => acc + curr.count, 0);
            setResign(totalResign);

            // Calculate active employees for all organizations in resignSummary
            const organizations = resignSummary.map(item => ({
                organization_code: item.organization_code,
                organization_name: item.organization_name
            }));
            
            calculateActiveEmployees(organizations).then((activeEmployeesMap) => {
                const totalActive = Object.values(activeEmployeesMap).reduce((acc, count) => acc + count, 0);
                setActive(totalActive);
                
                // Calculate turnover ratio
                if (totalActive > 0) {
                    setTurnOverRatio(parseFloat((totalResign / totalActive * 100).toFixed(2)));
                } else {
                    setTurnOverRatio(0);
                }

                // Now update limitedResignSummary with active employee data
                const sortedResignData = [...resignSummary]
                    .sort((a, b) => (b.count ) - (a.count ))
                    .map(item => ({
                        ...item,
                        active: activeEmployeesMap[item.organization_code] || 0
                    }));
                
                setLimitedResignSummary(sortedResignData);
            });
        }
    }, [resignSummary, calculateActiveEmployees]);

    React.useEffect(() => {
        if(resignType){
            const total = resignType.reduce((acc, curr) => acc + curr.count, 0);
            setTotalResignType(total);
        }
        
    }, [resignType]);

    React.useEffect(() => {
        if(resignReason){
            const total = resignReason.reduce((acc, curr) => acc + curr.count, 0);
            setTotalResignReason(total);
        }
    }, [resignReason]);

    // Process employee movement data for recruitment calculations
    React.useEffect(() => {
        if(employeeMovement && Object.keys(activeEmployeesByOrg).length > 0) {
            // Calculate total recruitment from employee movement data
            const totalRecruitmentCount = employeeMovement.reduce((acc, curr) => {
                return acc + (curr.recruitment || 0);
            }, 0);
            
            // Use the calculated active employee data
            const totalActiveCount = Object.values(activeEmployeesByOrg).reduce((acc, count) => acc + count, 0);
            
            // Calculate recruitment ratio (recruitment / total active * 100)
            const ratio = totalActiveCount > 0 ? parseFloat(((totalRecruitmentCount / totalActiveCount) * 100).toFixed(2)) : 0;
            
            setTotalRecruitment(totalRecruitmentCount);
            setTotalActiveEmployees(totalActiveCount);
            setRecruitmentRatio(ratio);
        }
    }, [employeeMovement, activeEmployeesByOrg]);

    // Process MPP recruitment data for chart
    React.useEffect(() => {
        if(mppRecruitment && employeeMovement) {
            // Aggregate MPP data by organization
            const mppMap = new Map<string, {
                organization_code: string;
                organization_name: string;
                mpp_target: number;
            }>();

            mppRecruitment.forEach(item => {
                const key = item.organization_code;
                if (mppMap.has(key)) {
                    const existing = mppMap.get(key)!;
                    existing.mpp_target += item.total;
                } else {
                    mppMap.set(key, {
                        organization_code: item.organization_code,
                        organization_name: item.organization_name,
                        mpp_target: item.total
                    });
                }
            });

            // Get actual recruitment data from employee movement
            const recruitmentMap = new Map<string, number>();
            employeeMovement.forEach(item => {
                recruitmentMap.set(item.organization_code, item.recruitment || 0);
            });

            // Calculate recruited vs remaining MPP positions
            const aggregatedData = Array.from(mppMap.values()).map(mppItem => {
                const actualRecruitment = recruitmentMap.get(mppItem.organization_code) || 0;
                const recruited = Math.min(actualRecruitment, mppItem.mpp_target); // Can't recruit more than target
                const remaining = Math.max(0, mppItem.mpp_target - recruited); // Remaining positions to fill
                
                return {
                    organization_code: mppItem.organization_code,
                    organization_name: mppItem.organization_name,
                    recruited: recruited,
                    remaining: remaining
                };
            });

            // Sort by total MPP target (recruited + remaining) and limit to top 10
            const sortedData = aggregatedData
                .sort((a, b) => (b.recruited + b.remaining) - (a.recruited + a.remaining))
                .slice(0, 10);
            
            setMppRecruitmentSummary(sortedData);
        }
    }, [mppRecruitment, employeeMovement]);

    const getColorByCategory = (category: string) => {
        switch(category){
            case "Whitelist":
                return "#EAEAEA";
            case "Blacklist":
                return "#3D3D3D";
            case "Yellowlist":
                return "#F5C41F";
            default:
                return undefined;
        }
    }

    // Show loader while any data is loading
    if (isLoading) {
        return <PageLoader text={t('turnover.loadingData')} />;
    }

    return (
        <div className="grid grid-cols-12 gap-4">
            <div className="col-span-4 bg-white rounded-lg py-4 px-4 max-h-[420px] flex flex-col">
                <div className="text-lg font-bold">{t('turnover.karyawanBaruSeluruh')}</div>
                {isLoadingEmployeeMovement ? (
                    <div className="flex-1 min-h-[300px] flex justify-center items-center flex-col">
                        <LucideLoader2 className="animate-spin" />
                    </div>
                ) : (
                    <>
                        <div className="relative h-24 bg-[#E8F4FD] mt-8 rounded-xl" ref={recruitmentRef}>
                            <div className={`absolute top-0 left-0 h-24 bg-[#2385DE] rounded-xl transition-all duration-1000`} style={{width: `${recruitmentWidth * recruitmentRatio / 100}px`}}></div>
                        </div>
                        <div className="flex mt-6 justify-around gap-3">
                            <div className="px-3 py-4 flex-1 flex flex-col border border-[#DDE8F8] rounded-lg">
                                <div className="text-sm text-[#5A5A5A]">{t('turnover.rasioRecruitment')}</div>
                                <div className="text-xl font-bold">{recruitmentRatio} %</div>
                            </div>
                            <div className="px-3 py-4 flex-1 flex flex-col border border-[#DDE8F8] rounded-lg">
                                <div className="text-sm text-[#5A5A5A]">{t('turnover.karyawanBaru')}</div>
                                <div className="text-xl font-bold">{totalRecruitment.toLocaleString('id-ID')}</div>
                            </div>
                            <div className="px-3 py-4 flex-1 flex flex-col border border-[#DDE8F8] rounded-lg">
                                <div className="text-sm text-[#5A5A5A]">{t('turnover.karyawanAktif')}</div>
                                <div className="text-xl font-bold">{totalActiveEmployees.toLocaleString('id-ID')}</div>
                            </div>
                        </div>
                    </>
                )}
            </div>
            <div className="col-span-8 bg-white py-4 pl-4 rounded-lg max-h-[420px] flex flex-col">
                <div className="text-xl font-bold">{t('turnover.manPowerPlanning')}</div>
                <div className="flex-1 min-h-[300px] relative">
                {mppRecruitmentSummary && !isLoadingMppRecruitment ? (
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={mppRecruitmentSummary.map(item => ({
                            ...item,
                            recruitedPercent: (item.recruited / (item.recruited + item.remaining)) * 100,
                            remainingPercent: (item.remaining / (item.recruited + item.remaining)) * 100
                        }))}>
                            {/* <CartesianGrid strokeDasharray="3 3" /> */}
                            <XAxis 
                                dataKey="organization_code" 
                                tick={{ fontSize: 12 }}
                            />
                            <YAxis 
                                tickFormatter={(value) => `${value}%`}
                            />
                            <Tooltip 
                                formatter={(value, name, props) => {
                                    const orgData = mppRecruitmentSummary.find(e => e.organization_code === props.payload.organization_code);
                                    if (name === t('turnover.recruited')) {
                                        return [`${orgData?.recruited || 0} ${t('common.employees')}`, t('turnover.recruited')];
                                    } else {
                                        return [`${orgData?.remaining || 0} ${t('common.employees')}`, t('turnover.remaining')];
                                    }
                                }}
                                labelFormatter={(label) => {
                                    const org = mppRecruitmentSummary.find(e => e.organization_code === label);
                                    return org?.organization_name || label;
                                }}
                            />
                            <Legend />
                            <Bar dataKey="recruitedPercent" stackId="a" fill="#F7B500" name={t('turnover.recruited')} />
                            <Bar dataKey="remainingPercent" stackId="a" fill="#2385DE" name={t('turnover.remaining')} />
                        </BarChart>
                    </ResponsiveContainer>
                ) : isLoadingMppRecruitment ? (
                    <LucideLoader2 className="absolute top-1/2 left-1/2 animate-spin" />
                ) : (
                    <div className="absolute inset-0 flex justify-center items-center">
                        <span className="text-gray-600">{t('common.dataNotAvailable')}</span>
                    </div>
                )}
                </div>
            </div>
            <div className="col-span-4 bg-white rounded-lg py-4 px-4 max-h-[420px] flex flex-col">
                <div className="text-lg font-bold">{t('turnover.karyawanResignSeluruh')}</div>
                <div className="relative h-24 bg-[#C7EBEB] mt-8 rounded-xl" ref={resignRef}>
                    <div className={`absolute top-0 left-0 h-24 bg-[#6AC8C8] rounded-xl transition-all duration-1000`} style={{width: `${width * turnOverRatio / 100}px`}}></div>
                </div>
                <div className="flex mt-6 justify-around gap-3">
                    <div className="px-3 py-4 flex-1 flex flex-col border border-[#DDE8F8] rounded-lg">
                        <div className="text-sm text-[#5A5A5A]">{t('turnover.rasioTurnOver')}</div>
                        <div className="text-xl font-bold">{turnOverRatio} %</div>
                    </div>
                    <div className="px-3 py-4 flex-1 flex flex-col border border-[#DDE8F8] rounded-lg">
                        <div className="text-sm text-[#5A5A5A]">{t('turnover.karyawanResign')}</div>
                        <div className="text-xl font-bold">{resign.toLocaleString('id-ID')}</div>
                    </div>
                    <div className="px-3 py-4 flex-1 flex flex-col border border-[#DDE8F8] rounded-lg">
                        <div className="text-sm text-[#5A5A5A]">{t('turnover.karyawanAktif')}</div>
                        <div className="text-xl font-bold">{active.toLocaleString('id-ID')}</div>
                    </div>
                </div>
            </div>
            <div className="col-span-8 bg-white py-4 pl-4 rounded-lg max-h-[420px] flex flex-col">
                <div className="text-xl font-bold">{t('turnover.resignmentPerPerusahaan')}</div>
                <div className="flex-1 min-h-[300px] relative">
                {limitedResignSummary && !isLoadingResignSummary ? (
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={limitedResignSummary.map(item => ({
                            ...item,
                            resignPercent: (item.count / (item.count + item.active)) * 100,
                            activePercent: (item.active / (item.count + item.active)) * 100
                        }))}>
                            {/* <CartesianGrid strokeDasharray="3 3" /> */}
                            <XAxis 
                                dataKey="organization_code" 
                                tick={{ fontSize: 12 }}
                            />
                            <YAxis 
                                tickFormatter={(value) => `${value}%`}
                            />
                            <Tooltip 
                                formatter={(value, name, props) => {
                                    const orgData = limitedResignSummary.find(e => e.organization_code === props.payload.organization_code);
                                    if (name === t('turnover.resign')) {
                                        return [`${orgData?.count?.toLocaleString('id-ID') || 0} ${t('common.employees')}`, t('turnover.resign')];
                                    } else {
                                        return [`${orgData?.active?.toLocaleString('id-ID') || 0} ${t('common.employees')}`, t('turnover.active')];
                                    }
                                }}
                                labelFormatter={(label) => {
                                    const org = limitedResignSummary.find(e => e.organization_code === label);
                                    return org?.organization_name || label;
                                }}
                            />
                            <Legend />
                            <Bar dataKey="resignPercent" stackId="a" fill="#F7B500" name={t('turnover.resign')} />
                            <Bar dataKey="activePercent" stackId="a" fill="#2385DE" name={t('turnover.active')} />
                        </BarChart>
                    </ResponsiveContainer>
                ) : isLoadingResignSummary || isFetchingResignSummary ? (
                    <LucideLoader2 className="absolute top-1/2 left-1/2 animate-spin" />
                ) : (
                    <div className="absolute inset-0 flex justify-center items-center">
                        <span className="text-gray-600">{t('common.dataNotAvailable')}</span>
                    </div>
                )}
                </div>
            </div>
            <div className="col-span-4 bg-white py-4 px-4 rounded-lg max-h-[480px] flex flex-col">
                <div className="text-xl font-bold">{t('turnover.jenisPemutusanHubungan')}</div>
                <div className={`flex-1 min-h-[300px] gap-3 flex flex-col mt-8 ${resignType && resignType.length === 0 ? "justify-center items-center" : ""}`}>
                    {resignType && resignType.map((resign, index) => (
                        <div key={index} className="grid grid-cols-12 items-center"  data-tooltip-id="tooltip-tor-type" data-tooltip-content={`${resign.count} ${t('common.employee')}`}>
                            <div className="text-sm col-span-3 text-gray-600">{resign.type}</div>
                            <div className="col-span-1"/>
                            <div className="relative col-span-8 h-6 bg-[#2385DE] rounded-lg">
                                <div className="absolute top-0 left-0 h-6 bg-[#F7B500] rounded-lg" style={{width: `${totalResignType > 0 ? (resign.count / totalResignType * 100) : 0}%`}}/>
                            </div>
                        </div>
                    ))}
                    {resignType && resignType.length === 0 && <span className="text-black text-sm text-center">{t('common.dataNotAvailable')}</span>}
                    <ReactTooltip id="tooltip-tor-type" />
                </div>
            </div>
            <div className="col-span-4 bg-white py-4 px-4 rounded-lg max-h-[480px] flex flex-col">
                <div className="text-xl font-bold">{t('turnover.kategoriResign')}</div>
                <div className="w-4/5 flex-1 flex mx-auto">
                    {resignCategory && resignCategory.length > 0 ? (
                        <ResponsiveContainer width="100%" height="100%">
                            <PieChart>
                                <Pie
                                    data={resignCategory.map(e => ({name: e.category, value: e.count}))}
                                    cx="50%"
                                    cy="50%"
                                    outerRadius={120}
                                    innerRadius={90}
                                    dataKey="value"
                                    label={({ name }) => name}
                                    labelLine={false}
                                >
                                    {resignCategory.map((entry, index) => (
                                        <Cell key={`cell-${index}`} fill={getColorByCategory(entry.category)} />
                                    ))}
                                </Pie>
                                <Tooltip formatter={(value, name) => [`${value} ${t('common.employees')}`, name]} />
                                <Legend 
                                    verticalAlign="bottom" 
                                    align="center" 
                                    layout="horizontal"
                                    wrapperStyle={{ paddingTop: '20px' }}
                                />
                            </PieChart>
                        </ResponsiveContainer>
                    ) : (
                        <div className="flex justify-center items-center h-full">
                            <span className="text-gray-600">{t('common.dataNotAvailable')}</span>
                        </div>
                    )}
                    </div>
            </div>
            <div className="col-span-4 bg-white py-4 px-4 rounded-lg max-h-[480px] flex flex-col">
                <div className="text-xl font-bold">{t('turnover.alasanPemutusanHubungan')}</div>
                <div className={`flex-1 min-h-[300px] gap-3 flex flex-col mt-8 ${resignReason && resignReason.length === 0 ? "justify-center items-center" : ""}`}>
                    {resignReason && resignReason.map((resign, index) => (
                        <div key={index} className="grid grid-cols-12 items-center" data-tooltip-id="tooltip-tor-type" data-tooltip-content={`${resign.count} ${t('common.employee')}`}>
                            <div className="text-sm col-span-3 text-gray-600">{resign.reason}</div>
                            <div className="col-span-1"/>
                            <div className="relative col-span-8 h-6 bg-[#2385DE] rounded-lg">
                                <div className="absolute top-0 left-0 h-6 bg-[#F7B500] rounded-lg" style={{width: `${totalResignReason > 0 ? (resign.count / totalResignReason * 100) : 0}%`}}/>
                            </div>
                        </div>
                    ))}
                    {resignReason && resignReason.length === 0 && <span className="text-black text-sm text-center">{t('common.dataNotAvailable')}</span>}
                    <ReactTooltip id="tooltip-tor-type" />
                </div>
            </div>
        </div>
    )
}