"use client";

import { useAppSelector } from "@/lib/hooks";
import { useLocale } from "@/lib/hooks/useLocale";
import { useGetFilterOptionsQuery, useGetProductivityByRegionQuery, useGetProductivityByAgeQuery, useGetProductivityByTenureQuery, useGetTonnageHarvestGroupEmployeeQuery, useGetTonnageHarvestByEmployeeOriginQuery, useGetTonnageHarvestByEmployeeSalaryQuery, useGetTargetTonnageQuery, useGetOrganizationAttendanceQuery, useGetCostQuery } from "@/services/api";
import { Filter } from "@/services/types";
import { useState } from "react";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, ComposedChart, Line, Legend } from "recharts";
import { PageLoader } from "@/components/Loader";

export default function ProductivityPage() {
    const { t } = useLocale();
    const filter = useAppSelector(state => state.filter.filter);
    const { data: filterOptions, isLoading: isLoadingFilterOptions, isFetching: isFetchingFilterOptions } = useGetFilterOptionsQuery(filter);
    const { data: productivityByRegion, isLoading: isLoadingProductivityByRegion, isFetching: isFetchingProductivityByRegion } = useGetProductivityByRegionQuery(filter);
    const { data: productivityByAge, isLoading: isLoadingProductivityByAge, isFetching: isFetchingProductivityByAge } = useGetProductivityByAgeQuery(filter);
    const { data: productivityByTenure, isLoading: isLoadingProductivityByTenure, isFetching: isFetchingProductivityByTenure } = useGetProductivityByTenureQuery(filter);
    const { data: tonnageHarvestGroupEmployee, isLoading: isLoadingTonnageHarvestGroupEmployee, isFetching: isFetchingTonnageHarvestGroupEmployee } = useGetTonnageHarvestGroupEmployeeQuery(filter);
    const { data: tonnageHarvestByEmployeeOrigin, isLoading: isLoadingTonnageHarvestByEmployeeOrigin, isFetching: isFetchingTonnageHarvestByEmployeeOrigin } = useGetTonnageHarvestByEmployeeOriginQuery(filter);
    const { data: tonnageHarvestByEmployeeSalary, isLoading: isLoadingTonnageHarvestByEmployeeSalary, isFetching: isFetchingTonnageHarvestByEmployeeSalary } = useGetTonnageHarvestByEmployeeSalaryQuery(filter);
    const { data: targetTonnage, isLoading: isLoadingTargetTonnage, isFetching: isFetchingTargetTonnage } = useGetTargetTonnageQuery(filter);
    const { data: attendanceData, isLoading: isLoadingAttendance, isFetching: isFetchingAttendance } = useGetOrganizationAttendanceQuery(filter);
    const { data: costData, isLoading: isLoadingCost, isFetching: isFetchingCost } = useGetCostQuery(filter);

    // Combine all loading states (both initial loading and refetching)
    const isLoading = isLoadingFilterOptions || isLoadingProductivityByRegion || 
                     isLoadingProductivityByAge || isLoadingProductivityByTenure || 
                     isLoadingTonnageHarvestGroupEmployee || isLoadingTonnageHarvestByEmployeeOrigin || 
                     isLoadingTonnageHarvestByEmployeeSalary || isLoadingTargetTonnage || isLoadingAttendance || isLoadingCost ||
                     isFetchingFilterOptions || isFetchingProductivityByRegion ||
                     isFetchingProductivityByAge || isFetchingProductivityByTenure ||
                     isFetchingTonnageHarvestGroupEmployee || isFetchingTonnageHarvestByEmployeeOrigin ||
                     isFetchingTonnageHarvestByEmployeeSalary || isFetchingTargetTonnage || isFetchingAttendance || isFetchingCost;

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

    // Calculate total tonnage for percentage calculations (convert kg to tons)
    const totalTonnageAge = productivityByAge?.reduce((sum, item) => sum + (item.tonnage / 1000), 0) || 0;
    const totalTonnageTenure = productivityByTenure?.reduce((sum, item) => sum + (item.tonnage / 1000), 0) || 0;

    // Calculate number of days between start_date and end_date
    const calculateDays = (startDate: string, endDate: string) => {
        const start = new Date(startDate);
        const end = new Date(endDate);
        const timeDiff = end.getTime() - start.getTime();
        const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1; // +1 to include both start and end dates
        return daysDiff;
    };

    const filterDays = filter.start_date && filter.end_date ? 
        calculateDays(filter.start_date, filter.end_date) : 1;

    // Prepare data for pie charts (convert kg to tons)
    const ageData = productivityByAge?.map(item => ({
        name: item.age_range,
        value: item.tonnage / 1000,
        percentage: totalTonnageAge > 0 ? (((item.tonnage / 1000) / totalTonnageAge) * 100).toFixed(1) : 0
    })) || [];

    const tenureData = productivityByTenure?.map(item => ({
        name: item.tenure_range,
        value: item.tonnage / 1000,
        percentage: totalTonnageTenure > 0 ? (((item.tonnage / 1000) / totalTonnageTenure) * 100).toFixed(1) : 0
    })) || [];

    // Prepare data for charts (convert kg to tons and calculate ratio per employee per day)
    const regionData = productivityByRegion?.map(item => ({
        ...item,
        tonnage: item.tonnage / 1000, // Convert kg to tons
        ratioPerEmployee: item.count > 0 && filterDays > 0 ? 
            ((item.tonnage / 1000) / item.count) / filterDays : 0
    })).sort((a, b) => b.ratioPerEmployee - a.ratioPerEmployee) || []; // Sort by ratio descending

    const ageBarData = productivityByAge?.map(item => ({
        ...item,
        tonnage: item.tonnage / 1000, // Convert kg to tons
        ratioPerEmployee: item.count > 0 && filterDays > 0 ? 
            ((item.tonnage / 1000) / item.count) / filterDays : 0
    })).sort((a, b) => b.ratioPerEmployee - a.ratioPerEmployee) || []; // Sort by ratio descending

    const tenureBarData = productivityByTenure?.map(item => ({
        ...item,
        tonnage: item.tonnage / 1000, // Convert kg to tons
        ratioPerEmployee: item.count > 0 && filterDays > 0 ? 
            ((item.tonnage / 1000) / item.count) / filterDays : 0
    })).sort((a, b) => b.ratioPerEmployee - a.ratioPerEmployee) || []; // Sort by ratio descending

    // Prepare data for tonnage harvest group employee pie chart
    const tonnageGroupData = tonnageHarvestGroupEmployee?.map(item => {
        // Parse tonnage range from kg format (e.g., "0.0 - 20499.9") and convert to tons
        const parseRange = (range: string) => {
            if (!range || range.endsWith("+")){
                return (Number(range.replace("+", "")) / 1000).toFixed(1) + "+ ton"
            }

            const parts = range.split(' - ');
            if (parts.length === 2) {
                const min = parseFloat(parts[0]) / 1000; // Convert kg to tons
                const max = parseFloat(parts[1]) / 1000; // Convert kg to tons
                return `${min.toFixed(1)} - ${max.toFixed(1)} ton`;
            }
            return range; // Fallback to original if parsing fails
        };

        const convertedRange = parseRange(item.tonnage_range);
        
        return {
            name: convertedRange,
            originalRange: item.tonnage_range,
            value: item.count,
            percentage: item.percentage,
            sortOrder: parseFloat(item.tonnage_range.split(' - ')[0]) // Use the minimum value for sorting
        };
    }).sort((a, b) => a.sortOrder - b.sortOrder) || []; // Sort by the minimum tonnage value

    // Prepare data for employee origin pie chart
    const totalTonnageOrigin = tonnageHarvestByEmployeeOrigin?.reduce((sum, item) => sum + (item.tonnage / 1000), 0) || 0;
    const employeeOriginData = tonnageHarvestByEmployeeOrigin?.map(item => ({
        name: item.category,
        value: item.tonnage / 1000, // Convert kg to tons
        count: item.count,
        percentage: totalTonnageOrigin > 0 ? (((item.tonnage / 1000) / totalTonnageOrigin) * 100).toFixed(1) : 0
    })).sort((a, b) => b.value - a.value) || []; // Sort by tonnage descending

    // Prepare data for employee salary pie chart
    const employeeSalaryData = tonnageHarvestByEmployeeSalary?.map(item => ({
        name: item.salary_range,
        value: item.tonnage / 1000, // Convert kg to tons
        count: item.count,
    })).sort((a, b) => b.value - a.value) || []; // Sort by tonnage descending

    // Calculate current total tonnage from region data (already in tons)
    const currentTotalTonnage = regionData.reduce((sum, item) => sum + item.tonnage, 0);
    
    // Get target tonnage (convert from kg to tons)
    const targetTonnageValue = targetTonnage ? targetTonnage.total / 1000 : 0;
    
    // Calculate percentage for visual representation
    const currentPercentage = targetTonnageValue > 0 ? (currentTotalTonnage / targetTonnageValue) * 100 : 0;

    // Calculate attendance data
    const totalWorkdays = attendanceData?.reduce((sum, item) => sum + item.workdays, 0) || 0;
    const totalAttendance = attendanceData?.reduce((sum, item) => sum + item.count, 0) || 0;
    
    // Calculate attendance percentage
    const attendancePercentage = totalWorkdays > 0 ? (totalAttendance / totalWorkdays) * 100 : 0;

    // Calculate cost per kilo by dividing total cost by total tonnage in kilograms
    const totalCost = costData?.reduce((sum, item) => sum + item.amount, 0) || 0;
    const costPerKilo = currentTotalTonnage > 0 ? totalCost / (currentTotalTonnage * 1000) : 0;

    // Colors for pie charts
    const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8', '#82CA9D', '#FFC658', '#8DD1E1'];

    return (
        <div className="grid grid-cols-12 gap-4">
            <div className="col-span-4 bg-white p-6 rounded-lg shadow">
                <div className="text-xl font-bold">{t('productivity.produktifitas')}</div>
                <div className="space-y-4">
                    <div className="mt-4">
                        <div className="text-lg text-gray-600 mb-1">{t('productivity.targetTonase')}</div>
                        <div className="relative w-full bg-blue-300 rounded-lg h-12 overflow-hidden">
                            {/* Target tonnage background (lighter) */}
                            <div className="absolute inset-0 flex items-center justify-center text-white font-medium text-sm">
                                {targetTonnageValue.toLocaleString('id-ID', { maximumFractionDigits: 0 })} {t('common.ton')}
                            </div>
                            {/* Current tonnage overlay (darker) */}
                            <div 
                                className="absolute top-0 left-0 h-full bg-blue-600 rounded-lg flex items-center justify-center text-white font-medium text-sm transition-all duration-300"
                                style={{ width: `${Math.min(currentPercentage, 100)}%` }}
                            >
                                {currentPercentage >= 30 && (
                                    <span>{currentTotalTonnage.toLocaleString('id-ID', { maximumFractionDigits: 0 })} {t('common.ton')}</span>
                                )}
                            </div>
                        </div>
                        <div className="text-xs text-gray-500 mt-1">
                             {t('productivity.current')}: {currentTotalTonnage.toLocaleString('id-ID', { maximumFractionDigits: 0 })} {t('common.ton')} | {t('productivity.target')}: {targetTonnageValue.toLocaleString('id-ID', { maximumFractionDigits: 0 })} {t('common.ton')} ({currentPercentage.toFixed(1)}% {t('productivity.achieved')})
                         </div>
                    </div>
                    
                    <div className="mt-4">
                        <div className="text-lg text-gray-600 mb-1">{t('productivity.rasioAbsensi')}</div>
                        <div className="relative w-full bg-teal-300 rounded-lg h-12 overflow-hidden">
                            {/* Total workdays background (lighter) */}
                            <div className="absolute inset-0 flex items-center justify-center text-white font-medium text-sm">
                                {totalWorkdays.toLocaleString('id-ID')} {t('productivity.hariKerja')}
                            </div>
                            {/* Attendance overlay (darker) */}
                            <div 
                                className="absolute top-0 left-0 h-full bg-teal-600 rounded-lg flex items-center justify-center text-white font-medium text-sm transition-all duration-300"
                                style={{ width: `${Math.min(attendancePercentage, 100)}%` }}
                            >
                                {attendancePercentage >= 30 && (
                                    <span>{totalAttendance.toLocaleString('id-ID')} {t('productivity.masuk')}</span>
                                )}
                            </div>
                        </div>
                        <div className="text-xs text-gray-500 mt-1">
                             {t('productivity.masuk')}: {totalAttendance.toLocaleString('id-ID')} {t('productivity.hari')} | {t('productivity.hariKerja')}: {totalWorkdays.toLocaleString('id-ID')} {t('productivity.hari')} ({attendancePercentage.toFixed(1)}% {t('productivity.kehadiran')})
                         </div>
                    </div>

                    <div className="mt-4">
                        <div className="text-lg text-gray-600 mb-1">{t('productivity.costPerKilo')}</div>
                        <div className="text-2xl font-bold text-green-600">Rp {costPerKilo?.toLocaleString('id-ID', { maximumFractionDigits: 0 }) || '0'}</div>
                    </div>
                </div>
            </div>
            
            <div className="col-span-8 bg-white p-6 rounded-lg shadow">
                <div className="text-xl font-bold">{t('productivity.analisaProduktifitas')}</div>
                <div className="h-96 mt-4">
                    {productivityByRegion && productivityByRegion.length > 0 ? (
                        <ResponsiveContainer width="100%" height="100%">
                            <ComposedChart data={regionData}>
                                <CartesianGrid strokeDasharray="3 3" />
                                <XAxis 
                                    dataKey="organization_code" 
                                    tick={{ fontSize: 12 }}
                                />
                                <YAxis yAxisId="tonnage" label={{ value: t('productivity.tonnage'), angle: -90, position: 'insideLeft' }} />
                                <YAxis yAxisId="count" orientation="right" label={{ value: t('productivity.employeeCount'), angle: 90, position: 'insideRight' }} />
                                <YAxis yAxisId="ratio" orientation="right" hide />
                                <Tooltip 
                                    formatter={(value, name) => {
                                        if (name === t('productivity.tonnage')) {
                                            return [`${Math.round(Number(value)).toLocaleString('id-ID')} ${t('common.ton')}`, t('productivity.tonnage')];
                                        }
                                        if (name === t('productivity.employeeCount')) {
                                            return [`${Number(value).toLocaleString('id-ID')} ${t('common.employees')}`, t('productivity.employeeCount')];
                                        }
                                        if (name === t('productivity.ratioPerEmployee')) {
                                            return [`${Number(value).toFixed(2)} ${t('productivity.tonPerEmployee')}`, t('productivity.ratioPerEmployee')];
                                        }
                                        return [value, name];
                                    }}
                                    labelFormatter={(label) => {
                                        const org = productivityByRegion.find(e => e.organization_code === label);
                                        return org?.organization_name || label;
                                    }}
                                />
                                <Legend />
                                <Bar yAxisId="tonnage" dataKey="tonnage" fill="#3B82F6" name={t('productivity.tonnage')} />
                                <Bar yAxisId="count" dataKey="count" fill="#10B981" name={t('productivity.employeeCount')} />
                                <Line yAxisId="ratio" type="monotone" dataKey="ratioPerEmployee" stroke="#F97316" strokeWidth={3} dot={{ fill: '#F97316', strokeWidth: 2, r: 4 }} name={t('productivity.ratioPerEmployee')} />
                            </ComposedChart>
                        </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 p-6 rounded-lg shadow">        
                <div className="text-xl font-bold">{t('productivity.outputTonPerTenagaKerja')}</div>
                {tonnageGroupData && tonnageGroupData.length > 0 ? (
                    <ResponsiveContainer width="100%" height={300}>
                        <PieChart>
                            <Legend 
                                verticalAlign="middle" 
                                align="right"
                                layout="vertical"
                                iconType="circle"
                                wrapperStyle={{ paddingLeft: '20px' }}
                                formatter={(value, entry) => {
                                    const totalEmployees = tonnageGroupData.reduce((sum, item) => sum + item.value, 0);
                                    const calculatedPercentage = totalEmployees > 0 ? ((entry.payload?.value / totalEmployees) * 100).toFixed(2) : 0;
                                    return (
                                        <span style={{ color: entry.color }} className="z-0">
                                            {value}: {entry.payload?.value?.toLocaleString('id-ID', { maximumFractionDigits: 2 })} {t('common.ton')} ({calculatedPercentage}%)
                                        </span>
                                    )
                                }}/>
                            <Pie
                                data={tonnageGroupData}
                                cx="50%"
                                cy="50%"
                                labelLine={false}
                                outerRadius={90}
                                innerRadius={60}
                                fill="#8884d8"
                                dataKey="value"
                            >
                                {tonnageGroupData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                ))}
                            </Pie>
                            <Tooltip 
                                formatter={(value, name, props) => [
                                    `${Number(value).toLocaleString('id-ID')} ${t('common.karyawan')}`,
                                    t('productivity.jumlahKaryawan')
                                ]}
                                labelFormatter={(label, payload) => {
                                    return `${t('productivity.rangeTonase')}: ${label}`;
                                }}
                                content={({ active, payload, label }) => {
                                    if (active && payload && payload.length) {
                                        const data = payload[0].payload;
                                        const totalEmployees = tonnageGroupData.reduce((sum, item) => sum + item.value, 0);
                                        const calculatedPercentage = totalEmployees > 0 ? ((data.value / totalEmployees) * 100).toFixed(2) : 0;
                                        return (
                                            <div className="bg-white p-3 border rounded shadow z-10">
                                                <p className="font-semibold">{`${t('productivity.rangeTonase')}: ${payload[0].name}`}</p>
                                                <p className="text-blue-600">{`${t('common.karyawan')}: ${data.value.toLocaleString('id-ID')} ${t('common.orang')}`}</p>
                                                <p className="text-gray-600">{`${t('productivity.persentase')}: ${calculatedPercentage}%`}</p>
                                            </div>
                                        );
                                    }
                                    return null;
                                }}
                            />
                            
                        </PieChart>
                    </ResponsiveContainer>
                ) : (
                    <div className="flex items-center justify-center h-64 text-gray-500">
                        {t('common.dataNotAvailable')}
                    </div>
                )}
            </div>

            <div className="col-span-4 bg-white p-6 rounded-lg shadow">        
                <div className="text-xl font-bold">{t('productivity.outputTonBerdasarkanGaji')}</div>
                <div className="h-80">
                    <ResponsiveContainer width="100%" height="100%">
                        <PieChart>
                            <Legend 
                                verticalAlign="middle" 
                                align="right" 
                                layout="vertical"
                                iconSize={12}
                                wrapperStyle={{ paddingLeft: '10px' }}
                                formatter={(value, entry) => {
                                    const totalEmployees = employeeSalaryData.reduce((sum, item) => sum + item.count, 0);
                                    const calculatedPercentage = totalEmployees > 0 ? (((entry.payload as any).count / totalEmployees) * 100).toFixed(2) : 0;
                                    return (
                                        <span style={{ color: entry.color }}>
                                            {value}: {entry.payload?.value?.toLocaleString('id-ID', { maximumFractionDigits: 2 })} {t('common.ton')} ({calculatedPercentage}%)
                                        </span>
                                    )
                                }}
                            />
                            <Pie
                                data={employeeSalaryData}
                                cx="50%"
                                cy="50%"
                                outerRadius={90}
                                innerRadius={60}
                                fill="#8884d8"
                                dataKey="value"
                                // label={({ name, percentage }) => `${name}: ${percentage}%`}
                                labelLine={false}
                            >
                                {employeeSalaryData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                ))}
                            </Pie>
                            <Tooltip 
                                formatter={(value, name) => [
                                    `${value.toLocaleString('id-ID')} ${t('common.ton')}`, 
                                    t('productivity.outputTonnage')
                                ]}
                                labelFormatter={(label) => `${t('productivity.gaji')}: ${label}`}
                                content={({ active, payload, label }) => {
                                    if (active && payload && payload.length) {
                                        const data = payload[0].payload;
                                        const totalEmployees = employeeSalaryData.reduce((sum, item) => sum + item.count, 0);
                                        const calculatedPercentage = totalEmployees > 0 ? ((data.count / totalEmployees) * 100).toFixed(2) : 0;
                                        return (
                                            <div className="bg-white p-3 border rounded shadow">
                                                <p className="font-semibold">{`${t('productivity.gaji')}: ${payload[0].name}`}</p>
                                                <p className="text-blue-600">{`${t('productivity.output')}: ${data.value.toLocaleString('id-ID')} ${t('common.ton')}`}</p>
                                                <p className="text-green-600">{`${t('common.karyawan')}: ${data.count.toLocaleString('id-ID')} ${t('common.orang')}`}</p>
                                                <p className="text-gray-600">{`${t('productivity.persentase')}: ${calculatedPercentage}%`}</p>
                                            </div>
                                        );
                                    }
                                    return null;
                                }}
                            />
                        </PieChart>
                    </ResponsiveContainer>
                </div>
            </div>

            <div className="col-span-4 bg-white p-6 rounded-lg shadow">        
                <div className="text-xl font-bold">{t('productivity.outputTonBerdasarkanDomisili')}</div>
                <div className="h-80">
                    <ResponsiveContainer width="100%" height="100%">
                        <PieChart>
                            <Pie
                                data={employeeOriginData}
                                cx="50%"
                                cy="50%"
                                outerRadius={"80%"}
                                innerRadius={"55%"}
                                fill="#8884d8"
                                dataKey="value"
                                label={false}
                            >
                                {employeeOriginData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                ))}
                            </Pie>
                            <Tooltip 
                                formatter={(value, name, props) => [
                                    `${props.payload?.count?.toLocaleString('id-ID') ?? 0} ${t('common.karyawan')}`,
                                    `${Math.round(Number(props.payload?.value ?? 0)).toLocaleString('id-ID')} ${t('common.ton')}`
                                ]}
                                labelFormatter={(label) => `${t('productivity.category')}: ${label}`}
                            />
                            <Legend 
                                verticalAlign="middle" 
                                align="right" 
                                layout="vertical"
                                iconType="circle"
                                wrapperStyle={{ paddingLeft: '20px' }}
                                formatter={(value, entry) => (
                                    <span style={{ color: entry.color }}>
                                        {value}: {Math.round(Number(entry.payload?.value ?? 0)).toLocaleString('id-ID')} {t('common.ton')}
                                    </span>
                                )}
                            />
                        </PieChart>
                    </ResponsiveContainer>
                </div>
            </div>

            <div className="col-span-6 bg-white p-6 rounded-lg shadow">
                <div className="text-xl font-bold">{t('productivity.rasioUsiaKaryawan')}</div>
                <div className="h-96">
                    <ResponsiveContainer width="100%" height="100%">
                        <ComposedChart data={ageBarData}>
                            <CartesianGrid strokeDasharray="3 3" />
                            <XAxis dataKey="age_range" />
                            <YAxis yAxisId="tonnage" label={{ value: t('productivity.tonnage'), angle: -90, position: 'insideLeft' }} />
                            <YAxis yAxisId="count" orientation="right" label={{ value: t('productivity.employeeCount'), angle: 90, position: 'insideRight' }} />
                            <YAxis yAxisId="ratio" orientation="right" hide />
                            <Tooltip 
                                formatter={(value, name) => {
                                    if (name === t('productivity.tonnage')) {
                                        return [`${Math.round(Number(value)).toLocaleString('id-ID')} ${t('common.ton')}`, t('productivity.tonnage')];
                                    }
                                    if (name === t('productivity.employeeCount')) {
                                        return [`${Number(value).toLocaleString('id-ID')} ${t('common.employees')}`, t('productivity.employeeCount')];
                                    }
                                    if (name === t('productivity.ratioPerEmployee')) {
                                        return [`${Number(value).toFixed(2)} ${t('productivity.tonPerEmployee')}`, t('productivity.ratioPerEmployee')];
                                    }
                                    return [value, name];
                                }}
                            />
                            <Legend />
                            <Bar yAxisId="tonnage" dataKey="tonnage" fill="#3B82F6" name={t('productivity.tonnage')} />
                            <Bar yAxisId="count" dataKey="count" fill="#10B981" name={t('productivity.employeeCount')} />
                            <Line yAxisId="ratio" type="monotone" dataKey="ratioPerEmployee" stroke="#F97316" strokeWidth={3} dot={{ fill: '#F97316', strokeWidth: 2, r: 4 }} name={t('productivity.ratioPerEmployee')} />
                        </ComposedChart>
                    </ResponsiveContainer>
                </div>
            </div>

            <div className="col-span-6 bg-white p-6 rounded-lg shadow">
                <div className="text-xl font-bold">{t('productivity.rasioMasaKerja')}</div>
                <div className="h-96">
                    <ResponsiveContainer width="100%" height="100%">
                        <ComposedChart data={tenureBarData}>
                            <CartesianGrid strokeDasharray="3 3" />
                            <XAxis dataKey="tenure_range" />
                            <YAxis yAxisId="tonnage" label={{ value: t('productivity.tonnage'), angle: -90, position: 'insideLeft' }} />
                            <YAxis yAxisId="count" orientation="right" label={{ value: t('productivity.employeeCount'), angle: 90, position: 'insideRight' }} />
                            <YAxis yAxisId="ratio" orientation="right" hide />
                            <Tooltip 
                                formatter={(value, name) => {
                                    if (name === t('productivity.tonnage')) {
                                        return [`${Math.round(Number(value)).toLocaleString('id-ID')} ${t('common.ton')}`, t('productivity.tonnage')];
                                    }
                                    if (name === t('productivity.employeeCount')) {
                                        return [`${Number(value).toLocaleString('id-ID')} ${t('common.employees')}`, t('productivity.employeeCount')];
                                    }
                                    if (name === t('productivity.ratioPerEmployee')) {
                                        return [`${Number(value).toFixed(2)} ${t('productivity.tonPerEmployee')}`, t('productivity.ratioPerEmployee')];
                                    }
                                    return [value, name];
                                }}
                            />
                            <Legend />
                            <Bar yAxisId="tonnage" dataKey="tonnage" fill="#3B82F6" name={t('productivity.tonnage')} />
                            <Bar yAxisId="count" dataKey="count" fill="#10B981" name={t('productivity.employeeCount')} />
                            <Line yAxisId="ratio" type="monotone" dataKey="ratioPerEmployee" stroke="#F97316" strokeWidth={3} dot={{ fill: '#F97316', strokeWidth: 2, r: 4 }} name={t('productivity.ratioPerEmployee')} />
                        </ComposedChart>
                    </ResponsiveContainer>
                </div>
            </div>
        </div>
    );
}