'use client';

import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { motion, useReducedMotion } from 'motion/react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { type User } from '@/lib/types';
import { 
  TrendingUp, 
  Calendar, 
  Save,
  Edit,
  Check,
  X,
  Palette,
  Plus,
  Trash2
} from 'lucide-react';
import { AppSpinner } from '@/components/ui/app-loader';
import { ChartPanelSkeleton } from '@/components/ui/loading-skeletons';
import { staggerContainer, staggerItem } from '@/lib/motion';
import { TablePagination } from '@/components/ui/table-pagination';
import { api } from '@/lib/store/api';
import { apiCall, apiErrorMessage } from '@/lib/store/api-call';
import {
  enumerateMonthRange,
  monthWindowForDateRange,
  personalKpiCyclesFromRecords,
  personalKpiPeriodKey,
  yearMonthFromDateInput,
  formatPersonalKpiCycleLabel,
  spanForPersonalKpiPeriod,
  parsePersonalKpiEditKey,
  latestPersonalKpiRecord,
} from '@/lib/date-utils';
import { MonthYearPicker } from '@/components/ui/month-year-picker';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';

const MONTHLY_PAGE_SIZE = 10;

// Design KPI configurations
const DESIGN_GRAPHIC_KPI_CONFIG = {
  designQuality: { label: 'Design Quality', weight: 30, max: 30 },
  designSpeed: { label: 'Design Speed', weight: 25, max: 25 },
  deliverableVolume: { label: 'Deliverable Volume', weight: 20, max: 20 },
  collaboration: { label: 'Collaboration', weight: 10, max: 10 },
  technicalKnowledge: { label: 'Technical Knowledge', weight: 15, max: 15 }
};

const DESIGN_UX_KPI_CONFIG = {
  designQuality: { label: 'Design Quality', weight: 30, max: 30 },
  designSpeed: { label: 'Design Speed', weight: 25, max: 25 },
  userExperienceLogic: { label: 'User Experience Logic', weight: 20, max: 20 },
  sowRevisionAdaptation: { label: 'SOW Revision Adaptation', weight: 10, max: 10 },
  technicalKnowledge: { label: 'Technical Knowledge', weight: 15, max: 15 }
};

const DESIGN_ANIMATION_KPI_CONFIG = {
  deliverableQuality: { label: 'Deliverable Quality', weight: 30, max: 30 },
  deliverableSpeed: { label: 'Deliverable Speed', weight: 25, max: 25 },
  editingEfforts: { label: 'Editing Efforts', weight: 20, max: 20 },
  revisionAdaptation: { label: 'Revision Adaptation', weight: 10, max: 10 },
  technicalKnowledge: { label: 'Technical Knowledge', weight: 15, max: 15 }
};

const DESIGN_TEAM_LEAD_KPI_CONFIG = {
  deliverableDeadlines: { label: 'Deliverable Deadlines', weight: 20, max: 20 },
  teamProductivity: { label: 'Team Productivity', weight: 15, max: 15 },
  artDirection: { label: 'Art Direction', weight: 15, max: 15 },
  teamDevelopment: { label: 'Team Development', weight: 10, max: 10 },
  stakeholderCommunication: { label: 'Stakeholder Communication', weight: 10, max: 10 },
  priorityAdaptation: { label: 'Priority Adaptation', weight: 10, max: 10 },
  teamRetentionSatisfaction: { label: 'Team Retention & Satisfaction', weight: 10, max: 10 },
  uptoDateTaskRecords: { label: 'Up-to-Date Task Records', weight: 10, max: 10 }
};

const DESIGN_PERSONAL_BIANNUAL_KPI_CONFIG = {
  professionalDevelopment: { label: 'Professional Development', weight: 20, max: 20 },
  improvementOfDesignStyle: { label: 'Improvement of Design Style', weight: 40, max: 40 },
  designTrendsKnowledge: { label: 'Design Trends Knowledge', weight: 40, max: 40 }
};


interface DesignPerformanceProps {
  user: User;
  designPerformanceType: string;
  designSubTeam?: string;
  isDesignTeamLead: boolean;
  canEdit: boolean;
  dateFrom?: string;
  dateTo?: string;
}

