"use client"

import React from "react";
import { useAppSelector } from "@/lib/hooks";
import { useLocale } from "@/lib/hooks/useLocale";
import { useGetHrCostByJobQuery, useGetHrCostQuery, useGetHrCostByOrganizationQuery, useGetHrCostPerMonthQuery, useGetHrCostPerEmployeeQuery } from "@/services/api";
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend, BarChart, Bar, XAxis, YAxis, CartesianGrid, LineChart, Line } from "recharts";
import { PageLoader } from "@/components/Loader";
import { DataGrid, GridColDef, GridToolbar } from "@mui/x-data-grid";
import { ArrowsPointingOutIcon, ArrowsPointingInIcon, MagnifyingGlassIcon } from "@heroicons/react/24/outline";

// Colors for the pie chart
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8', '#82CA9D'];

export default function HrcostPage() {
    const { t } = useLocale();
    const filter = useAppSelector(state => state.filter.filter);
    const { data: hrCostByJob, isLoading: isLoadingHrCostByJob, isFetching: isFetchingHrCostByJob } = useGetHrCostByJobQuery(filter);
    const { data: hrCost, isLoading: isLoadingHrCost, isFetching: isFetchingHrCost } = useGetHrCostQuery(filter);
    const { data: hrCostByOrganization, isLoading: isLoadingHrCostByOrganization, isFetching: isFetchingHrCostByOrganization } = useGetHrCostByOrganizationQuery(filter);
    const { data: hrCostPerMonth, isLoading: isLoadingHrCostPerMonth, isFetching: isFetchingHrCostPerMonth } = useGetHrCostPerMonthQuery(filter);
    const { data: hrCostPerEmployee, isLoading: isLoadingHrCostPerEmployee, isFetching: isFetchingHrCostPerEmployee } = useGetHrCostPerEmployeeQuery({
        ...filter,
        job_name: "HARVESTERS"
    });
    const [isFullscreen, setIsFullscreen] = React.useState(false);

    const isLoading = isLoadingHrCostByJob || isFetchingHrCostByJob || isLoadingHrCost || isFetchingHrCost || isLoadingHrCostByOrganization || isFetchingHrCostByOrganization || isLoadingHrCostPerMonth || isFetchingHrCostPerMonth || isLoadingHrCostPerEmployee || isFetchingHrCostPerEmployee;

    if (isLoading) {
        return <PageLoader text={t('hrcost.loadingData')} />;
    }

    if (isFullscreen) {
        const salaries = hrCostPerEmployee?.map(emp => emp.salary) || [];
        const grandTotal = salaries.reduce((sum, salary) => sum + salary, 0);
        const avgSalary = salaries.length > 0 ? grandTotal / salaries.length : 0;
        const maxSalary = salaries.length > 0 ? Math.max(...salaries) : 0;

        return (
            <div className="grid grid-cols-12 gap-4">
                <div className="col-span-12">
                    <div className="bg-white p-4 rounded-md shadow-md">
                        <div className="flex justify-between items-center mb-4">
                            <div className="text-xl font-bold">{t('hrcost.rincianGajiPemanen')}</div>
                            <div className="flex items-center gap-2">
                                <div className="text-sm text-gray-500">{t('common.total')}: {hrCostPerEmployee?.length?.toLocaleString('id-ID') || 0} {t('common.karyawan')}</div>
                                <button
                                    className="p-2 border rounded hover:bg-gray-50"
                                    onClick={() => setIsFullscreen(false)}
                                    title={t('hrcost.keluarFullscreen')}
                                >
                                    <ArrowsPointingInIcon className="w-4 h-4" />
                                </button>
                            </div>
                        </div>
                        
                        <div className="grid grid-cols-12 gap-4 mb-4">
                            {/* Information Cards */}
                            <div className="col-span-8 grid grid-cols-3 gap-4">
                                <div className="bg-blue-50 p-3 rounded-lg border">
                                    <div className="text-sm text-blue-600 font-medium">{t('hrcost.grandTotalGaji')}</div>
                                    <div className="text-lg font-bold text-blue-800">Rp. {grandTotal.toLocaleString('id-ID')}</div>
                                </div>
                                <div className="bg-green-50 p-3 rounded-lg border">
                                    <div className="text-sm text-green-600 font-medium">{t('hrcost.rataRataGaji')}</div>
                                    <div className="text-lg font-bold text-green-800">Rp. {Math.round(avgSalary).toLocaleString('id-ID')}</div>
                                </div>
                                <div className="bg-purple-50 p-3 rounded-lg border">
                                    <div className="text-sm text-purple-600 font-medium">{t('hrcost.gajiTertinggi')}</div>
                                    <div className="text-lg font-bold text-purple-800">Rp. {maxSalary.toLocaleString('id-ID')}</div>
                                </div>
                            </div>
                            
                        </div>
                        
                        <div style={{ height: 'calc(100vh - 420px)' }}>
                            <EmployeeDataGrid data={hrCostPerEmployee || []} isFullscreen />
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    // Format data for pie chart (Gaji Karyawan)
    const pieChartData = hrCostByJob?.map((item, index) => ({
        name: item.job_label,
        value: item.total_salary,
        valueInMillions: item.total_salary / 1000000000, // Convert to millions (9 zeros)
        color: COLORS[index % COLORS.length]
    })) || [];

    // Format data for HR Cost pie chart
    const hrCostPieData = hrCost ? [
        {
            name: t('hrcost.gaji'),
            value: hrCost.total_salary,
            valueInMillions: hrCost.total_salary / 1000000000,
            color: COLORS[0]
        },
        {
            name: t('hrcost.bpjsTk'),
            value: hrCost.total_bpjs_tk,
            valueInMillions: hrCost.total_bpjs_tk / 1000000000,
            color: COLORS[1]
        },
        {
            name: t('hrcost.bpjsKs'),
            value: hrCost.total_bpjs_ks,
            valueInMillions: hrCost.total_bpjs_ks / 1000000000,
            color: COLORS[2]
        },
        {
            name: t('hrcost.thr'),
            value: hrCost.total_thr,
            valueInMillions: hrCost.total_thr / 1000000000,
            color: COLORS[3]
        }
    ] : [];

    // Prepare bar chart data for top 10 organizations
    const organizationBarData = hrCostByOrganization ? 
        [...hrCostByOrganization]
            .sort((a, b) => b.total_salary - a.total_salary)
            .slice(0, 10)
            .map(org => ({
                organization_code: org.organization_code,
                organization_name: org.organization_name,
                total_salary: org.total_salary,
                valueInMillions: org.total_salary / 1000000000
            })) : [];

    // Prepare line chart data for monthly HR cost
    const monthlyLineData = hrCostPerMonth ? 
        [...hrCostPerMonth]
            .sort((a, b) => {
                if (a.year !== b.year) return a.year - b.year;
                return a.month - b.month;
            })
            .map(month => ({
                month: month.month,
                month_name: month.month_name,
                year: month.year,
                total_salary: month.total_salary,
                valueInMillions: month.total_salary / 1000000000,
                displayName: `${month.month_name} ${month.year}`
            })) : [];

    // Format currency for display in millions
    const formatCurrency = (value: number) => {
        const valueInMillions = value / 1000000000;
        return `${valueInMillions.toFixed(2)} M IDR`;
    };

    // Custom tooltip for pie chart
    const CustomTooltip = ({ active, payload }: any) => {
        if (active && payload && payload.length) {
            const data = payload[0];
            return (
                <div className="bg-white p-3 border border-gray-300 rounded shadow-lg">
                    <p className="font-semibold">{data.name}</p>
                    <p className="text-blue-600">
                        {formatCurrency(data.value)}
                    </p>
                </div>
            );
        }
        return null;
    };

    return (
        <div className="grid grid-cols-12 gap-4">
            <div className="col-span-8 flex flex-col" >
                <div className="bg-white p-4 rounded-md shadow-md flex-1">        
                    <div className="text-xl font-bold mb-4">{t('hrcost.hrCost')}</div>
                        <ResponsiveContainer width="100%" height="90%">
                            <PieChart>
                                <Pie
                                    data={hrCostPieData}
                                    cx="50%"
                                    cy="40%"
                                    labelLine={false}
                                    label={({ name, percent, valueInMillions }) => `${name} ${(valueInMillions as number).toFixed(1)}M IDR (${(percent as number * 100).toFixed(1)}%)`}
                                    outerRadius={"80%"}
                                    innerRadius={"60%"}
                                    fill="#8884d8"
                                    dataKey="value"
                                >
                                    {hrCostPieData.map((entry, index) => (
                                        <Cell key={`cell-${index}`} fill={entry.color} />
                                    ))}
                                </Pie>
                                <Tooltip content={<CustomTooltip />} />
                                <Legend 
                                    verticalAlign="bottom" 
                                    align="center"
                                    layout="horizontal"
                                    iconType="circle"
                                    wrapperStyle={{ paddingTop: '20px' }}
                                />
                            </PieChart>
                        </ResponsiveContainer>
                </div>
            </div>
            <div className="col-span-4">
                <div className="flex flex-col gap-4">
                    <div className="bg-white p-4 rounded-md shadow-md">                  
                        <div className="text-xl font-bold mb-4">{t('hrcost.gajiKaryawan')}</div>
                        <div className="h-48">
                            <ResponsiveContainer width="100%" height="100%">
                                <PieChart>
                                    <Pie
                                        data={pieChartData}
                                        cx="50%"
                                        cy="50%"
                                        labelLine={false}
                                        // label={({ name, percent, valueInMillions }) => `${name} ${(valueInMillions as number).toFixed(2)}M IDR (${(percent as number * 100).toFixed(2)}%)`}
                                        outerRadius={85}
                                        innerRadius={60}
                                        fill="#8884d8"
                                        dataKey="value"
                                    >
                                        {pieChartData.map((entry, index) => (
                                            <Cell key={`cell-${index}`} fill={entry.color} />
                                        ))}
                                    </Pie>
                                    <Tooltip content={<CustomTooltip />} />
                                    <Legend 
                                        verticalAlign="middle" 
                                        align="right"
                                        layout="vertical"
                                        iconType="circle"
                                        wrapperStyle={{ paddingLeft: '20px' }}
                                    />
                                </PieChart>
                            </ResponsiveContainer>
                        </div>
                    </div>
                    <div className="bg-white p-4 rounded-md shadow-md">      
                        <div className="text-xl font-bold mb-4">{t('hrcost.rankingTop10')}</div>
                        <div className="h-48">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart
                                    data={organizationBarData}
                                    margin={{
                                        top: 5,
                                        right: 30,
                                        left: 20,
                                        bottom: 5,
                                    }}
                                >
                                    <XAxis 
                                        dataKey="organization_code" 
                                        tick={{ fontSize: 12 }}
                                        angle={-45}
                                        textAnchor="end"
                                        height={40}
                                    />
                                    <YAxis 
                                        tick={{ fontSize: 12 }}
                                        tickFormatter={(value) => `${(value / 1000000000).toFixed(1)}M`}
                                        
                                    />
                                    <Tooltip 
                                        formatter={(value: number, name: string) => [
                                            `${(value / 1000000000).toFixed(2)} M IDR`,
                                            t('hrcost.totalSalary')
                                        ]}
                                        labelFormatter={(label: string) => {
                                            const org = organizationBarData.find(item => item.organization_code === label);
                                            return org ? org.organization_name : label;
                                        }}
                                    />
                                    <Bar dataKey="total_salary" fill="#8884d8" />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </div>
                </div>
            </div>
            <div className="col-span-8">
                <div className="bg-white p-4 rounded-md shadow-md flex-1 flex flex-col">
                    <div className="flex justify-between items-center mb-4">
                        <div className="text-xl font-bold">{t('hrcost.rincianGajiPemanen')}</div>
                        <div className="flex items-center gap-2">
                            <div className="text-sm text-gray-500">{t('common.total')}: {hrCostPerEmployee?.length?.toLocaleString('id-ID') || 0} {t('common.karyawan')}</div>
                            <button
                                className="p-2 border rounded hover:bg-gray-50"
                                onClick={() => setIsFullscreen(true)}
                                title={t('hrcost.fullscreen')}
                            >
                                <ArrowsPointingOutIcon className="w-4 h-4" />
                            </button>
                        </div>
                    </div>
                    
                    {/* Information Cards and Search Box - Top of table section */}
                    <div className="grid grid-cols-12 gap-4 mb-4">
                        {/* Information Cards */}
                        <div className="col-span-8 grid grid-cols-3 gap-4">
                            <div className="bg-blue-50 p-3 rounded-lg border">
                                <div className="text-sm text-blue-600 font-medium">{t('hrcost.grandTotalGaji')}</div>
                                <div className="text-lg font-bold text-blue-800">Rp. {(() => {
                                    const salaries = hrCostPerEmployee?.map(emp => emp.salary) || [];
                                    return salaries.reduce((sum, salary) => sum + salary, 0).toLocaleString('id-ID');
                                })()}</div>
                            </div>
                            <div className="bg-green-50 p-3 rounded-lg border">
                                <div className="text-sm text-green-600 font-medium">{t('hrcost.rataRataGaji')}</div>
                                <div className="text-lg font-bold text-green-800">Rp. {(() => {
                                    const salaries = hrCostPerEmployee?.map(emp => emp.salary) || [];
                                    const avg = salaries.length > 0 ? salaries.reduce((sum, salary) => sum + salary, 0) / salaries.length : 0;
                                    return Math.round(avg).toLocaleString('id-ID');
                                })()}</div>
                            </div>
                            <div className="bg-purple-50 p-3 rounded-lg border">
                                <div className="text-sm text-purple-600 font-medium">{t('hrcost.gajiTertinggi')}</div>
                                <div className="text-lg font-bold text-purple-800">Rp. {(() => {
                                    const salaries = hrCostPerEmployee?.map(emp => emp.salary) || [];
                                    const max = salaries.length > 0 ? Math.max(...salaries) : 0;
                                    return max.toLocaleString('id-ID');
                                })()}</div>
                            </div>
                        </div>
                        
                    </div>
                    
                    <div className="flex-1">
                        <EmployeeDataGrid data={hrCostPerEmployee || []} />
                    </div>
                </div>
            </div>
            <div className="col-span-4">
                <div className="bg-white p-4 rounded-md shadow-md flex-1">
                    <div className="text-xl font-bold mb-4">{t('hrcost.totalGajiSetiapBulan')}</div>
                    <div className="h-96">
                        <ResponsiveContainer width="100%" height="100%">
                            <LineChart
                                data={monthlyLineData}
                                margin={{
                                    top: 5,
                                    right: 30,
                                    left: 20,
                                    bottom: 5,
                                }}
                            >
                                <CartesianGrid strokeDasharray="3 3" />
                                <XAxis 
                                    dataKey="month_name" 
                                    tick={{ fontSize: 12 }}
                                    angle={-45}
                                    textAnchor="end"
                                    height={60}
                                />
                                <YAxis 
                                    tick={{ fontSize: 12 }}
                                    tickFormatter={(value) => `${(value / 1000000000).toFixed(1)}M`}
                                />
                                <Tooltip 
                                    formatter={(value: number, name: string) => [
                                        `${(value / 1000000000).toFixed(2)} M IDR`,
                                        t('hrcost.totalSalary')
                                    ]}
                                    labelFormatter={(label: string) => {
                                        const month = monthlyLineData.find(item => item.month_name === label);
                                        return month ? month.displayName : label;
                                    }}
                                />
                                <Line 
                                    type="monotone" 
                                    dataKey="total_salary" 
                                    stroke="#8884d8" 
                                    strokeWidth={2}
                                    dot={{ fill: '#8884d8', strokeWidth: 2, r: 4 }}
                                    activeDot={{ r: 6 }}
                                />
                            </LineChart>
                        </ResponsiveContainer>
                    </div>
                </div>
            </div>
        </div>
    )
}

function EmployeeDataGrid({ data, isFullscreen = false }: { data: { id_karyawan: string; name: string; address: string; salary: number; }[], isFullscreen?: boolean }) {
    const { t } = useLocale();
    const columns: GridColDef[] = [
        { field: 'id_karyawan', headerName: t('hrcost.idKaryawan'), flex: 1, minWidth: 150 },
        { field: 'name', headerName: t('hrcost.nama'), flex: 1, minWidth: 180 },
        { field: 'address', headerName: t('hrcost.alamat'), flex: 1, minWidth: 220 },
        {
            field: 'salary',
            headerName: t('hrcost.gajiIdr'),
            flex: 1,
            minWidth: 160,
            type: 'number',
            valueFormatter: (params: number) => 'Rp. '+params?.toLocaleString('id-ID') || '0',
        },
    ];

    const rows = data.map((d) => ({ id: d.id_karyawan, ...d }));

    const containerStyle = isFullscreen
        ? { height: '100%' }
        : { height: 300 };

    return (
        <div style={containerStyle} className="w-full">
            <DataGrid
                rows={rows}
                columns={columns}
                initialState={{
                    pagination: { paginationModel: { pageSize: isFullscreen ? 100 : 25 } },
                    columns: { columnVisibilityModel: { address: true } },
                }}
                density={isFullscreen ? 'compact' : 'standard'}
                disableRowSelectionOnClick
            />
        </div>
    );
}