"use client"
import { useAppSelector } from "@/lib/hooks";
import { useGetEmployeeSummaryQuery, useGetEmployeeMovementQuery, useGetMonthlyEmployeeQuery, useGetSanctionSummaryQuery } from "@/services/api";
import { ExclamationCircleIcon } from "@heroicons/react/24/outline";
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, Area, AreaChart } from "recharts";
import { formatDate } from "date-fns";
import { useEffect, useState } from "react";
import { PageLoader } from "@/components/Loader";
import { useLocale } from "@/lib/hooks/useLocale";

export default function KaryawanPage() {
  const { t } = useLocale();
  const filter = useAppSelector(state => state.filter.filter);
  const {data: employeeSummary, isFetching : loadingSummary} = useGetEmployeeSummaryQuery(filter);
  const {data: montlyEmployee, isFetching : loadingMonthly} = useGetMonthlyEmployeeQuery(filter);
  const {data: sanctionSummary, isFetching: loadingSanction} = useGetSanctionSummaryQuery(filter);
  const {data: employeeMovement, isFetching: loadingMovement} = useGetEmployeeMovementQuery(filter);

  // Combine all loading states
  const isLoading = loadingSummary || loadingMonthly || loadingSanction || loadingMovement;
  const [totalSanctions, setTotalSanctions] = useState<{
    type: string;
    count: number;
  }[]>([]);
  const [movementSummary, setMovementSummary] = useState<{
    type: string;
    count: number;
  }[]>([]);
  const [topMovementCompanies, setTopMovementCompanies] = useState<{
    organization_code: string;
    organization_name: string;
    recruitment: number;
    resignation: number;
    promotion: number;
    mutation: number;
    demotion: number;
    total_movement: number;
  }[]>([]);

  useEffect(() => {
    if (sanctionSummary) {
      const tmp = sanctionSummary.reduce((acc, curr) => {
        acc.push({type: "st", count: curr.st});
        acc.push({type: "sp1", count: curr.sp1});
        acc.push({type: "sp2", count: curr.sp2});
        acc.push({type: "sp3", count: curr.sp3});
        return acc;
      }, [] as {type: string; count: number}[]);
      //add total
      const total = tmp.reduce((acc, curr) => {
        acc[curr.type] = (acc[curr.type] || 0) + curr.count;
        return acc;
      }, {} as {[key: string]: number});
      setTotalSanctions(Object.keys(total).map(key => ({type: key, count: total[key]})));
    }
  }, [sanctionSummary]);

  useEffect(() => {
    if (employeeMovement) {
      // Calculate total movement summary for pie chart
      const totalRecruitment = employeeMovement.reduce((sum, item) => sum + item.recruitment, 0);
      const totalResignation = employeeMovement.reduce((sum, item) => sum + item.resignation, 0);
      const totalPromotion = employeeMovement.reduce((sum, item) => sum + item.promotion, 0);
      const totalMutation = employeeMovement.reduce((sum, item) => sum + item.mutation, 0);
      const totalDemotion = employeeMovement.reduce((sum, item) => sum + item.demotion, 0);

      setMovementSummary([
        { type: "Recruitment", count: totalRecruitment },
        { type: "Resignation", count: totalResignation },
        { type: "Promotion", count: totalPromotion },
        { type: "Mutation", count: totalMutation },
        { type: "Demotion", count: totalDemotion },
      ].filter(item => item.count > 0)); // Only show categories with data

      // Calculate top 10 companies by total movement for detailed breakdown
      const companiesWithMovement = employeeMovement.map(company => ({
        organization_code: company.organization_code,
        organization_name: company.organization_name,
        recruitment: company.recruitment,
        resignation: company.resignation,
        promotion: company.promotion,
        mutation: company.mutation,
        demotion: company.demotion,
        total_movement: company.recruitment + company.resignation + company.promotion + company.mutation + company.demotion
      })).filter(company => company.total_movement > 0)
        .sort((a, b) => b.total_movement - a.total_movement)
        .slice(0, 10);

      setTopMovementCompanies(companiesWithMovement);
    }
  }, [employeeMovement]);

  useEffect(() => {
    console.log(filter);
  }, [filter]);

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

  return (
    <div className="grid grid-cols-12 gap-4">
      <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('employee.dataKaryawan')}</div>
        <div className="flex-1 min-h-[300px] relative">
          {employeeSummary && employeeSummary.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={[...employeeSummary].sort((a, b) => b.count - a.count)}>
                {/* <CartesianGrid strokeDasharray="3 3" /> */}
                <XAxis 
                  dataKey="organization_code" 
                  tick={{ fontSize: 12 }}
                />
                <YAxis />
                <Tooltip 
                  formatter={(value, name) => [`${Number(value).toLocaleString('id-ID')} ${t('employee.karyawan')}`, t('employee.jumlahKaryawan')]}
                  labelFormatter={(label) => {
                    const org = employeeSummary.find(e => e.organization_code === label);
                    return org?.organization_name || label;
                  }}
                />
                <Bar dataKey="count" fill="#2385DE" />
              </BarChart>
            </ResponsiveContainer>
          ) : !loadingSummary ? (
            <div className="absolute inset-0 flex justify-center items-center">
              <div className="text-gray-400 flex flex-col items-center">
                <span className="text-gray-600">{t('common.dataNotAvailable')}</span>
              </div>
            </div>
          ) : null}
        </div>
      </div>
      <div className="col-span-4 bg-white rounded-lg py-4 pl-4 max-h-[420px] flex flex-col">
        <div className="text-xl font-bold">{t('employee.dataKaryawanPerbulan')}</div>
        <div className="flex-1 min-h-[300px] relative">
          {montlyEmployee && montlyEmployee.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={montlyEmployee}>
                {/* <CartesianGrid strokeDasharray="3 3" /> */}
                <XAxis 
                  dataKey="date" 
                  tick={{ fontSize: 12 }}
                  tickFormatter={(value) => formatDate(new Date(value), "MMM")}
                />
                <YAxis />
                <Tooltip 
                  formatter={(value, name) => [`${Number(value).toLocaleString('id-ID')} ${t('employee.karyawan')}`, t('employee.jumlahKaryawan')]}
                  labelFormatter={(label) => formatDate(new Date(label), "MMMM yyyy")}
                />
                <Area 
                  type="monotone" 
                  dataKey="count" 
                  stroke="#F7CAA9" 
                  fill="#F7CAA9" 
                  fillOpacity={0.6}
                />
              </AreaChart>
            </ResponsiveContainer>
          ) : !loadingMonthly ? (
            <div className="absolute inset-0 flex justify-center items-center">
              <div className="text-gray-400 flex flex-col items-center">
                <span className="text-gray-600">{t('common.dataNotAvailable')}</span>
              </div>
            </div>
          ) : null}
        </div>
      </div>
      <div className="col-span-4 bg-white rounded-lg py-4 pl-4 max-h-[420px] flex flex-col">
        <div className="text-xl font-bold">{t('employee.pergerakanKaryawan')}</div>
        <div className="flex-1 min-h-[300px] relative">
          {movementSummary && movementSummary.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={movementSummary.map(e => ({name: e.type, value: e.count}))}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={120}
                  paddingAngle={0}
                  dataKey="value"
                  // label={({ name, value }) => `${name}: ${value}`}
                  labelLine={false}
                >
                  {movementSummary.map((entry, index) => {
                    const colors = ["#2385DE","#F7B500","#69C9C9","#8A5FB1","#E65550"];
                    return <Cell key={`cell-${index}`} fill={colors[index % colors.length]} />;
                  })}
                </Pie>
                <Tooltip formatter={(value, name) => [`${Number(value).toLocaleString('id-ID')} ${t('employee.karyawan')}`, name]} />
                <Legend 
                  verticalAlign="middle" 
                  align="right" 
                  layout="vertical"
                  wrapperStyle={{ paddingLeft: '20px' }}
                />
              </PieChart>
            </ResponsiveContainer>
          ) : !loadingMovement ? (
            <div className="absolute inset-0 flex justify-center items-center">
              <div className="text-gray-400 flex flex-col items-center">
                <span className="text-gray-600">{t('common.dataNotAvailable')}</span>
              </div>
            </div>
          ) : null}
        </div>
      </div>
      <div className="col-span-8 bg-white rounded-lg py-4 pl-4 max-h-[420px] flex flex-col">
        <div className="text-xl font-bold">{t('employee.rankingPergerakanKaryawan')}</div>
        <div className="flex-1 min-h-[300px] relative">
          {topMovementCompanies && topMovementCompanies.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={topMovementCompanies}>
                {/* <CartesianGrid strokeDasharray="3 3" /> */}
                <XAxis 
                  dataKey="organization_code" 
                  tick={{ fontSize: 12 }}
                />
                <YAxis label={{ value: t('employee.jumlahPergerakan'), angle: -90, position: 'insideLeft' }} />
                <Tooltip 
                  formatter={(value, name) => [`${Number(value).toLocaleString('id-ID')} ${t('employee.karyawan')}`, name]}
                  labelFormatter={(label) => {
                    const org = topMovementCompanies.find(e => e.organization_code === label);
                    return org?.organization_name || label;
                  }}
                />
                <Legend />
                <Bar dataKey="recruitment" fill="#2385DE" name={t('employee.recruitment')} />
                <Bar dataKey="resignation" fill="#F7B500" name={t('employee.resignation')} />
                <Bar dataKey="promotion" fill="#69C9C9" name={t('employee.promotion')} />
                <Bar dataKey="mutation" fill="#8A5FB1" name={t('employee.mutation')} />
                <Bar dataKey="demotion" fill="#E65550" name={t('employee.demotion')} />
              </BarChart>
            </ResponsiveContainer>
          ) : !loadingMovement ? (
            <div className="absolute inset-0 flex justify-center items-center">
              <div className="text-gray-400 flex flex-col items-center">
                <span className="text-gray-600">{t('common.dataNotAvailable')}</span>
              </div>
            </div>
          ) : null}
        </div>
      </div>
      <div className="col-span-4 bg-white rounded-lg py-4 pl-4 max-h-[420px] flex flex-col">
        <div className="text-xl font-bold">{t('employee.penjatuhanSanksi')}</div>
        <div className="flex-1 min-h-[300px] flex justify-center items-center flex-col">
          {totalSanctions && totalSanctions.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={totalSanctions}>
                {/* <CartesianGrid strokeDasharray="3 3" /> */}
                <XAxis 
                  dataKey="type" 
                  tick={{ fontSize: 12 }}
                  tickFormatter={(value) => value.toUpperCase()}
                />
                <YAxis />
                <Tooltip 
                  formatter={(value, name) => [`${Number(value).toLocaleString('id-ID')} ${t('common.total')}`, name]}
                  labelFormatter={(label) => label.toUpperCase()}
                />
                <Bar dataKey="count" fill="#F5C322" />
              </BarChart>
            </ResponsiveContainer>
          ) : (
            <div className="text-gray-400 flex flex-col items-center">
              <span className="text-gray-600">{t('common.dataNotAvailable')}</span>
            </div>
          )}
        </div>
      </div>
      <div className="col-span-8 bg-white rounded-lg py-4 pl-4 max-h-[420px] flex flex-col">
        <div className="text-xl font-bold">{t('employee.rankingSanksi')}</div>
        <div className="flex-1 min-h-[300px] flex justify-center items-center flex-col">
          {sanctionSummary && sanctionSummary.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={[...sanctionSummary.slice().sort((a, b) => b.st + b.sp1 + b.sp2 + b.sp3 - a.st - a.sp1 - a.sp2 - a.sp3).slice(0, 10)]}>
                {/* <CartesianGrid strokeDasharray="3 3" /> */}
                <XAxis 
                  dataKey="organization_code" 
                  tick={{ fontSize: 12 }}
                />
                <YAxis />
                <Tooltip 
                  formatter={(value, name) => [`${Number(value).toLocaleString('id-ID')} ${t('common.total')}`, name]}
                  labelFormatter={(label) => {
                    const org = sanctionSummary?.find(e => e.organization_code === label);
                    return org?.organization_name || label;
                  }}
                />
                <Legend />
                <Bar dataKey="st" fill="#F5C322" name="ST" />
                <Bar dataKey="sp1" fill="#F3832D" name="SP1" />
                <Bar dataKey="sp2" fill="#F6CBAB" name="SP2" />
                <Bar dataKey="sp3" fill="#E65551" name="SP3" />
              </BarChart>
            </ResponsiveContainer>
          ) : !loadingSanction ? (
            <div className="text-gray-400 flex flex-col items-center">
              <span className="text-gray-600">{t('common.dataNotAvailable')}</span>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
}