// Utility functions
const formatNumber = (value: number | undefined | null): string => {
  if (value === null || value === undefined || isNaN(value)) return '0.00';
  return Number(value).toFixed(2);
};

const validateKPIValue = (value: number, maxValue: number): boolean => {
  return value >= 0 && value <= maxValue;
};

const getInputClassName = (value: number, maxValue: number, baseClassName: string): string => {
  const isValid = validateKPIValue(value, maxValue);
  const errorClass = isValid ? '' : ' border-red-500 bg-red-50 focus:border-red-500 focus:ring-red-500';
  return baseClassName + errorClass;
};

export function DesignPerformance({ 
  user, 
  designPerformanceType, 
  designSubTeam, 
  isDesignTeamLead,
  canEdit,
  dateFrom,
  dateTo
}: DesignPerformanceProps) {
  const [monthlyData, setMonthlyData] = useState<any[]>([]);
  const [biannualData, setBiannualData] = useState<any[]>([]);
  const [earliestDataMonth, setEarliestDataMonth] = useState<{ year: number; month: number } | null>(null);
  const [loading, setLoading] = useState(true);
  const [isEditingDepartmental, setIsEditingDepartmental] = useState(false);
  const [isEditingPersonal, setIsEditingPersonal] = useState(false);
  const [editingMonthlyData, setEditingMonthlyData] = useState<Record<string, any>>({});
  const [editingBiannualData, setEditingBiannualData] = useState<Record<string, any>>({});
  const [personalRemarks, setPersonalRemarks] = useState<string>('');
  const [departmentalSaveStatus, setDepartmentalSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
  const [personalSaveStatus, setPersonalSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
  const [monthlyPage, setMonthlyPage] = useState(1);
  const [newCycleFrom, setNewCycleFrom] = useState("");
  const [newCycleTo, setNewCycleTo] = useState("");
  const [departmentCycles, setDepartmentCycles] = useState<Array<{ period: string; year: number }>>([]);
  const [isAddingCycle, setIsAddingCycle] = useState(false);
  const [periodToDelete, setPeriodToDelete] = useState<{
    period: string;
    year: number;
    label: string;
  } | null>(null);
  const [isDeletingCycle, setIsDeletingCycle] = useState(false);
  const prefersReducedMotion = useReducedMotion();
  const { toast } = useToast();

  // Select appropriate KPI config based on design type
  const MONTHLY_KPI_CONFIG = useMemo(() => {
    switch (designPerformanceType) {
      case 'design-graphic':
        return DESIGN_GRAPHIC_KPI_CONFIG;
      case 'design-ux':
        return DESIGN_UX_KPI_CONFIG;
      case 'design-animation':
        return DESIGN_ANIMATION_KPI_CONFIG;
      case 'design-team-lead':
        return DESIGN_TEAM_LEAD_KPI_CONFIG;
      default:
        return DESIGN_GRAPHIC_KPI_CONFIG;
    }
  }, [designPerformanceType]);

  const BIANNUAL_CONFIG = DESIGN_PERSONAL_BIANNUAL_KPI_CONFIG;

  const FISCAL_YEAR_MONTHS = useMemo(() => {
    const { start, end } = monthWindowForDateRange(dateFrom, dateTo);
    return enumerateMonthRange(start, end);
  }, [dateFrom, dateTo]);

  const BIANNUAL_PERIODS = useMemo(
    () => personalKpiCyclesFromRecords([...departmentCycles, ...biannualData], dateFrom, dateTo),
    [departmentCycles, biannualData, dateFrom, dateTo],
  );

  const displayedPersonalCycles = useMemo(() => {
    const base = BIANNUAL_PERIODS;
    if (!isEditingPersonal) return base;
    const extras = Object.values(editingBiannualData)
      .filter((row) => row.period && row.year != null)
      .filter(
        (row) =>
          !base.some((c) => c.period === row.period && c.year === row.year),
      )
      .map((row) => {
        const span = spanForPersonalKpiPeriod(row.period as string, row.year as number);
        return {
          period: row.period as string,
          year: row.year as number,
          label: formatPersonalKpiCycleLabel(span.start, span.end),
          start: span.start,
          end: span.end,
        };
      });
    return [...base, ...extras].sort(
      (a, b) =>
        a.start.year * 100 + a.start.month - (b.start.year * 100 + b.start.month),
    );
  }, [BIANNUAL_PERIODS, isEditingPersonal, editingBiannualData]);

  const paginatedMonths = useMemo(() => {
    const start = (monthlyPage - 1) * MONTHLY_PAGE_SIZE;
    return FISCAL_YEAR_MONTHS.slice(start, start + MONTHLY_PAGE_SIZE);
  }, [FISCAL_YEAR_MONTHS, monthlyPage]);

  useEffect(() => {
    setMonthlyPage(1);
  }, [user.id, FISCAL_YEAR_MONTHS.length, dateFrom, dateTo]);

  // API endpoints
  const monthlyApiEndpoint = `/api/performance/${designPerformanceType}-monthly`;
  const biannualApiEndpoint = '/api/performance/design-personal-biannual';

  // Load data
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        
        try {
          const monthlyPerformances = await apiCall<any>(
            api.endpoints.getPerformance.initiate({
              endpoint: monthlyApiEndpoint,
              userId: user.id,
            }),
          );
          setMonthlyData(Array.isArray(monthlyPerformances) ? monthlyPerformances : []);
        } catch {
          // keep empty monthly data on failure
        }

        try {
          const biannualPerformances = await apiCall<any>(
            api.endpoints.getPerformance.initiate({
              endpoint: biannualApiEndpoint,
              userId: user.id,
            }),
          );
          const biannualArray = Array.isArray(biannualPerformances) ? biannualPerformances : [];
          setBiannualData(biannualArray);
          
          const latestBiannual = latestPersonalKpiRecord(biannualArray);
          if (latestBiannual && latestBiannual.remarks) {
            setPersonalRemarks(latestBiannual.remarks);
          }
        } catch {
          // keep empty biannual data on failure
        }

        try {
          const sharedCycles = await apiCall<any>(
            api.endpoints.getPerformance.initiate({
              endpoint: '/api/performance/personal-kpi-cycles',
              userId: user.id,
            }),
          );
          setDepartmentCycles(
            Array.isArray(sharedCycles)
              ? sharedCycles.filter((row: { period?: string; year?: number }) => row?.period && row?.year != null)
              : [],
          );
        } catch {
          setDepartmentCycles([]);
        }
        // Determine earliest data month from attendance records
        try {
          let earliest: { year: number; month: number } | null = null;
          const attData = await apiCall<any>(
            api.endpoints.getMonthlyAttendance.initiate({ userId: user.id }),
          );
          for (const r of (attData.monthlyAttendance || [])) {
            const val = r.year * 100 + r.month;
            if (!earliest || val < earliest.year * 100 + earliest.month) {
              earliest = { year: r.year, month: r.month };
            }
          }
          setEarliestDataMonth(earliest);
        } catch (e) {
          console.error('Error fetching earliest data month:', e);
        }

      } catch (error) {
        console.error('Error loading design performance data:', error);
        toast({
          title: "Error",
          description: "Failed to load design performance data",
          variant: "destructive",
        });
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [user.id, monthlyApiEndpoint, biannualApiEndpoint]);

  // Helper functions
  const getDefaultKPIValue = (weight: number): number => {
    return Math.round(weight * 0.7);
  };

  const handleMonthlyKPIChange = (key: string, field: string, value: number) => {
    setEditingMonthlyData(prev => ({
      ...prev,
      [key]: {
        ...prev[key],
        userId: user.id,
        month: parseInt(key.split('_')[0]),
        year: parseInt(key.split('_')[1]),
        [field]: value,
        weightedAverage: 0
      }
    }));
  };

  const handleBiannualKPIChange = (key: string, field: string, value: number) => {
    const parsed = parsePersonalKpiEditKey(key);
    setEditingBiannualData(prev => ({
      ...prev,
      [key]: {
        ...prev[key],
        userId: user.id,
        period: prev[key]?.period || parsed.period,
        year: prev[key]?.year ?? parsed.year,
        [field]: value,
        weightedAverage: 0
      }
    }));
  };

  const startDepartmentalEditing = () => {
    const monthlyEditData: Record<string, any> = {};
    
    FISCAL_YEAR_MONTHS.forEach(({ month, year }) => {
      const key = `${month}_${year}`;
      const existingData = monthlyData.find(d => d.month === month && d.year === year);
      
      const defaultData: any = {
        userId: user.id,
        month,
        year,
        weightedAverage: 0,
        isPublished: false,
        remarks: ''
      };

      Object.entries(MONTHLY_KPI_CONFIG).forEach(([field, config]) => {
        defaultData[field] = existingData?.[field] || getDefaultKPIValue(config.weight);
      });

      monthlyEditData[key] = existingData ? { ...existingData } : defaultData;
    });
    
    setEditingMonthlyData(monthlyEditData);
    setIsEditingDepartmental(true);
  };

  const startPersonalEditing = () => {
    const biannualEditData: Record<string, any> = {};
    
    BIANNUAL_PERIODS.forEach(({ period, year }) => {
      const key = `${period}_${year}`;
      const existingData = biannualData.find(d => d.period === period && d.year === year);
      
      const defaultData: any = {
        userId: user.id,
        period,
        year,
        weightedAverage: 0,
        isPublished: false,
        remarks: personalRemarks || ''
      };

      Object.entries(BIANNUAL_CONFIG).forEach(([field, config]) => {
        defaultData[field] = existingData?.[field] || getDefaultKPIValue(config.weight);
      });

      biannualEditData[key] = existingData ? { ...existingData } : defaultData;
    });
    
    setEditingBiannualData(biannualEditData);
    setIsEditingPersonal(true);
    setNewCycleFrom("");
    setNewCycleTo("");
  };

  const addPersonalCycle = async () => {
    const start = yearMonthFromDateInput(newCycleFrom);
    const end = yearMonthFromDateInput(newCycleTo);
    if (!start || !end) {
      toast({
        title: "Choose a cycle range",
        description: "Set both start and end months for the new Personal KPI period.",
        variant: "destructive",
      });
      return;
    }
    if (start.year * 100 + start.month > end.year * 100 + end.month) {
      toast({
        title: "Invalid cycle range",
        description: "The cycle start must be on or before the cycle end.",
        variant: "destructive",
      });
      return;
    }

    const { period, year } = personalKpiPeriodKey(start, end);
    const key = `${period}_${year}`;
    if (
      displayedPersonalCycles.some((c) => c.period === period && c.year === year) ||
      editingBiannualData[key]
    ) {
      toast({
        title: "Period already exists",
        description: `${formatPersonalKpiCycleLabel(start, end)} is already in the table.`,
        variant: "destructive",
      });
      return;
    }

    const groupLabel = user.department || "this department";
    setIsAddingCycle(true);
    try {
      await apiCall(
        api.endpoints.savePerformance.initiate({
          endpoint: "/api/performance/personal-kpi-cycles",
          body: { userId: user.id, period, year },
        }),
      );
    } catch (error) {
      toast({
        title: "Could not add period",
        description: apiErrorMessage(error, "Failed to apply this period to the department."),
        variant: "destructive",
      });
      setIsAddingCycle(false);
      return;
    }

    const defaults: Record<string, unknown> = {
      userId: user.id,
      period,
      year,
      weightedAverage: 0,
      isPublished: false,
      remarks: personalRemarks || "",
    };
    Object.entries(BIANNUAL_CONFIG).forEach(([field, config]) => {
      defaults[field] = getDefaultKPIValue(config.weight);
    });

    setDepartmentCycles((prev) =>
      prev.some((c) => c.period === period && c.year === year)
        ? prev
        : [...prev, { period, year }],
    );
    setEditingBiannualData((prev) => ({ ...prev, [key]: defaults }));
    setNewCycleFrom("");
    setNewCycleTo("");
    setIsAddingCycle(false);
    toast({
      title: "Period added",
      description: `${formatPersonalKpiCycleLabel(start, end)} now appears for every ${groupLabel} employee.`,
    });
  };

  const deletePersonalCycle = async () => {
    if (!periodToDelete) return;
    const { period, year, label } = periodToDelete;
    const key = `${period}_${year}`;
    setIsDeletingCycle(true);
    try {
      await apiCall(
        api.endpoints.deletePerformance.initiate({
          endpoint: "/api/performance/personal-kpi-cycles",
          params: { userId: user.id, period, year },
        }),
      );
      setDepartmentCycles((prev) =>
        prev.filter((c) => !(c.period === period && c.year === year)),
      );
      setBiannualData((prev) =>
        prev.filter((c) => !(c.period === period && c.year === year)),
      );
      setEditingBiannualData((prev) => {
        const next = { ...prev };
        delete next[key];
        return next;
      });
      setPeriodToDelete(null);
      toast({
        title: "Period deleted",
        description: `${label} was removed for every ${user.department || "department"} employee.`,
      });
    } catch (error) {
      toast({
        title: "Could not delete period",
        description: apiErrorMessage(error, "Failed to delete this Personal KPI period."),
        variant: "destructive",
      });
    } finally {
      setIsDeletingCycle(false);
    }
  };

  const saveDepartmentalChanges = async () => {
    try {
      setDepartmentalSaveStatus('saving');
      
      for (const [key, data] of Object.entries(editingMonthlyData)) {
        // Calculate weighted average
        const total = Object.entries(MONTHLY_KPI_CONFIG).reduce((sum, [field, config]) => {
          const value = data[field] || 0;
          return sum + (value * (config.weight / 100));
        }, 0);
        
        const dataWithWeightedAvg = {
          ...data,
          weightedAverage: total
        };

        await apiCall(
          api.endpoints.savePerformance.initiate({
            endpoint: monthlyApiEndpoint,
            body: dataWithWeightedAvg,
          }),
        );
      }

      // Update local state
      const updatedMonthlyData = monthlyData.map(existing => {
        const key = `${existing.month}_${existing.year}`;
        return editingMonthlyData[key] ? { ...existing, ...editingMonthlyData[key] } : existing;
      });

      // Add new entries
      Object.entries(editingMonthlyData).forEach(([key, data]) => {
        const exists = monthlyData.some(d => d.month === data.month && d.year === data.year);
        if (!exists) {
          updatedMonthlyData.push(data);
        }
      });

      setMonthlyData(updatedMonthlyData);
      setDepartmentalSaveStatus('saved');
      setIsEditingDepartmental(false);
      
      setTimeout(() => setDepartmentalSaveStatus('idle'), 3000);
      
      toast({
        title: "Success",
        description: "Design performance data saved successfully",
      });
    } catch (error) {
      console.error('Error saving design monthly data:', error);
      setDepartmentalSaveStatus('error');
      setTimeout(() => setDepartmentalSaveStatus('idle'), 3000);
      
      toast({
        title: "Error",
        description: "Failed to save design performance data",
        variant: "destructive",
      });
    }
  };

  const savePersonalChanges = async () => {
    try {
      setPersonalSaveStatus('saving');
      
      for (const [key, data] of Object.entries(editingBiannualData)) {
        // Calculate weighted average
        const total = Object.entries(BIANNUAL_CONFIG).reduce((sum, [field, config]) => {
          const value = data[field] || 0;
          return sum + (value * (config.weight / 100));
        }, 0);
        
        const dataWithWeightedAvg = {
          ...data,
          weightedAverage: total
        };

        await apiCall(
          api.endpoints.savePerformance.initiate({
            endpoint: biannualApiEndpoint,
            body: dataWithWeightedAvg,
          }),
        );
      }

      // Update local state
      const updatedBiannualData = biannualData.map(existing => {
        const key = `${existing.period}_${existing.year}`;
        return editingBiannualData[key] ? { ...existing, ...editingBiannualData[key] } : existing;
      });

      // Add new entries
      Object.entries(editingBiannualData).forEach(([key, data]) => {
        const exists = biannualData.some(d => d.period === data.period && d.year === data.year);
        if (!exists) {
          updatedBiannualData.push(data);
        }
      });

      setBiannualData(updatedBiannualData);
      setPersonalSaveStatus('saved');
      setIsEditingPersonal(false);
      setNewCycleFrom("");
      setNewCycleTo("");
      
      setTimeout(() => setPersonalSaveStatus('idle'), 3000);
      
      toast({
        title: "Success",
        description: "Design personal development data saved successfully",
      });
    } catch (error) {
      console.error('Error saving design biannual data:', error);
      setPersonalSaveStatus('error');
      setTimeout(() => setPersonalSaveStatus('idle'), 3000);
      
      toast({
        title: "Error",
        description: "Failed to save design personal development data",
        variant: "destructive",
      });
    }
  };

  const cancelDepartmentalEditing = () => {
    setIsEditingDepartmental(false);
    setEditingMonthlyData({});
    setDepartmentalSaveStatus('idle');
  };

  const cancelPersonalEditing = () => {
    setIsEditingPersonal(false);
    setEditingBiannualData({});
    setPersonalSaveStatus('idle');
    setNewCycleFrom("");
    setNewCycleTo("");
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <ChartPanelSkeleton />
        <ChartPanelSkeleton />
      </div>
    );
  }

  return (
    <motion.div
      className="space-y-5"
      variants={staggerContainer}
      initial={prefersReducedMotion ? false : 'initial'}
      animate={prefersReducedMotion ? false : 'animate'}
    >
      {/* Design Monthly Performance Section */}
      <motion.section variants={staggerItem} className="rounded-xl border border-border bg-card overflow-hidden">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 px-5 py-3.5 border-b border-border">
          <div className="flex items-center gap-2 min-w-0">
            <Palette className="h-4 w-4 text-primary shrink-0" />
            <div className="min-w-0">
              <h3 className="text-sm font-semibold text-foreground truncate">
                {isDesignTeamLead ? 'Design Team Lead KPIs (Monthly)' : 
                 `Design ${designSubTeam} KPIs (Monthly)`}
              </h3>
              <span className="text-xs text-muted-foreground">All recorded months</span>
            </div>
          </div>
        
          <div className="flex items-center gap-2 shrink-0">
            {departmentalSaveStatus === 'saved' && (
              <div className="flex items-center gap-1.5 text-emerald-600 dark:text-emerald-400">
                <Check className="h-4 w-4" />
                <span className="text-sm font-medium">Saved!</span>
              </div>
            )}
            
            {departmentalSaveStatus === 'error' && (
              <div className="flex items-center gap-1.5 text-destructive">
                <X className="h-4 w-4" />
                <span className="text-sm font-medium">Save Failed</span>
              </div>
            )}
            
            {isEditingDepartmental ? (
              <div className="flex gap-2">
                <Button 
                  variant="outline" 
                  onClick={cancelDepartmentalEditing}
                  disabled={departmentalSaveStatus === 'saving'}
                  size="sm"
                >
                  <X className="h-4 w-4 mr-2" />
                  Cancel
                </Button>
                <Button 
                  onClick={saveDepartmentalChanges}
                  disabled={departmentalSaveStatus === 'saving'}
                  size="sm"
                >
                  {departmentalSaveStatus === 'saving' ? (
                    <>
                      <AppSpinner className="mr-2" />
                      Saving...
                    </>
                  ) : (
                    <>
                      <Save className="h-4 w-4 mr-2" />
                      Save Changes
                    </>
                  )}
                </Button>
              </div>
            ) : canEdit && (
              <Button 
                variant="outline" 
                onClick={startDepartmentalEditing}
                size="sm"
              >
                <Edit className="h-4 w-4 mr-2" />
                Edit
              </Button>
            )}
          </div>
        </div>

        {/* Design Monthly KPI Form */}
        <div className="overflow-x-auto">
          <table className="w-full border-collapse">
            <thead>
              <tr className="bg-muted/50 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                <th className="border-b border-border px-4 py-2 text-left min-w-[140px]">KPI</th>
                <th className="border-b border-border px-4 py-2 text-left min-w-[64px]">Weight</th>
                {paginatedMonths.map(({ month, monthName, year }) => (
                  <th key={`${month}-${year}`} className="border-b border-border px-2 py-2 text-center min-w-[88px] normal-case">
                    <span className="text-[11px] font-semibold text-foreground">{monthName}</span>
                    <span className="block text-[10px] font-normal text-muted-foreground">{year}</span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {Object.entries(MONTHLY_KPI_CONFIG).map(([field, config]) => (
                <tr key={field} className="border-b border-border/60 hover:bg-muted/40">
                  <td className="px-4 py-2 font-medium text-foreground text-sm">{config.label}</td>
                  <td className="px-4 py-2 text-muted-foreground text-sm">{config.weight}</td>
                  {paginatedMonths.map(({ month, year }) => {
                    const key = `${month}_${year}`;
                    const existingData = monthlyData.find(d => d.month === month && d.year === year);
                    const currentValue = isEditingDepartmental && editingMonthlyData[key] 
                      ? editingMonthlyData[key][field] 
                      : existingData?.[field] || 0;
                    
                    return (
                      <td key={key} className="px-2 py-1.5">
                        <Input
                          type="number"
                          min="0"
                          max={config.max}
                          step="0.1"
                          value={currentValue}
                          onChange={(e) => handleMonthlyKPIChange(key, field, parseFloat(e.target.value) || 0)}
                          disabled={!isEditingDepartmental}
                          className={getInputClassName(currentValue, config.max, "w-full h-8 text-center text-sm")}
                          placeholder="0"
                        />
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {FISCAL_YEAR_MONTHS.length > 0 && (
          <TablePagination
            currentPage={monthlyPage}
            totalItems={FISCAL_YEAR_MONTHS.length}
            pageSize={MONTHLY_PAGE_SIZE}
            onPageChange={setMonthlyPage}
            itemLabel="months"
          />
        )}
      </motion.section>

      {/* Design Personal Biannual Performance Section */}
      <motion.section variants={staggerItem} className="rounded-xl border border-border bg-card overflow-hidden">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 px-5 py-3.5 border-b border-border">
          <div className="flex items-center gap-2 min-w-0">
            <TrendingUp className="h-4 w-4 text-emerald-600 dark:text-emerald-400 shrink-0" />
            <div className="min-w-0">
              <h3 className="text-sm font-semibold text-foreground truncate">
                Design Personal Development KPIs
              </h3>
              <span className="text-xs text-muted-foreground">
                One column per review cycle · {displayedPersonalCycles.length} period
                {displayedPersonalCycles.length === 1 ? '' : 's'}
              </span>
            </div>
          </div>
          
          <div className="flex items-center gap-2 shrink-0">
            {personalSaveStatus === 'saved' && (
              <div className="flex items-center gap-1.5 text-emerald-600 dark:text-emerald-400">
                <Check className="h-4 w-4" />
                <span className="text-sm font-medium">Saved!</span>
              </div>
            )}
            
            {personalSaveStatus === 'error' && (
              <div className="flex items-center gap-1.5 text-destructive">
                <X className="h-4 w-4" />
                <span className="text-sm font-medium">Save Failed</span>
              </div>
            )}
            
            {isEditingPersonal ? (
              <div className="flex gap-2">
                <Button 
                  variant="outline" 
                  onClick={cancelPersonalEditing}
                  disabled={personalSaveStatus === 'saving'}
                  size="sm"
                >
                  <X className="h-4 w-4 mr-2" />
                  Cancel
                </Button>
                <Button 
                  onClick={savePersonalChanges}
                  disabled={personalSaveStatus === 'saving'}
                  size="sm"
                >
                  {personalSaveStatus === 'saving' ? (
                    <>
                      <AppSpinner className="mr-2" />
                      Saving...
                    </>
                  ) : (
                    <>
                      <Save className="h-4 w-4 mr-2" />
                      Save Changes
                    </>
                  )}
                </Button>
              </div>
            ) : canEdit && (
              <Button 
                variant="outline" 
                onClick={startPersonalEditing}
                size="sm"
              >
                <Edit className="h-4 w-4 mr-2" />
                Edit
              </Button>
            )}
          </div>
        </div>

        {isEditingPersonal && (
          <div className="flex flex-wrap items-end gap-2 border-b border-border bg-muted/30 px-5 py-3">
            <div className="space-y-1">
              <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
                New cycle from
              </p>
              <MonthYearPicker
                value={newCycleFrom}
                onChange={setNewCycleFrom}
                max={newCycleTo || undefined}
                buttonClassName="h-8 w-[148px]"
                title="Cycle start month"
                placeholder="Select month"
              />
            </div>
            <div className="space-y-1">
              <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
                to
              </p>
              <MonthYearPicker
                value={newCycleTo}
                onChange={setNewCycleTo}
                min={newCycleFrom || undefined}
                buttonClassName="h-8 w-[148px]"
                title="Cycle end month"
                placeholder="Select month"
              />
            </div>
            <Button
              type="button"
              size="sm"
              variant="outline"
              onClick={addPersonalCycle}
              disabled={isAddingCycle}
              className="h-8"
            >
              <Plus className="mr-1.5 h-4 w-4" />
              {isAddingCycle ? "Adding..." : "Add period"}
            </Button>
            <p className="w-full text-[11px] text-muted-foreground">
              Month and year only. Adding or deleting a period applies to every {user.department || "department"} employee.
            </p>
          </div>
        )}

        {/* Design Biannual KPI Form */}
        <div className="overflow-x-auto">
          <table className="w-full border-collapse">
            <thead>
              <tr className="bg-muted/50 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                <th className="border-b border-border px-4 py-2 text-left min-w-[200px]">KPI</th>
                <th className="border-b border-border px-4 py-2 text-left min-w-[64px]">Weight</th>
                {displayedPersonalCycles.map(({ period, label, year }) => (
                  <th key={`${period}-${year}`} className="border-b border-border px-2 py-2 text-center min-w-[120px] normal-case">
                    <span className="text-[11px] font-semibold text-foreground">{label}</span>
                    {isEditingPersonal && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="mt-1 h-7 w-7 text-muted-foreground hover:text-destructive"
                        title={`Delete ${label}`}
                        disabled={isDeletingCycle || personalSaveStatus === "saving"}
                        onClick={() => setPeriodToDelete({ period, year, label })}
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    )}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {Object.entries(BIANNUAL_CONFIG).map(([field, config]) => (
                <tr key={field} className="border-b border-border/60 hover:bg-muted/40">
                  <td className="px-4 py-2 font-medium text-foreground text-sm">{config.label}</td>
                  <td className="px-4 py-2 text-muted-foreground text-sm">{config.weight}</td>
                  {displayedPersonalCycles.map(({ period, year }) => {
                    const key = `${period}_${year}`;
                    const existingData = biannualData.find(d => d.period === period && d.year === year);
                    const currentValue = isEditingPersonal && editingBiannualData[key] 
                      ? editingBiannualData[key][field] 
                      : existingData?.[field] || 0;
                    
                    return (
                      <td key={key} className="px-2 py-1.5">
                        <Input
                          type="number"
                          min="0"
                          max={config.max}
                          step="0.1"
                          value={currentValue}
                          onChange={(e) => handleBiannualKPIChange(key, field, parseFloat(e.target.value) || 0)}
                          disabled={!isEditingPersonal}
                          className={getInputClassName(currentValue, config.max, "w-full h-8 text-center text-sm")}
                          placeholder="0"
                        />
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {displayedPersonalCycles.length === 0 && (
          <div className="text-center py-5 text-muted-foreground">
            <TrendingUp className="h-8 w-8 mx-auto mb-2 opacity-30" />
            <p className="text-sm">No Personal KPI cycles in this date range.</p>
            <p className="text-xs mt-1">
              {canEdit
                ? "Click Edit, then Add period (for example July 2025 – September 2026)."
                : "Widen the date range to see earlier review cycles."}
            </p>
          </div>
        )}
      </motion.section>

      <AlertDialog
        open={!!periodToDelete}
        onOpenChange={(open) => {
          if (!open && !isDeletingCycle) setPeriodToDelete(null);
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete this Personal KPI period?</AlertDialogTitle>
            <AlertDialogDescription>
              {periodToDelete
                ? `${periodToDelete.label} will be removed for every ${user.department || "department"} employee. Saved scores and remarks for this period will also be deleted. This cannot be undone.`
                : ""}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeletingCycle}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              disabled={isDeletingCycle}
              onClick={(event) => {
                event.preventDefault();
                void deletePersonalCycle();
              }}
            >
              {isDeletingCycle ? "Deleting..." : "Delete period"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </motion.div>
  );
}
