import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useNumberCards, useDashboardChart } from '../hooks/useApi';
import { useWorkOrders } from '../hooks/useWorkOrder';
import { useAssetMaintenanceLogs } from '../hooks/useAssetMaintenance';
import { useTranslation } from 'react-i18next';
import { FaShoppingCart, FaChartLine, FaBoxes, FaTools, FaCheckCircle, FaClock, FaExclamationTriangle, FaArrowUp, FaArrowDown, FaTimes, FaArchive, FaExternalLinkAlt, FaStar } from 'react-icons/fa';
import LinkField from '../components/LinkField';
import ChartDetailModal from '../components/ChartDetailModal';
import AssetUpDownCard from '../components/AssetUpDownCard';
import AssetStatusReportModal from '../components/AssetStatusReportModal';
import WorkOrderStatusReportModal from '../components/WorkOrderStatusReportModal';
import RepairStatusCompletionCard from '../components/RepairStatusCompletionCard';
import TechnicianWorkedChartCard from '../components/TechnicianWorkedChartCard';
import TechnicianHoursChartCard from '../components/TechnicianHoursChartCard';
import TechnicianWorkOrderSummaryReportModal from '../components/TechnicianWorkOrderSummaryReportModal';
import TechnicianWorkingHoursReportModal from '../components/TechnicianWorkingHoursReportModal';
import WoFeedbackReportModal from '../components/WoFeedbackReportModal';
import useUserDashboardFilters from '../hooks/useUserDashboardFilters';
import { useUserPermissions } from '../hooks/useUserPermissions';
import apiService from '../services/apiService';
import {
  fetchAssigneesStatusChart,
  type AssigneesStatusChartData,
} from '../services/assigneesStatusService';
import {
  fetchTechnicianWorkSummaryChart,
  type TechnicianWorkSummaryChartData,
} from '../services/technicianWorkSummaryService';
import {
  fetchTechnicianWorkingHoursChart,
  type TechnicianWorkingHoursChartData,
} from '../services/technicianWorkingHoursService';
import { fetchWoFeedbackSummary } from '../services/woFeedbackReportService';
import { applyWoFeedbackChartColors, getWoFeedbackRatingColor } from '../utils/woFeedbackChartUtils';
import { fetchAssetsForStatusModal } from '../services/assetDeviceStatusService';
import type { PieChartData } from '../components/PieChart';
import type { CompletionByTypeData } from '../utils/chartLabelUtils';
import { getRepairCompletionRate, getCombinedCompletedCount } from '../utils/chartLabelUtils';
import {
  buildDashboardReportFilters,
  buildMaintenanceLogDashboardFilters,
  buildWorkOrderDashboardFilters,
  buildMobileTeamSiteFilters,
  isSiteEnabledHospital,
} from '../utils/hospitalUtils';
import { buildWoUrl } from '../utils/buildWoUrl';
import { buildAssetUrl } from '../utils/buildAssetUrl';
import {
  compactFilterFieldWrapClass,
  compactFilterInputClass,
  compactFilterLabelClass,
} from '../utils/reportModalStyles';

const UP_TIME_COLOR = '#22C55E';
const DOWN_TIME_COLOR = '#EF4444';

const parseHours = (value: unknown): number => {
  if (value == null || value === '') return 0;
  if (typeof value === 'number') {
    return Number.isFinite(value) && value >= 0 ? value : 0;
  }
  if (typeof value === 'string') {
    if (value.includes(':')) {
      const parts = value.split(':').map(p => Number(p) || 0);
      if (parts.length === 3) return parts[0] + parts[1] / 60 + parts[2] / 3600;
      if (parts.length === 2) return parts[0] + parts[1] / 60;
    }
    const n = Number(value);
    return Number.isFinite(n) && n >= 0 ? n : 0;
  }
  return 0;
};

const isPieChartRenderable = (data: unknown): boolean => {
  if (!data || typeof data !== 'object' || 'error' in (data as object)) return false;
  const chart = data as { labels?: string[]; datasets?: { values?: unknown[] }[] };
  const values = chart.datasets?.[0]?.values;
  if (!Array.isArray(values) || values.length === 0) return false;
  return values.some(v => parseHours(v) > 0);
};

const ModernDashboard: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [dashFromDate, setDashFromDate] = useState('');
  const [dashToDate, setDashToDate] = useState('');
  const {
    filterHospital,
    filterSiteName,
    hospitalLocked,
    siteLocked,
    handleHospitalChange,
    handleSiteChange,
    hospitalLinkFilters,
  } = useUserDashboardFilters();
  const {
    isAdmin: isWoAdmin,
    restrictions: woRestrictions,
    permissionFilters: woPermissionFilters,
  } = useUserPermissions('Work_Order');

  const permittedIssueTypes = useMemo(() => {
    const fromRestriction =
      woRestrictions['Issue Type']?.values ||
      woRestrictions.work_order_type?.values ||
      [];
    if (fromRestriction.length) return fromRestriction;

    const permFilter = woPermissionFilters.work_order_type;
    if (Array.isArray(permFilter) && permFilter[0] === 'in' && Array.isArray(permFilter[1])) {
      return permFilter[1] as string[];
    }
    if (typeof permFilter === 'string' && permFilter) return [permFilter];
    return [];
  }, [woRestrictions, woPermissionFilters]);

  const selectedIssueType = useMemo(
    () => (!isWoAdmin && permittedIssueTypes.length === 1 ? permittedIssueTypes[0] : ''),
    [isWoAdmin, permittedIssueTypes]
  );

  const mobileTeamSiteFilters = useMemo(
    () => buildMobileTeamSiteFilters(filterHospital, siteLocked ? filterSiteName : undefined),
    [filterHospital, filterSiteName, siteLocked]
  );

  const dashboardReportFilters = useMemo(
    () => buildDashboardReportFilters(filterHospital, filterSiteName, dashFromDate, dashToDate),
    [filterHospital, filterSiteName, dashFromDate, dashToDate]
  );
  const workOrderFilters = useMemo(
    () => buildWorkOrderDashboardFilters(filterHospital, filterSiteName),
    [filterHospital, filterSiteName]
  );
  const maintenanceLogFilters = useMemo(
    () => buildMaintenanceLogDashboardFilters(filterHospital, filterSiteName),
    [filterHospital, filterSiteName]
  );
  const showSiteFilter = isSiteEnabledHospital(filterHospital);

  const { data: numberCards, loading: cardsLoading } = useNumberCards(dashboardReportFilters);
  const { workOrders } = useWorkOrders(workOrderFilters, 1000, 0);
  const { logs: maintenanceLogs } = useAssetMaintenanceLogs(maintenanceLogFilters, 1000, 0);
  
  const [workOrderChartData, setWorkOrderChartData] = useState<any>(null);
  const [completionByTypeChartData, setCompletionByTypeChartData] = useState<CompletionByTypeData | null>(null);
  const [workOrderGroupedChartData, setWorkOrderGroupedChartData] = useState<any>(null);
  const [typeStatusChartData, setTypeStatusChartData] = useState<any>(null);
  const [showWorkOrderStatusReport, setShowWorkOrderStatusReport] = useState(false);
  const [assigneesStatusChartData, setAssigneesStatusChartData] = useState<AssigneesStatusChartData | null>(null);
  const [assigneesStatusLoading, setAssigneesStatusLoading] = useState(false);
  const [technicianWorkedData, setTechnicianWorkedData] = useState<TechnicianWorkSummaryChartData | null>(null);
  const [technicianWorkedLoading, setTechnicianWorkedLoading] = useState(false);
  const [showTechnicianWorkOrderReport, setShowTechnicianWorkOrderReport] = useState(false);
  const [technicianHoursData, setTechnicianHoursData] = useState<TechnicianWorkingHoursChartData | null>(null);
  const [technicianHoursLoading, setTechnicianHoursLoading] = useState(false);
  const [showTechnicianHoursReport, setShowTechnicianHoursReport] = useState(false);
  const [showWoFeedbackReport, setShowWoFeedbackReport] = useState(false);
  const [woFeedbackChartData, setWoFeedbackChartData] = useState<any>(null);
  const [woFeedbackChartLoading, setWoFeedbackChartLoading] = useState(false);
  const [assetDeviceStatusChartData, setAssetDeviceStatusChartData] = useState<PieChartData | null>(null);
  const [totalAssetsCount, setTotalAssetsCount] = useState(0);
  const [showAssetReport, setShowAssetReport] = useState(false);
  const [assetMetricsLoading, setAssetMetricsLoading] = useState(false);
  const [chartDetail, setChartDetail] = useState<{
    title: string;
    data: any;
    redirectContext?: 'wo_status' | 'wo_type' | 'assignees_status' | null;
  } | null>(null);
  const [woStatusLoading, setWoStatusLoading] = useState(false);

  const navigateToAssets = useCallback(() => {
    navigate(
      buildAssetUrl(
        {},
        dashboardReportFilters.from_date,
        dashboardReportFilters.to_date,
        dashboardReportFilters
      )
    );
  }, [navigate, dashboardReportFilters]);

  const navigateToWorkOrders = useCallback(
    (status?: string) => {
      navigate(
        buildWoUrl(
          {
            status,
            work_order_type: selectedIssueType || undefined,
          },
          dashboardReportFilters.from_date,
          dashboardReportFilters.to_date,
          dashboardReportFilters
        )
      );
    },
    [navigate, dashboardReportFilters, selectedIssueType]
  );
  
  const [realWorkOrderCounts, setRealWorkOrderCounts] = useState({
    open: 0,
    inProgress: 0,
    completed: 0,
    completedCombined: 0,
    pendingReview: 0,
    rejected: 0,
    closed: 0,
    total: 0,
  });

  const repairCompletedTotal = useMemo(() => {
    const completed = realWorkOrderCounts.completed || numberCards?.work_orders_completed || 0;
    const closed = realWorkOrderCounts.closed || numberCards?.work_orders_closed || 0;
    return getCombinedCompletedCount(completed, closed);
  }, [realWorkOrderCounts, numberCards]);

  const [insights, setInsights] = useState({
    assetUptime: 0,
    avgResponseTime: 0,
    maintenanceEfficiency: 0,
    overdueTasks: 0,
    plannedMaintenance: 0
  });

  // Fetch all charts
  const { data: workOrderChart } = useDashboardChart('Work Order Status Chart', dashboardReportFilters);
  // const { data: ppmStatusChart } = useDashboardChart('PPM Status');

  // Generate grouped Work Order chart by type + status
  useEffect(() => {
    if (workOrders && workOrders.length > 0) {
      const groupedData: Record<string, Record<string, number>> = {};
      const allStatuses = new Set<string>();
      
      workOrders.forEach(wo => {
        const workOrderType = wo.work_order_type || 'null';
        const repairStatus = wo.repair_status || 'Unknown';

        allStatuses.add(repairStatus);

        if (!groupedData[workOrderType]) {
          groupedData[workOrderType] = {};
        }

        if (!groupedData[workOrderType][repairStatus]) {
          groupedData[workOrderType][repairStatus] = 0;
        }

        groupedData[workOrderType][repairStatus]++;
      });

      const workOrderTypeLabels = Object.keys(groupedData);

      const statusOrder = ['Open', 'Work In Progress', 'Pending Review', 'Completed', 'Closed', 'Cancelled'];
      const statusList = Array.from(allStatuses).sort((a, b) => {
        const aIndex = statusOrder.indexOf(a);
        const bIndex = statusOrder.indexOf(b);
        if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;
        if (aIndex !== -1) return -1;
        if (bIndex !== -1) return 1;
        return a.localeCompare(b);
      });
      
      const datasets = statusList.map(status => {
        const values = workOrderTypeLabels.map(type => groupedData[type][status] || 0);
        return {
          name: status,
          values: values
        };
      });

      setWorkOrderGroupedChartData({
        labels: workOrderTypeLabels,
        datasets: datasets,
        type: 'Bar'
      });
    } else {
      setWorkOrderGroupedChartData(null);
    }
  }, [workOrders]);

  useEffect(() => {
    let cancelled = false;

    const fetchWorkOrderMetrics = async () => {
      setWoStatusLoading(true);
      try {
        const filters: Record<string, string> = {};
        if (filterHospital) filters.company = filterHospital;
        if (filterSiteName && isSiteEnabledHospital(filterHospital)) {
          filters.site_name = filterSiteName;
        }
        if (selectedIssueType) {
          filters.work_order_type = selectedIssueType;
        }
        if (dashFromDate) filters.from_date = dashFromDate;
        if (dashToDate) filters.to_date = dashToDate;

        const data = await apiService.getDashboardWorkOrderMetrics(filters);
        if (cancelled) return;

        setWorkOrderChartData(data.work_order_chart);
        setTypeStatusChartData(data.type_status_chart || null);
        setCompletionByTypeChartData(data.completion_by_type || null);
        setRealWorkOrderCounts({
          open: data.counts.open || 0,
          inProgress: data.counts.inProgress || 0,
          completed: data.counts.completed || 0,
          completedCombined: getCombinedCompletedCount(
            data.counts.completed,
            data.counts.closed
          ),
          pendingReview: data.counts.pendingReview || 0,
          rejected: data.counts.rejected || 0,
          closed: data.counts.closed || 0,
          total: data.counts.total || 0,
        });
      } catch (err) {
        console.error('Failed to load work order metrics:', err);
        if (!cancelled) {
          setWorkOrderChartData(null);
          setTypeStatusChartData(null);
          setCompletionByTypeChartData(null);
          setRealWorkOrderCounts({
            open: 0,
            inProgress: 0,
            completed: 0,
            completedCombined: 0,
            pendingReview: 0,
            rejected: 0,
            closed: 0,
            total: 0,
          });
        }
      } finally {
        if (!cancelled) {
          setWoStatusLoading(false);
        }
      }
    };

    fetchWorkOrderMetrics();
    return () => {
      cancelled = true;
    };
  }, [filterHospital, filterSiteName, selectedIssueType, dashFromDate, dashToDate]);

  useEffect(() => {
    let cancelled = false;

    const fetchTechnicianWorked = async () => {
      setTechnicianWorkedLoading(true);
      try {
        const filters: Record<string, string> = {};
        if (dashFromDate) filters.from_date = dashFromDate;
        if (dashToDate) filters.to_date = dashToDate;
        if (filterHospital) filters.company = filterHospital;
        if (filterSiteName && isSiteEnabledHospital(filterHospital)) {
          filters.site_name = filterSiteName;
        }
        if (selectedIssueType) {
          filters.work_order_type = selectedIssueType;
        }

        const chartData = await fetchTechnicianWorkSummaryChart(filters);
        if (!cancelled) {
          setTechnicianWorkedData(chartData);
        }
      } catch (err) {
        console.error('Failed to load technician work summary:', err);
        if (!cancelled) {
          setTechnicianWorkedData(null);
        }
      } finally {
        if (!cancelled) {
          setTechnicianWorkedLoading(false);
        }
      }
    };

    fetchTechnicianWorked();
    return () => {
      cancelled = true;
    };
  }, [filterHospital, filterSiteName, dashFromDate, dashToDate, selectedIssueType]);

  useEffect(() => {
    let cancelled = false;

    const fetchTechnicianHours = async () => {
      setTechnicianHoursLoading(true);
      try {
        const filters: Record<string, string> = {};
        if (dashFromDate) filters.from_date = dashFromDate;
        if (dashToDate) filters.to_date = dashToDate;
        if (filterHospital) filters.company = filterHospital;
        if (filterSiteName && isSiteEnabledHospital(filterHospital)) {
          filters.site_name = filterSiteName;
        }
        if (selectedIssueType) {
          filters.work_order_type = selectedIssueType;
        }

        const chartData = await fetchTechnicianWorkingHoursChart(filters);
        if (!cancelled) {
          setTechnicianHoursData(chartData);
        }
      } catch (err) {
        console.error('Failed to load technician working hours:', err);
        if (!cancelled) {
          setTechnicianHoursData(null);
        }
      } finally {
        if (!cancelled) {
          setTechnicianHoursLoading(false);
        }
      }
    };

    fetchTechnicianHours();
    return () => {
      cancelled = true;
    };
  }, [filterHospital, filterSiteName, dashFromDate, dashToDate, selectedIssueType]);

  // Fetch asset device status summary for UP & Down pie chart
  useEffect(() => {
    let cancelled = false;

    const fetchAssetDeviceStatus = async () => {
      setAssetMetricsLoading(true);
      try {
        const filters: Record<string, string> = {};
        if (filterHospital) filters.company = filterHospital;
        if (filterSiteName) filters.site_name = filterSiteName;
        if (dashFromDate) filters.from_date = dashFromDate;
        if (dashToDate) filters.to_date = dashToDate;

        const data = await apiService.getAssetDeviceStatusSummary(filters);
        if (cancelled) return;

        setAssetDeviceStatusChartData(data.chart || null);
        setTotalAssetsCount(data.total_assets || 0);
      } catch (err) {
        console.error('Failed to load asset device status summary:', err);
        if (!cancelled) {
          setAssetDeviceStatusChartData(null);
          setTotalAssetsCount(0);
        }
      } finally {
        if (!cancelled) setAssetMetricsLoading(false);
      }
    };

    fetchAssetDeviceStatus();
    return () => { cancelled = true; };
  }, [filterHospital, filterSiteName, dashFromDate, dashToDate]);

  useEffect(() => {
    if (selectedIssueType) {
      setWoFeedbackChartData(null);
      return;
    }

    let cancelled = false;

    const fetchWoFeedbackChart = async () => {
      setWoFeedbackChartLoading(true);
      try {
        const chart = await fetchWoFeedbackSummary(dashboardReportFilters);
        if (!cancelled) {
          setWoFeedbackChartData(applyWoFeedbackChartColors(chart ?? {}));
        }
      } catch (err) {
        console.error('Failed to load WO feedback summary:', err);
        if (!cancelled) {
          setWoFeedbackChartData(null);
        }
      } finally {
        if (!cancelled) {
          setWoFeedbackChartLoading(false);
        }
      }
    };

    fetchWoFeedbackChart();
    return () => {
      cancelled = true;
    };
  }, [selectedIssueType, dashboardReportFilters]);

  const refreshAssetStatusReport = useCallback(async (filters: Record<string, string>) => {
    const [summaryData, assets] = await Promise.all([
      apiService.getAssetDeviceStatusSummary(filters),
      fetchAssetsForStatusModal(filters),
    ]);
    return {
      chart: summaryData.chart || null,
      total_assets: summaryData.total_assets || 0,
      assets,
    };
  }, []);

  const refreshWorkOrderStatusReport = useCallback(async (filters: Record<string, string>) => {
    const data = await apiService.getDashboardWorkOrderMetrics(filters);
    return {
      chart: data.type_status_chart || null,
      total: data.counts?.total || 0,
    };
  }, []);

  // Generate maintenance charts and insights
  useEffect(() => {
    if (maintenanceLogs && maintenanceLogs.length > 0) {
      let completedMaintenance = 0;
      let plannedMaintenance = 0;
      let overdueMaintenance = 0;
      const today = new Date();
      
      maintenanceLogs.forEach(log => {
        if (log.maintenance_status?.toLowerCase() === 'completed') completedMaintenance++;
        if (log.maintenance_status?.toLowerCase() === 'planned') plannedMaintenance++;
        
        if (log.due_date && new Date(log.due_date) < today && log.maintenance_status !== 'Completed') {
          overdueMaintenance++;
        }
      });

      const maintenanceEfficiency = maintenanceLogs.length > 0 
        ? ((completedMaintenance / maintenanceLogs.length) * 100)
        : 0;

      setInsights(prev => ({
        ...prev,
        maintenanceEfficiency,
        overdueTasks: overdueMaintenance,
        plannedMaintenance
      }));
    }
  }, [maintenanceLogs]);

  useEffect(() => {
    let cancelled = false;

    const fetchAssigneesStatus = async () => {
      setAssigneesStatusLoading(true);
      try {
        const filters: Record<string, string> = {};
        if (dashFromDate) filters.from_date = dashFromDate;
        if (dashToDate) filters.to_date = dashToDate;
        if (filterHospital) filters.company = filterHospital;
        if (filterSiteName && isSiteEnabledHospital(filterHospital)) {
          filters.site_name = filterSiteName;
        }

        const chartData = await fetchAssigneesStatusChart(filters);
        if (!cancelled) {
          setAssigneesStatusChartData(chartData);
        }
      } catch (err) {
        console.error('Failed to load assignees status chart:', err);
        if (!cancelled) {
          setAssigneesStatusChartData(null);
        }
      } finally {
        if (!cancelled) {
          setAssigneesStatusLoading(false);
        }
      }
    };

    fetchAssigneesStatus();
    return () => {
      cancelled = true;
    };
  }, [filterHospital, filterSiteName, dashFromDate, dashToDate]);

  // Calculate asset uptime and response time from work orders
  useEffect(() => {
    if (workOrders && workOrders.length > 0) {
      let totalResponseHours = 0;
      let responseCount = 0;
      
      workOrders.forEach(wo => {
        // Calculate response time if we have creation and first_responded_on
        if (wo.creation && wo.first_responded_on) {
          const created = new Date(wo.creation);
          const responded = new Date(wo.first_responded_on);
          const hours = (responded.getTime() - created.getTime()) / (1000 * 60 * 60);
          if (hours >= 0) {
            totalResponseHours += hours;
            responseCount++;
          }
        }
      });

      const avgResponseTime = responseCount > 0 ? totalResponseHours / responseCount : 0;

      // Calculate uptime (assets operational vs under maintenance)
      const operationalCount = workOrders.filter(wo => 
        wo.repair_status?.toLowerCase() === 'completed'
      ).length;
      const assetUptime = workOrders.length > 0 
        ? ((operationalCount / workOrders.length) * 100) 
        : 0;

      setInsights(prev => ({
        ...prev,
        assetUptime,
        avgResponseTime
      }));
    }
  }, [workOrders]);

  const resolvedWorkOrderChartData = useMemo(
    () => workOrderChartData,
    [workOrderChartData]
  );

  const resolvedWorkOrderGroupedChartData = useMemo(
    () => typeStatusChartData || workOrderGroupedChartData || workOrderChart,
    [typeStatusChartData, workOrderGroupedChartData, workOrderChart]
  );

  if (cardsLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto mb-4"></div>
          <div className="text-gray-600 dark:text-gray-400">{t('dashboard.loading')}</div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen w-full min-w-0 overflow-x-hidden bg-gray-50 dark:bg-gray-900 p-3 sm:p-6">
      <div className="max-w-[1600px] mx-auto">

        {/* Hospital / Site / Date filters */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 px-4 py-3 mb-4">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 items-end w-full min-w-0">
            <div className="relative z-[60]">
              <LinkField
                label={t('commonFields.hospital', { defaultValue: 'Hospital' })}
                doctype="Company"
                value={filterHospital}
                onChange={handleHospitalChange}
                placeholder={t('dashboard.allHospitals', { defaultValue: 'All Hospitals' })}
                disabled={hospitalLocked}
                compact
                filters={hospitalLinkFilters}
              />
              {filterHospital && !hospitalLocked && (
                <button
                  type="button"
                  onClick={() => handleHospitalChange('')}
                  className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                >
                  <FaTimes size={10} />
                </button>
              )}
            </div>

            {showSiteFilter && (
              <div className="relative z-[55]">
                <LinkField
                  label={t('commonFields.siteName', { defaultValue: 'Site Name' })}
                  doctype="Mobile Team Site"
                  value={filterSiteName}
                  onChange={handleSiteChange}
                  placeholder={t('dashboard.allSites', { defaultValue: 'All Sites' })}
                  disabled={siteLocked}
                  compact
                  filters={mobileTeamSiteFilters}
                />
                {filterSiteName && !siteLocked && (
                  <button
                    type="button"
                    onClick={() => handleSiteChange('')}
                    className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                  >
                    <FaTimes size={10} />
                  </button>
                )}
              </div>
            )}

            <div className={compactFilterFieldWrapClass}>
              <label className={compactFilterLabelClass}>
                {t('dashboard.fromDate', { defaultValue: 'From Date' })}
              </label>
              <input
                type="date"
                value={dashFromDate}
                onChange={e => setDashFromDate(e.target.value)}
                className={compactFilterInputClass}
              />
            </div>

            <div className={compactFilterFieldWrapClass}>
              <label className={compactFilterLabelClass}>
                {t('dashboard.toDate', { defaultValue: 'To Date' })}
              </label>
              <input
                type="date"
                value={dashToDate}
                onChange={e => setDashToDate(e.target.value)}
                className={compactFilterInputClass}
              />
            </div>
          </div>
        </div>

        {/* Top Section: Side-by-Side Layout */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-3 mb-6">
          
          {/* LEFT SIDE: 7 columns - Two cards stacked */}
          <div className="lg:col-span-7 col-span-12 space-y-2">
            {/* TOP: All 6 Stats in ONE Container */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 px-4 py-4">
              {/* Inside: 12-column grid, each stat takes 2 columns */}
              <div className="grid grid-cols-12 gap-0 w-full">
                {/* Each box takes col-span-2 (6 boxes × 2 = 12 columns) */}
                <div className="col-span-2">
                  <StatCard
                    icon={<FaBoxes className="text-indigo-600" />}
                    value={numberCards?.total_assets ?? 0}
                    label={t('dashboard.totalAssets')}
                    bgColor="bg-indigo-50 dark:bg-indigo-900/20"
                    onClick={navigateToAssets}
                  />
                </div>
                
                <div className="col-span-2">
                  <StatCard
                    icon={<FaShoppingCart className="text-purple-600" />}
                    value={realWorkOrderCounts.open || (numberCards?.work_orders_open ?? 0)}
                    label={t('dashboard.openWorkOrders')}
                    bgColor="bg-purple-50 dark:bg-purple-900/20"
                    onClick={() => navigateToWorkOrders('Open')}
                  />
                </div>
                
                <div className="col-span-2">
                  <StatCard
                    icon={<FaClock className="text-blue-600" />}
                    value={realWorkOrderCounts.inProgress || (numberCards?.work_orders_in_progress ?? 0)}
                    label={t('dashboard.workOrdersInProgress')}
                    bgColor="bg-blue-50 dark:bg-blue-900/20"
                    onClick={() => navigateToWorkOrders('Work In Progress')}
                  />
                </div>
                
                <div className="col-span-2">
                  <StatCard
                    icon={<FaCheckCircle className="text-pink-600" />}
                    value={realWorkOrderCounts.completed || (numberCards?.work_orders_completed ?? 0)}
                    label={t('dashboard.completedWorkOrders')}
                    bgColor="bg-pink-50 dark:bg-pink-900/20"
                    onClick={() => navigateToWorkOrders('Completed')}
                  />
                </div>

                <div className="col-span-2">
                  <StatCard
                    icon={<FaArchive className="text-cyan-600" />}
                    value={realWorkOrderCounts.closed || (numberCards?.work_orders_closed ?? 0)}
                    label={t('dashboard.closedWorkOrders')}
                    bgColor="bg-cyan-50 dark:bg-cyan-900/20"
                    onClick={() => navigateToWorkOrders('Closed')}
                  />
                </div>
                
                <div className="col-span-2">
                  <StatCard
                    icon={<FaChartLine className="text-purple-600" />}
                    value={realWorkOrderCounts.total}
                    label={t('dashboard.totalWorkOrders')}
                    bgColor="bg-purple-50 dark:bg-purple-900/20"
                    onClick={() => navigateToWorkOrders()}
                  />
                </div>
              </div>
            </div>

            {/* BOTTOM: Overall Completion Rate Card */}
            <RepairStatusCompletionCard
              loading={woStatusLoading}
              totalWorkOrders={realWorkOrderCounts.total}
              completedWorkOrders={repairCompletedTotal}
              inProgressWorkOrders={realWorkOrderCounts.inProgress}
              rejectedWorkOrders={realWorkOrderCounts.rejected}
              byTypeChartData={completionByTypeChartData}
              onOpenReport={() => {
                const rates = completionByTypeChartData?.rates || [];
                setChartDetail({
                  title: t('dashboard.overallCompletionByDepartment', {
                    defaultValue: 'Overall Completion Rate by Department',
                  }),
                  redirectContext: 'wo_type',
                  data: {
                    labels: rates.map(rate => rate.type),
                    datasets: [
                      {
                        name: 'Completion Rate (%)',
                        values: rates.map(rate => getRepairCompletionRate(rate)),
                      },
                      {
                        name: 'Completed WOs',
                        values: rates.map(
                          rate => rate.completedCombined ?? (rate.completed || 0) + (rate.closed || 0)
                        ),
                      },
                      {
                        name: 'In Progress',
                        values: rates.map(rate => rate.inProgress || 0),
                      },
                      {
                        name: 'Rejected',
                        values: rates.map(rate => rate.rejected || 0),
                      },
                      {
                        name: 'Total WOs',
                        values: rates.map(rate => rate.total || 0),
                      },
                    ],
                    hideFooterTotal: true,
                  },
                });
              }}
            />
          </div>

          {/* RIGHT SIDE: Asset Maintenance Assignees Status Count Chart (5 columns - Full height) */}
          <div className="lg:col-span-5 col-span-12">
            <GroupedChartCard
              title={t('dashboard.assigneesStatus', {
                defaultValue: 'Asset Maintenance Assignees Status Count',
              })}
              data={assigneesStatusChartData}
              loading={assigneesStatusLoading}
              onOpenReport={() =>
                setChartDetail({
                  title: t('dashboard.assigneesStatus', {
                    defaultValue: 'Asset Maintenance Assignees Status Count',
                  }),
                  data: assigneesStatusChartData,
                  redirectContext: 'assignees_status',
                })
              }
            />
          </div>
        </div>

        {/* Insights Row - Key Metrics (All Dynamic Data) */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          <InsightCard
            icon={<FaCheckCircle className="text-green-500" />}
            title={t('dashboard.assetUptime')}
            value={`${insights.assetUptime.toFixed(1)}%`}
            trend={insights.assetUptime >= 90 ? "Excellent" : insights.assetUptime >= 75 ? "Good" : "Needs Attention"}
            trendUp={insights.assetUptime >= 75}
            bgColor="bg-green-50 dark:bg-green-900/20"
          />
          
          <InsightCard
            icon={<FaClock className="text-blue-500" />}
            title={t('dashboard.avgResponseTime')}
            value={insights.avgResponseTime > 0 ? `${insights.avgResponseTime.toFixed(1)} hrs` : 'N/A'}
            trend={insights.avgResponseTime > 0 && insights.avgResponseTime < 4 ? "Fast Response" : "Monitor"}
            trendUp={insights.avgResponseTime > 0 && insights.avgResponseTime < 4}
            bgColor="bg-blue-50 dark:bg-blue-900/20"
          />
          
          <InsightCard
            icon={<FaTools className="text-orange-500" />}
            title={t('dashboard.maintenanceEfficiency')}
            value={`${insights.maintenanceEfficiency.toFixed(1)}%`}
            trend={insights.maintenanceEfficiency >= 70 ? "On Track" : "Needs Attention"}
            trendUp={insights.maintenanceEfficiency >= 70}
            bgColor="bg-orange-50 dark:bg-orange-900/20"
          />
          
          <InsightCard
            icon={<FaExclamationTriangle className="text-red-500" />}
            title={t('dashboard.overdueMaintenance')}
            value={insights.overdueTasks}
            trend={insights.overdueTasks === 0 ? "All Clear" : insights.overdueTasks <= 3 ? "Low" : "High Priority"}
            trendUp={insights.overdueTasks <= 3}
            bgColor="bg-red-50 dark:bg-red-900/20"
          />
        </div>

        {/* Asset UP & Down + Work Order Status Distribution */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
          <AssetUpDownCard
            title={t('dashboard.assetUpDown', { defaultValue: 'Asset UP & Down' })}
            data={assetDeviceStatusChartData}
            loading={assetMetricsLoading}
            totalAssets={totalAssetsCount}
            onOpenReport={() => setShowAssetReport(true)}
          />

          <DepartmentSalesCard
            title={t('dashboard.workOrderStatusDistribution', { defaultValue: 'Work Order Status Distribution' })}
            data={resolvedWorkOrderChartData}
            totalWorkOrders={realWorkOrderCounts.total}
            completedWorkOrders={realWorkOrderCounts.completed}
            loading={woStatusLoading}
            onOpenReport={() =>
              setChartDetail({
                title: t('dashboard.workOrderStatusDistribution', {
                  defaultValue: 'Work Order Status Distribution',
                }),
                data: resolvedWorkOrderChartData,
                redirectContext: 'wo_status',
              })
            }
          />
        </div>

        {/* Additional Charts Section */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 ">
          {/* Work Order Status Chart */}
          <GroupedChartCard 
            title={t('dashboard.workOrderStatus')} 
            data={resolvedWorkOrderGroupedChartData}
            loading={woStatusLoading}
            onOpenReport={() => setShowWorkOrderStatusReport(true)}
          />

          <TechnicianWorkedChartCard
            title={t('dashboard.techniciansWorked', { defaultValue: 'Technicians Work Summary' })}
            data={technicianWorkedData}
            loading={technicianWorkedLoading}
            onOpenReport={() => setShowTechnicianWorkOrderReport(true)}
          />

          <TechnicianHoursChartCard
            title={t('dashboard.technicianWorkingHours', { defaultValue: 'Technicians Working Hours' })}
            data={technicianHoursData}
            loading={technicianHoursLoading}
            onOpenReport={() => setShowTechnicianHoursReport(true)}
          />

          {!selectedIssueType && (
            <WoFeedbackSummaryChartCard
              title={t('dashboard.woFeedbackReport', { defaultValue: 'WO Feedback Report' })}
              data={woFeedbackChartData}
              loading={woFeedbackChartLoading}
              onOpenReport={() => setShowWoFeedbackReport(true)}
            />
          )}
        </div>
      </div>

      <WorkOrderStatusReportModal
        isOpen={showWorkOrderStatusReport}
        onClose={() => setShowWorkOrderStatusReport(false)}
        initialChartData={typeStatusChartData || resolvedWorkOrderGroupedChartData}
        defaultFromDate={dashFromDate}
        defaultToDate={dashToDate}
        locationFilters={dashboardReportFilters}
        workOrderType={selectedIssueType}
        onRefresh={refreshWorkOrderStatusReport}
      />

      <AssetStatusReportModal
        isOpen={showAssetReport}
        onClose={() => setShowAssetReport(false)}
        chartData={assetDeviceStatusChartData}
        defaultFromDate={dashFromDate}
        defaultToDate={dashToDate}
        locationFilters={dashboardReportFilters}
        onRefresh={refreshAssetStatusReport}
      />

      <TechnicianWorkOrderSummaryReportModal
        isOpen={showTechnicianWorkOrderReport}
        onClose={() => setShowTechnicianWorkOrderReport(false)}
        permittedIssueTypes={permittedIssueTypes}
        isAdmin={isWoAdmin}
        defaultWorkOrderType={selectedIssueType}
        defaultFromDate={dashFromDate}
        defaultToDate={dashToDate}
        defaultCompany={filterHospital}
        defaultSiteName={filterSiteName}
        companyLocked={hospitalLocked}
        siteLocked={siteLocked}
        hospitalLinkFilters={hospitalLinkFilters}
      />

      <TechnicianWorkingHoursReportModal
        isOpen={showTechnicianHoursReport}
        onClose={() => setShowTechnicianHoursReport(false)}
        permittedIssueTypes={permittedIssueTypes}
        isAdmin={isWoAdmin}
        defaultWorkOrderType={selectedIssueType}
        defaultFromDate={dashFromDate}
        defaultToDate={dashToDate}
        defaultCompany={filterHospital}
        defaultSiteName={filterSiteName}
        companyLocked={hospitalLocked}
        siteLocked={siteLocked}
        hospitalLinkFilters={hospitalLinkFilters}
      />

      <WoFeedbackReportModal
        isOpen={showWoFeedbackReport}
        onClose={() => setShowWoFeedbackReport(false)}
        defaultCompany={filterHospital}
        defaultSiteName={filterSiteName}
        companyLocked={hospitalLocked}
        siteLocked={siteLocked}
        hospitalLinkFilters={hospitalLinkFilters}
      />

      <ChartDetailModal
        isOpen={!!chartDetail}
        onClose={() => setChartDetail(null)}
        title={chartDetail?.title || ''}
        initialData={chartDetail?.data}
        redirectContext={chartDetail?.redirectContext}
        defaultFromDate={dashFromDate}
        defaultToDate={dashToDate}
        locationFilters={dashboardReportFilters}
        workOrderType={selectedIssueType}
      />
    </div>
  );
};

// Mini Stat Box Component with border-right (Compact)
const StatCard: React.FC<{
  icon: React.ReactNode;
  value: string | number;
  label: string;
  bgColor: string;
  onClick?: () => void;
}> = ({ icon, value, label, bgColor, onClick }) => (
  <button
    type="button"
    onClick={onClick}
    title={onClick ? `View ${label}` : undefined}
    className={`w-full text-center py-2 px-1 border-r border-gray-200 dark:border-gray-700 last:border-r-0 transition-all ${
      onClick
        ? 'cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/40 hover:shadow-sm rounded-lg group'
        : 'cursor-default'
    }`}
  >
    <div
      className={`w-10 h-10 ${bgColor} rounded-lg flex items-center justify-center text-base mx-auto mb-1.5 transition-transform ${
        onClick ? 'group-hover:scale-105' : ''
      }`}
    >
      {icon}
    </div>
    <div className="text-lg font-semibold text-gray-900 dark:text-white leading-none mb-1">{value}</div>
    <div className="text-[9px] font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide leading-tight px-1">
      {label}
    </div>
  </button>
);

// Insight Card Component - Shows key metrics with trends
const InsightCard: React.FC<{ 
  icon: React.ReactNode; 
  title: string; 
  value: string | number; 
  trend: string;
  trendUp: boolean;
  bgColor: string;
}> = ({ icon, title, value, trend, trendUp, bgColor }) => (
  <div className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-md transition-all p-4 border border-gray-200 dark:border-gray-700">
    <div className="flex items-start justify-between mb-3">
      <div className={`w-10 h-10 ${bgColor} rounded-lg flex items-center justify-center text-lg`}>
        {icon}
      </div>
      <div className={`flex items-center gap-1 text-xs font-medium ${trendUp ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}>
        {trendUp ? <FaArrowUp className="text-[10px]" /> : <FaArrowDown className="text-[10px]" />}
        {trend}
      </div>
    </div>
    <div className="text-2xl font-semibold text-gray-900 dark:text-white mb-1">{value}</div>
    <div className="text-xs font-medium text-gray-600 dark:text-gray-400">{title}</div>
  </div>
);

// Completion Rate Card with Mini Area Chart
const CompletionRateCard: React.FC<{ 
  totalWorkOrders: number; 
  completedWorkOrders: number;
  inProgressWorkOrders: number;
}> = ({ totalWorkOrders, completedWorkOrders, inProgressWorkOrders }) => {
  const completionRate = totalWorkOrders > 0 
    ? ((completedWorkOrders / totalWorkOrders) * 100).toFixed(2)
    : '0.00';
  
  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-md transition-all px-5 border border-gray-200 dark:border-gray-700">
      <div className="mb-3">
      <div className="text-2xl font-semibold text-gray-900 dark:text-white mb-2">{completionRate}%</div>
      <div className="text-sm font-medium text-indigo-600 dark:text-indigo-400 mb-1">Completion Rate</div>
       
      </div>
      <div className="mt-1">
        <MiniAreaChart />
      </div>
      
      {/* Mini Stats */}
      <div className="grid grid-cols-3 gap-3 mt-2 pt-2 mb-2 pb-2 border-t border-gray-200 dark:border-gray-700">
        <div className="text-center">
        <div className="text-lg font-semibold text-indigo-600 dark:text-indigo-400">{totalWorkOrders}</div>
        <div className="text-[9px] font-medium text-gray-500 dark:text-gray-400 uppercase">Total</div>
      </div>
      <div className="text-center">
        <div className="text-lg font-semibold text-blue-600 dark:text-blue-400">{inProgressWorkOrders}</div>
        <div className="text-[9px] font-medium text-gray-500 dark:text-gray-400 uppercase">In Progress</div>
      </div>
      <div className="text-center">
        <div className="text-lg font-semibold text-green-600 dark:text-green-400">{completedWorkOrders}</div>
        <div className="text-[9px] font-medium text-gray-500 dark:text-gray-400 uppercase">Completed</div>
        </div>
      </div>
    </div>
  );
};


// Department Sales Card (Full Height to match left side total height)
const DepartmentSalesCard: React.FC<{
  title: string;
  data: any;
  totalWorkOrders: number;
  completedWorkOrders: number;
  loading?: boolean;
  onOpenReport: () => void;
}> = ({ title, data, totalWorkOrders, completedWorkOrders, loading = false, onOpenReport }) => {
  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-md transition-all px-5 py-5 border border-gray-200 dark:border-gray-700 flex flex-col" style={{ minHeight: '100%' }}>
      <div className="flex items-center justify-between mb-4 flex-shrink-0">
        <div>
          <h3 className="text-base font-semibold text-gray-900 dark:text-white">{title}</h3>
          <div className="flex items-center gap-3 mt-1">
            <div className="text-xl font-semibold text-gray-900 dark:text-white">
              {totalWorkOrders} Total
            </div>
            <div className="text-xs text-gray-600 dark:text-gray-400">
              <span className="font-medium">{completedWorkOrders} Completed</span>
              <span className="ml-1">({totalWorkOrders > 0 ? ((completedWorkOrders / totalWorkOrders) * 100).toFixed(1) : 0}%)</span>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={onOpenReport}
            className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg text-indigo-600 dark:text-indigo-300"
            title="View details"
          >
            <FaExternalLinkAlt className="w-4 h-4" />
          </button>
        </div>
      </div>
      <div className="flex-1">
        {loading ? (
          <div className="h-64 flex items-center justify-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600" />
          </div>
        ) : isPieChartRenderable(data) ? (
          <PieChart data={data} />
        ) : (
          <div className="h-64 flex items-center justify-center text-gray-400 text-sm">
            No chart data available
          </div>
        )}
      </div>
    </div>
  );
};

// Metric Card Component (Bottom Row - Smaller & Compact)
// const MetricCard: React.FC<{ 
//   icon: React.ReactNode; 
//   label: string; 
//   value: string; 
//   iconColor?: string;
//   bgColor: string;
//   textColor?: string;
// }> = ({ icon, label, value, iconColor = "text-white", bgColor, textColor = "text-gray-900 dark:text-white" }) => (
//   <div className={`${bgColor} rounded-lg shadow hover:shadow-md transition-all p-5 border border-gray-200 dark:border-gray-700`}>
//     <div className="flex items-center justify-between mb-3">
//       <div className={`text-2xl ${iconColor}`}>
//         {icon}
//       </div>
//     </div>
//     <div>
//       <div className={`text-[10px] font-medium uppercase tracking-wide mb-1 ${textColor.includes('white') ? 'text-white/80' : 'text-gray-600 dark:text-gray-400'}`}>
//         {label}
//       </div>
//       <div className={`text-2xl font-semibold ${textColor}`}>{value}</div>
//     </div>
//   </div>
// );

// Mini Area Chart Component
const MiniAreaChart: React.FC = () => {
  const data = [10, 15, 13, 17, 14, 18, 16];
  const max = Math.max(...data);
  const width = 400;
  const height = 80;
  
  const points = data.map((value, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - (value / max) * height;
    return `${x},${y}`;
  }).join(' ');

  const areaPoints = `0,${height} ${points} ${width},${height}`;

  return (
    <svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`} className="w-full">
      <defs>
        <linearGradient id="areaGradient" x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" style={{ stopColor: '#8B5CF6', stopOpacity: 0.3 }} />
          <stop offset="100%" style={{ stopColor: '#8B5CF6', stopOpacity: 0.05 }} />
        </linearGradient>
      </defs>
      <polygon points={areaPoints} fill="url(#areaGradient)" />
      <polyline
        points={points}
        fill="none"
        stroke="#8B5CF6"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
};

// --- Chart hover tooltips (inline) ---
interface ChartTooltipState {
  x: number;
  y: number;
  text: string;
}

const formatChartTooltip = (label: string, value: number, total?: number): string => {
  if (total != null && total > 0) {
    const pct = ((value / total) * 100).toFixed(1);
    return `${label}: ${value} (${pct}%)`;
  }
  return `${label}: ${value}`;
};

const useChartTooltip = () => {
  const [tooltip, setTooltip] = useState<ChartTooltipState | null>(null);

  const show = useCallback(
    (clientX: number, clientY: number, label: string, value: number, total?: number) => {
      setTooltip({
        x: clientX,
        y: clientY,
        text: formatChartTooltip(label, value, total),
      });
    },
    []
  );

  const hide = useCallback(() => setTooltip(null), []);

  return { tooltip, show, hide };
};

const ChartTooltipOverlay: React.FC<{ tooltip: ChartTooltipState | null }> = ({ tooltip }) => {
  if (!tooltip) return null;

  return (
    <div
      className="fixed z-[9999] pointer-events-none px-2.5 py-1.5 rounded text-xs font-medium text-white bg-gray-900 shadow-lg whitespace-nowrap"
      style={{
        left: tooltip.x,
        top: tooltip.y - 8,
        transform: 'translate(-50%, -100%)',
      }}
      role="tooltip"
    >
      {tooltip.text}
    </div>
  );
};

// Grouped Bar Chart Component for multiple datasets
const GroupedBarChart: React.FC<{ data: any }> = ({ data }) => {
  const { tooltip, show, hide } = useChartTooltip();
  const labels = data?.labels || [];
  const datasets = data?.datasets || [];
  
  if (!datasets.length) {
    return <div className="text-center text-gray-400 py-4 text-sm">No data available</div>;
  }

  const allValues = datasets.flatMap((ds: any) => ds.values || []);
  const max = Math.max(...allValues, 1);
  const chartHeight = 240;
  const width = Math.max(800, labels.length * 100);
  const groupWidth = Math.min(120, (width - 100) / labels.length);
  const barSpacing = 4;
  const numBars = datasets.length;
  const barWidth = Math.max(12, (groupWidth - barSpacing * (numBars + 1)) / numBars);

  // Color mapping for status types - Blue and Purple palette
  const statusColors: Record<string, string> = {
    'Completed On Time': '#6366F1', // Indigo
    'Completed Within SLA': '#3B82F6', // Blue
    'Delay In Completion': '#8B5CF6', // Purple
    'Pending': '#A855F7', // Purple variant
    'Overdue': '#EC4899', // Pink (for contrast/alert)
    'Cancelled': '#0EA5E9', // Sky blue
    'Open': '#6366F1', // Indigo
    'Work In Progress': '#3B82F6', // Blue
    'Pending Review': '#8B5CF6', // Purple
    'Completed': '#6366F1', // Indigo
    'Closed': '#A855F7', // Purple variant
  };

  // Generate colors for datasets
  const getDatasetColor = (datasetName: string, index: number): string => {
    // Try to match by name first
    for (const [key, color] of Object.entries(statusColors)) {
      if (datasetName.toLowerCase().includes(key.toLowerCase())) {
        return color;
      }
    }
    // Fallback to generated colors
    return generateColors(numBars)[index];
  };

  const groupTotals = labels.map((_: string, labelIndex: number) =>
    datasets.reduce((sum: number, dataset: any) => sum + parseHours(dataset.values?.[labelIndex]), 0)
  );

  return (
    <div className="relative w-full overflow-x-auto" onMouseLeave={hide}>
      <ChartTooltipOverlay tooltip={tooltip} />
      <svg width="100%" height={chartHeight + 40} viewBox={`0 0 ${width} ${chartHeight + 40}`} className="w-full" preserveAspectRatio="xMidYMid meet">
        <defs>
          {datasets.map((ds: any, i: number) => {
            const color = getDatasetColor(ds.name || '', i);
            return (
              <linearGradient key={i} id={`groupedBarGradient${i}`} x1="0%" y1="0%" x2="0%" y2="100%">
                <stop offset="0%" style={{ stopColor: color, stopOpacity: 0.9 }} />
                <stop offset="100%" style={{ stopColor: color, stopOpacity: 0.7 }} />
              </linearGradient>
            );
          })}
        </defs>

        {/* Grid lines */}
        {[0, 0.25, 0.5, 0.75, 1].map((ratio, i) => (
          <line
            key={i}
            x1="60"
            y1={chartHeight - (ratio * chartHeight)}
            x2={width - 20}
            y2={chartHeight - (ratio * chartHeight)}
            stroke="#E5E7EB"
            strokeWidth="1"
            className="dark:stroke-gray-700"
          />
        ))}

        {/* Y-axis labels */}
        {[0, 0.25, 0.5, 0.75, 1].map((ratio, i) => (
          <text
            key={i}
            x="45"
            y={chartHeight - (ratio * chartHeight) + 4}
            textAnchor="end"
            className="text-xs fill-gray-400 dark:fill-gray-500"
          >
            {(max * ratio).toFixed(ratio === 0 ? 0 : max < 5 ? 1 : 0)}
          </text>
        ))}

        {/* Y-axis label */}
        <text
          x="15"
          y={chartHeight / 2}
          textAnchor="middle"
          transform={`rotate(-90, 15, ${chartHeight / 2})`}
          className="text-xs fill-gray-600 dark:fill-gray-400 font-medium"
        >
          Count
        </text>

        {/* Grouped Bars */}
        {labels.map((label: string, labelIndex: number) => {
          const groupX = 80 + (labelIndex * groupWidth);
          
          return (
            <g key={labelIndex}>
              {datasets.map((dataset: any, dsIndex: number) => {
                const value = parseHours(dataset.values?.[labelIndex]);
                const barHeight = (value / max) * chartHeight;
                const x = groupX + barSpacing + (dsIndex * (barWidth + barSpacing));
                const y = chartHeight - barHeight;
                const datasetColors = dataset.colors || [];
                const color =
                  numBars === 1 && datasetColors[labelIndex]
                    ? datasetColors[labelIndex]
                    : getDatasetColor(dataset.name || '', dsIndex);
                const statusLabel = labels[labelIndex] || label;
                const tooltipText =
                  numBars === 1
                    ? `${statusLabel} — Tasks: ${value}`
                    : `${statusLabel} — ${dataset.name || `Series ${dsIndex + 1}`}: ${value}`;
                
                return (
                  <g key={dsIndex}>
                    <rect
                      x={x}
                      y={y}
                      width={barWidth}
                      height={barHeight}
                      fill={color}
                      rx="4"
                      ry="4"
                      className="hover:opacity-80 transition-opacity"
                      onMouseEnter={(e) => show(e.clientX, e.clientY, tooltipText, value, groupTotals[labelIndex])}
                      onMouseMove={(e) => show(e.clientX, e.clientY, tooltipText, value, groupTotals[labelIndex])}
                      onMouseLeave={hide}
                    />
                  </g>
                );
              })}
              
              {/* X-axis label */}
              <text
                x={groupX + groupWidth / 2}
                y={chartHeight + 15}
                textAnchor="middle"
                className="text-xs fill-gray-600 dark:fill-gray-400"
              >
                {label && label.length > 12 ? label.substring(0, 10) + '...' : label || 'null'}
              </text>
            </g>
          );
        })}
      </svg>

      {/* Legend */}
      <div className="flex flex-wrap items-center justify-center gap-2 mt-2 pt-2 border-t border-gray-200 dark:border-gray-700">
        {datasets.map((dataset: any, i: number) => {
          const color = getDatasetColor(dataset.name || '', i);
          return (
            <div key={i} className="flex items-center gap-1.5">
              <div className="w-2.5 h-2.5 rounded" style={{ backgroundColor: color }}></div>
              <span className="text-xs text-gray-600 dark:text-gray-400">
                {dataset.name && dataset.name.length > 20 ? dataset.name.substring(0, 18) + '...' : dataset.name || `Series ${i + 1}`}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// Bar Chart Component with Line Overlay (Like in Image)
const BarChart: React.FC<{ data: any }> = ({ data }) => {
  const { tooltip, show, hide } = useChartTooltip();
  const labels = data?.labels || [];
  const datasets = data?.datasets || [];
  
  if (!datasets.length) {
    return <div className="text-center text-gray-400 py-8">No data available</div>;
  }

  const allValues = datasets.flatMap((ds: any) => ds.values || []);
  const max = Math.max(...allValues, 1);
  const chartHeight = 250;
  // Increase width based on number of labels to prevent overlap
  const minBarSpacing = 60; // Minimum spacing between bars
  const calculatedWidth = Math.max(800, labels.length * minBarSpacing + 100);
  const width = calculatedWidth;

  // Generate smooth line data (Average line overlay)
  const lineData = (datasets[0]?.values || []).map((v: unknown) => parseHours(v));
  const barTotal = lineData.reduce((sum: number, v: number) => sum + v, 0);

  return (
    <div className="relative w-full overflow-x-auto" onMouseLeave={hide}>
      <ChartTooltipOverlay tooltip={tooltip} />
      <svg width="100%" height="320" viewBox={`0 0 ${width} ${chartHeight + 70}`} className="w-full" preserveAspectRatio="xMidYMid meet">
        <defs>
          <linearGradient id="barGradient" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" style={{ stopColor: '#8B5CF6', stopOpacity: 0.8 }} />
            <stop offset="100%" style={{ stopColor: '#8B5CF6', stopOpacity: 0.6 }} />
          </linearGradient>
        </defs>

        {/* Grid lines */}
        {[0, 0.25, 0.5, 0.75, 1].map((ratio, i) => (
          <line
            key={i}
            x1="60"
            y1={chartHeight - (ratio * chartHeight)}
            x2={width - 20}
            y2={chartHeight - (ratio * chartHeight)}
            stroke="#E5E7EB"
            strokeWidth="1"
            className="dark:stroke-gray-700"
          />
        ))}

        {/* Y-axis labels */}
        {[0, 0.25, 0.5, 0.75, 1].map((ratio, i) => (
          <text
            key={i}
            x="45"
            y={chartHeight - (ratio * chartHeight) + 4}
            textAnchor="end"
            className="text-xs fill-gray-400 dark:fill-gray-500"
          >
            {(max * ratio).toFixed(0)}
          </text>
        ))}

        {/* Bars */}
        {labels.map((label: string, i: number) => {
          const value = parseHours(datasets[0]?.values?.[i]);
          const barHeight = (value / max) * chartHeight;
          const barWidth = Math.min(40, (width - 100) / labels.length - 10);
          const x = 80 + (i * ((width - 100) / labels.length));
          
          return (
            <g key={i}>
              <rect
                x={x}
                y={chartHeight - barHeight}
                width={barWidth}
                height={barHeight}
                fill={`url(#barGradient)`}
                rx="4"
                ry="4"
                className="hover:opacity-80 cursor-pointer transition-opacity"
                onMouseEnter={(e) => show(e.clientX, e.clientY, label || 'Value', value, barTotal)}
                onMouseMove={(e) => show(e.clientX, e.clientY, label || 'Value', value, barTotal)}
                onMouseLeave={hide}
              />
            </g>
          );
        })}

        {/* Line Chart Overlay */}
        {lineData.length > 0 && (
          <polyline
            points={lineData.map((value: number, i: number) => {
              const x = 80 + (i * ((width - 100) / labels.length)) + 20;
              const y = chartHeight - ((value / max) * chartHeight);
              return `${x},${y}`;
            }).join(' ')}
            fill="none"
            stroke="#60A5FA"
            strokeWidth="3"
            strokeLinecap="round"
            strokeLinejoin="round"
            className="drop-shadow-md"
          />
        )}

        {/* Line data points */}
        {lineData.map((value: number, i: number) => {
          const x = 80 + (i * ((width - 100) / labels.length)) + 20;
          const y = chartHeight - ((value / max) * chartHeight);
          const pointLabel = labels[i] || 'Value';
          return (
            <circle
              key={i}
              cx={x}
              cy={y}
              r="4"
              fill="#3B82F6"
              className="hover:r-6 cursor-pointer transition-all"
              onMouseEnter={(e) => show(e.clientX, e.clientY, pointLabel, value, barTotal)}
              onMouseMove={(e) => show(e.clientX, e.clientY, pointLabel, value, barTotal)}
              onMouseLeave={hide}
            />
          );
        })}

        {/* X-axis labels */}
        {labels.map((label: string, i: number) => {
          const barSpacing = (width - 100) / labels.length;
          const x = 80 + (i * barSpacing) + (barSpacing / 2);
          const truncatedLabel = label && label.length > 15 ? label.substring(0, 13) + '...' : label || 'null';
          
          return (
            <text
              key={i}
              x={x}
              y={chartHeight + 50}
              transform={`rotate(-45, ${x}, ${chartHeight + 50})`}
              textAnchor="middle"
              className="text-xs fill-gray-600 dark:fill-gray-400"
            >
              {truncatedLabel}
            </text>
          );
        })}
      </svg>

      {/* Legend - Inside the card */}
      <div className="flex items-center justify-center gap-3 mt-2">
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded" style={{ background: '#8B5CF6' }}></div>
          <span className="text-xs text-gray-600 dark:text-gray-400">Total Sales</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded-full bg-blue-500"></div>
          <span className="text-xs text-gray-600 dark:text-gray-400">Average</span>
        </div>
      </div>
    </div>
  );
};

// Pie Chart Component
const PieChart: React.FC<{ data: any }> = ({ data }) => {
  const { tooltip, show, hide } = useChartTooltip();
  const labels = data?.labels || [];
  const values = (data?.datasets?.[0]?.values || []).map((v: unknown) => parseHours(v));
  
  const isUpDownLabel = (label: string) => {
    const l = label.toLowerCase();
    return l.includes('up') || l.includes('down') || l.includes('تشغيل') || l.includes('توقف');
  };

  const isUpDownTimeChart = labels.some(isUpDownLabel);
  
  let colors: string[] = [];
  
  if (isUpDownTimeChart && labels.length >= 1) {
    colors = labels.map((label: string) => {
      const labelLower = label.toLowerCase();
      if (labelLower.includes('down') || label.includes('توقف')) return DOWN_TIME_COLOR;
      if (labelLower.includes('up') || label.includes('تشغيل')) return UP_TIME_COLOR;
      const index = labels.indexOf(label);
      return index === 0 ? UP_TIME_COLOR : DOWN_TIME_COLOR;
    });
  } else {
    // For other charts, use custom colors if provided, otherwise generate
    const datasetColors = data?.datasets?.[0]?.colors;
    colors = datasetColors && datasetColors.length === values.length 
      ? datasetColors 
      : generateColors(values.length);
  }
  
  const total = values.reduce((sum: number, val: number) => sum + val, 0);

  if (total <= 0 || labels.length === 0) {
    return (
      <div className="h-48 flex items-center justify-center text-gray-400 text-sm">
        No data available
      </div>
    );
  }

  const radius = 100;
  const cx = radius + 10;
  const cy = radius + 10;
  
  let cumulative = 0;
  const slices = values.map((value: number, i: number) => {
    const startAngle = (cumulative / total) * 2 * Math.PI - Math.PI / 2;
    cumulative += value;
    const endAngle = (cumulative / total) * 2 * Math.PI - Math.PI / 2;
    const largeArc = endAngle - startAngle > Math.PI ? 1 : 0;
    
    const x1 = cx + radius * Math.cos(startAngle);
    const y1 = cy + radius * Math.sin(startAngle);
    const x2 = cx + radius * Math.cos(endAngle);
    const y2 = cy + radius * Math.sin(endAngle);
    
    return {
      path: `M ${cx} ${cy} L ${x1} ${y1} A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2} Z`,
      color: colors[i],
      label: labels[i],
      value: value,
      percentage: ((value / total) * 100).toFixed(1)
    };
  });

  const isSingleSlice = slices.length === 1;

  return (
    <div className="flex flex-col md:flex-row items-center justify-around" onMouseLeave={hide}>
      <ChartTooltipOverlay tooltip={tooltip} />
      <svg width={cx * 2} height={cy * 2} viewBox={`0 0 ${cx * 2} ${cy * 2}`} className="max-w-xs">
        {isSingleSlice ? (
          <circle
            cx={cx}
            cy={cy}
            r={radius}
            fill={slices[0].color}
            className="hover:opacity-90 transition-opacity cursor-pointer drop-shadow-lg"
            onMouseEnter={(e) => show(e.clientX, e.clientY, slices[0].label, slices[0].value, total)}
            onMouseMove={(e) => show(e.clientX, e.clientY, slices[0].label, slices[0].value, total)}
            onMouseLeave={hide}
          />
        ) : (
          slices.map((slice: any, i: number) => (
            <path 
              key={i} 
              d={slice.path} 
              fill={slice.color} 
              className="hover:opacity-90 transition-opacity cursor-pointer drop-shadow-lg"
              onMouseEnter={(e) => show(e.clientX, e.clientY, slice.label, slice.value, total)}
              onMouseMove={(e) => show(e.clientX, e.clientY, slice.label, slice.value, total)}
              onMouseLeave={hide}
            />
          ))
        )}
      </svg>
      <div className="flex flex-col gap-3 mt-4 md:mt-0">
        {slices.map((slice: any, i: number) => (
          <div
            key={i}
            className="flex items-center gap-3 cursor-pointer rounded px-1 py-0.5 hover:bg-gray-100 dark:hover:bg-gray-700/50"
            onMouseEnter={(e) => show(e.clientX, e.clientY, slice.label, slice.value, total)}
            onMouseMove={(e) => show(e.clientX, e.clientY, slice.label, slice.value, total)}
            onMouseLeave={hide}
          >
            <div className="w-3 h-3 rounded-full" style={{ backgroundColor: slice.color }}></div>
            <span className="text-sm text-gray-700 dark:text-gray-300">{slice.label}</span>
            <span className="text-sm font-bold text-gray-900 dark:text-white">{slice.value}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// Grouped Chart Card Component for charts with multiple datasets
const GroupedChartCard: React.FC<{
  title: string;
  data: any;
  loading?: boolean;
  onOpenReport?: () => void;
}> = ({ title, data, loading = false, onOpenReport }) => {
  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-md transition-all p-3 border border-gray-200 dark:border-gray-700 h-full">
      <div className="flex items-center justify-between mb-2">
        <h3 className="text-sm font-semibold text-gray-800 dark:text-white">{title}</h3>
        {onOpenReport && (
          <button
            type="button"
            onClick={onOpenReport}
            className="p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg text-indigo-600 dark:text-indigo-300"
            title="View details"
          >
            <FaExternalLinkAlt className="w-3.5 h-3.5" />
          </button>
        )}
      </div>
      {loading ? (
        <div className="h-48 flex items-center justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600" />
        </div>
      ) : !data || !data.datasets || !data.datasets.length ? (
        <div className="h-48 flex items-center justify-center text-gray-400">
          <div className="text-center">
            <div className="text-xs">No chart data available</div>
          </div>
        </div>
      ) : (
        <GroupedBarChart data={data} />
      )}
    </div>
  );
};

const WoFeedbackSummaryChartCard: React.FC<{
  title: string;
  data: any;
  loading?: boolean;
  onOpenReport: () => void;
}> = ({ title, data, loading = false, onOpenReport }) => {
  const { t } = useTranslation();
  const [menuOpen, setMenuOpen] = React.useState(false);
  const menuRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setMenuOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const labels: string[] = data?.labels || [];
  const values: number[] = data?.datasets?.[0]?.values || [];
  const colors: string[] =
    data?.datasets?.[0]?.colors || labels.map((label: string) => getWoFeedbackRatingColor(label));
  const totalResponses = values.reduce((sum, value) => sum + (Number(value) || 0), 0);
  const maxValue = Math.max(...values.map(value => Number(value) || 0), 1);

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-md transition-all p-3 border border-gray-200 dark:border-gray-700">
      <div className="flex items-start justify-between gap-2 mb-2">
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={onOpenReport}
              className="p-1.5 rounded-full bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-300 hover:bg-emerald-100 dark:hover:bg-emerald-900/50 transition-colors shrink-0"
              title={t('dashboard.viewFullReport', { defaultValue: 'View Full Report' })}
            >
              <FaStar className="w-3.5 h-3.5" />
            </button>
            <div className="min-w-0">
              <h3 className="text-sm font-semibold text-gray-800 dark:text-white truncate">{title}</h3>
              <p className="text-[11px] text-emerald-600 dark:text-emerald-300 mt-0.5">
                {t('dashboard.woFeedbackTotalResponses', {
                  total: totalResponses,
                  defaultValue: `Total responses: ${totalResponses}`,
                })}
              </p>
            </div>
          </div>
        </div>

        <div className="relative" ref={menuRef}>
          <button
            type="button"
            onClick={() => setMenuOpen(prev => !prev)}
            className="p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
            aria-label="Chart menu"
          >
            <svg className="w-4 h-4 text-gray-500" fill="currentColor" viewBox="0 0 20 20">
              <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
            </svg>
          </button>
          {menuOpen && (
            <div className="absolute right-0 mt-1 w-44 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-20 py-1">
              <button
                type="button"
                className="w-full text-left px-3 py-2 text-xs text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700"
                onClick={() => {
                  setMenuOpen(false);
                  onOpenReport();
                }}
              >
                {t('dashboard.viewFullReport', { defaultValue: 'View Full Report' })}
              </button>
            </div>
          )}
        </div>
      </div>

      {loading ? (
        <div className="h-48 flex items-center justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-emerald-600" />
        </div>
      ) : !labels.length ? (
        <div className="h-48 flex items-center justify-center text-gray-400 text-xs">
          {t('dashboard.noChartData', { defaultValue: 'No chart data available' })}
        </div>
      ) : (
        <div className="max-h-72 overflow-y-auto pr-1 space-y-2">
          {labels.map((label, index) => {
            const value = Number(values[index]) || 0;
            const widthPct = (value / maxValue) * 100;
            const color = colors[index] || getWoFeedbackRatingColor(label);

            return (
              <div key={`${label}-${index}`} className="grid grid-cols-[7rem_1fr_auto] gap-2 items-center">
                <div className="text-xs text-gray-700 dark:text-gray-300 truncate text-right" title={label}>
                  {label}
                </div>
                <div className="h-7 bg-gray-100 dark:bg-gray-700/60 rounded-md overflow-hidden">
                  <div
                    className="h-full rounded-md transition-opacity"
                    style={{
                      width: `${widthPct}%`,
                      minWidth: value > 0 ? '4px' : 0,
                      backgroundColor: color,
                    }}
                  />
                </div>
                <div className="text-xs font-semibold text-gray-700 dark:text-gray-200 whitespace-nowrap">
                  {value}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

// Helper: Generate colors
function generateColors(count: number): string[] {
  const colors = [
    '#8B5CF6', // Purple
    '#6366F1', // Indigo  
    '#3B82F6', // Blue
    '#06B6D4', // Cyan
    '#14B8A6', // Teal
    '#EC4899', // Pink
    '#A855F7', // Purple variant
    '#0EA5E9', // Sky blue
    '#10B981', // Emerald
    '#F472B6', // Pink variant
    '#7C3AED', // Violet
    '#2DD4BF', // Teal variant
  ];
  return Array.from({ length: count }, (_, i) => colors[i % colors.length]);
}

export default ModernDashboard;

