import { useState, useEffect, useRef, useMemo } from "react";
import { Button } from "@/shared/common/ui/button";
import {
  PlusIcon,
  Pencil,
  Trash2,
  Loader2,
  Calendar,
  Target,
  BarChart3,
  Clock,
  Hash,
  Percent,
  Users,
  CheckCircle,
  TrendingUp,
  Download,
  Filter,
  Search,
  ChevronDown,
  Eye,
  Edit2,
  ArrowLeft,
  FileText,
  Layers,
  Package,
  UserCheck,
  MoreHorizontal,
  Save,
  X,
  Check,
  Clock4,
  CalendarDays,
} from "lucide-react";
import { t } from "i18next";
import {
  useNavigate,
  useParams,
  useLocation,
  useSearchParams,
} from "react-router-dom";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { useToast } from "@/shared/common/ui/use-toast";
import { useLocalizedName } from "@/shared/common/localizedName";
import { format } from "date-fns";
import { Badge } from "@/shared/common/ui/badge";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Input } from "@/shared/common/ui/input";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import { Label } from "@/shared/common/ui/label";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/shared/common/ui/tabs";
import { ScrollArea } from "@/shared/common/ui/scroll-area";
import {
  useEmployeePlanByPlanId,
  ExtendedEmployeePlanDto,
  EMPLOYEE_PLAN_KEYS,
} from "@/performance-management/hooks/useEmployeePlan";
import { useEmployeePlanMutations } from "@/performance-management/hooks/useEmployeePlan";
import { cn } from "@/shared/lib/utils";
import { usePlan } from "@/performance-management/hooks/usePlans";
import { useQueryClient } from "@tanstack/react-query";
import {
  calculateAvailableMonths,
  filterMonthsByEmployeePlans,
  monthsConfig,
} from "@/performance-management/utils/ethiopianMonthCalculator";
import { MyTeamPanel } from "./MyTeamPanel";

interface MonthData {
  employeePlanId: string | null;
  planned: number;
}
// Interface based on the API response structure
interface ApiEmployeeAssignment {
  employeePosition_created_at: string;
  employeePosition_updated_at: string;
  employeePosition_id: string;
  employeePosition_is_delegate: boolean;
  employeePosition_is_current: boolean;
  employeePosition_start_date: string;
  employeePosition_amharic_start_date: string;
  employeePosition_end_date: string | null;
  employeePosition_amharic_end_date: string | null;
  employeePosition_unit_id: string;
  employeePosition_delegator_id: string | null;
  employeePosition_employee_id: string;
  employeePosition_position_id: string;
  employeePosition_delegation_letter_id: string | null;
  employee_created_at: string;
  employee_updated_at: string;
  employee_id: string;
  employee_is_current: boolean;
  employee_status: string;
  employee_name: {
    am: string;
    en: string;
  };
  employee_organization_id: string;
  employee_unit_id: string;
  employee_user_id: string;
  service_created_at: string | null;
  service_updated_at: string | null;
  service_amharic_created_at: string | null;
  service_amharic_updated_at: string | null;
  service_id: string | null;
  service_slug: string | null;
  service_prefix: string | null;
  service_name: { am: string; en: string } | null;
  service_description: { am: string; en: string } | null;
  service_estimatedTime: number | null;
  service_estimatedTimeUnit: string | null;
  service_organization_id: string | null;
  service_service_category_id: string | null;
  no_of_employee_plans: string;
  total_quantity: number | null;
  planned_jul: string;
  planned_aug: string;
  planned_sep: string;
  planned_oct: string;
  planned_nov: string;
  planned_dec: string;
  planned_jan: string;
  planned_feb: string;
  planned_mar: string;
  planned_apr: string;
  planned_may: string;
  planned_jun: string;
  months: {
    jul: MonthData;
    aug: MonthData;
    sep: MonthData;
    oct: MonthData;
    nov: MonthData;
    dec: MonthData;
    jan: MonthData;
    feb: MonthData;
    mar: MonthData;
    apr: MonthData;
    may: MonthData;
    jun: MonthData;
  };
}

interface ProcessedEmployeeAssignment {
  id: string;
  employeeId: string;
  employeeName: {
    am: string;
    en: string;
  };
  positionId: string;
  employeePositionId: string;
  employeeStatus: string;
  service: {
    serviceId: string | null;
    serviceName: { am: string; en: string } | null;
    serviceDescription?: { am: string; en: string } | null;
    estimatedTime?: number | null;
    estimatedTimeUnit?: string | null;
  };
  monthlyPlans: {
    jul: MonthData;
    aug: MonthData;
    sep: MonthData;
    oct: MonthData;
    nov: MonthData;
    dec: MonthData;
    jan: MonthData;
    feb: MonthData;
    mar: MonthData;
    apr: MonthData;
    may: MonthData;
    jun: MonthData;
  };
  totalPlanned: number;
  hasEmployeePlan: boolean;
}

interface EditingCell {
  employeePositionId: string;
  monthKey: string;
  value: string;
}

interface BulkEditState {
  employeePositionId: string;
  isEditing: boolean;
  monthlyInputs: {
    [key: string]: number;
  };
}

interface MonthlyData {
  month: string;
  monthAbbr: string;
  planned: number;
  executed: number;
  variance: number;
  completionRate: number;
}

export const EmployeePlanAssignmentsPage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { yearId, planId } = useParams();
  const { data: planData } = usePlan(planId as string);
  const { toast } = useToast();
  const localizedName = useLocalizedName();
  const { create, update } = useEmployeePlanMutations();

  // Get plan months from URL query parameters
  const [searchParams] = useSearchParams();
  const monthsParam = searchParams.get("months");
  const planMonthsFromState = useMemo(() => {
    if (monthsParam) {
      // Parse comma-separated months or single month
      return monthsParam
        .split(",")
        .map((m) => parseInt(m))
        .filter((m) => !isNaN(m));
    }
    return [];
  }, [monthsParam]);

  // Also get navigation state as fallback
  const navigationState = useMemo(
    () => location.state as any,
    [location.state],
  );

  const [assignments, setAssignments] = useState<ProcessedEmployeeAssignment[]>(
    [],
  );
  const [selectedService, setSelectedService] = useState<string>("all");
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
  const [editingCell, setEditingCell] = useState<EditingCell | null>(null);
  const [bulkEditStates, setBulkEditStates] = useState<{
    [key: string]: BulkEditState; // keyed by employeePositionId
  }>({});
  const [selectedPlanType, setSelectedPlanType] = useState<
    "number" | "percent"
  >("percent");
  const [selectedTimeframe, setSelectedTimeframe] = useState<
    "yearly" | "quarterly" | "monthly" | "weekly" | "daily"
  >("monthly");
  const [dynamicMonthsConfig, setDynamicMonthsConfig] =
    useState<typeof monthsConfig>(monthsConfig);
  const queryClient = useQueryClient();
  // Fetch actual data from API
  const {
    data: assignmentsResponse,
    isLoading,
    error,
    refetch,
  } = useEmployeePlanByPlanId(planId as string);

  // Handle navigation to weekly view when timeframe is changed to weekly
  useEffect(() => {
    if (selectedTimeframe === "weekly") {
      // Get the first month from planMonthsFromState or dynamicMonthsConfig
      let monthToUse: number | undefined;

      if (planMonthsFromState && planMonthsFromState.length > 0) {
        monthToUse = planMonthsFromState[0];
      } else if (dynamicMonthsConfig && dynamicMonthsConfig.length > 0) {
        monthToUse = dynamicMonthsConfig[0].value;
      }

      if (monthToUse) {
        console.log("Navigating to weekly view for month:", monthToUse);
        navigate(
          `/performance-management/${yearId}/employee-plans/plans/${planId}/${monthToUse}/weekly`,
          {
            state: navigationState,
          },
        );
      }
    }
  }, [
    selectedTimeframe,
    planMonthsFromState,
    dynamicMonthsConfig,
    planId,
    yearId,
    navigate,
    navigationState,
  ]);

  // Calculate available months — the plan's own date range is the source of
  // truth (a Q4 plan must show only Apr/May/Jun, etc.). The ?months= URL
  // param and the assignments payload are only used as fallbacks when the
  // plan data hasn't loaded yet.
  useEffect(() => {
    const startDate =
      planData?.data?.amharicStartDate || planData?.data?.startDate;
    const endDate =
      planData?.data?.amharicEndDate || planData?.data?.endDate;

    if (startDate && endDate) {
      const filteredMonths = calculateAvailableMonths(
        startDate,
        endDate,
        monthsConfig,
      );
      setDynamicMonthsConfig(
        filteredMonths.length > 0 ? filteredMonths : monthsConfig,
      );
      return;
    }

    if (planMonthsFromState && planMonthsFromState.length > 0) {
      setDynamicMonthsConfig(
        filterMonthsByEmployeePlans(monthsConfig, planMonthsFromState),
      );
      return;
    }

    setDynamicMonthsConfig(monthsConfig);
  }, [
    planData?.data?.amharicStartDate,
    planData?.data?.amharicEndDate,
    planData?.data?.startDate,
    planData?.data?.endDate,
    planMonthsFromState,
  ]);

  // First, let's debug what data you're getting
  useEffect(() => {
    if (assignmentsResponse?.data?.items) {
      console.log("========== API RESPONSE DEBUG ==========");
      console.log(
        "Raw API response items count:",
        assignmentsResponse.data.items.length,
      );
      console.log(
        "Raw API response:",
        JSON.stringify(assignmentsResponse.data.items, null, 2),
      );

      const processed = processApiData(assignmentsResponse.data.items);

      console.log("========== PROCESSED DATA DEBUG ==========");
      console.log("Processed assignments count:", processed.length);
      processed.forEach((assignment, index) => {
        console.log(`\n--- Assignment ${index + 1} ---`);
        console.log("Composite ID:", assignment.employeePositionId);
        console.log("Service ID:", assignment.service.serviceId);
        console.log("Service Name:", assignment.service.serviceName);
        console.log("Sep planned:", assignment.monthlyPlans.sep?.planned);
        console.log("Nov planned:", assignment.monthlyPlans.nov?.planned);
        console.log("Dec planned:", assignment.monthlyPlans.dec?.planned);
      });

      setAssignments(processed);
    }
  }, [assignmentsResponse]);

  // Also add this to see what's being displayed
  useEffect(() => {
    console.log("Current assignments state:", assignments);
  }, [assignments]);

  // Process API response data
  const processApiData = (
    apiData: ApiEmployeeAssignment[],
  ): ProcessedEmployeeAssignment[] => {
    return apiData.map((item) => {
      const monthlyPlans = {
        jul: item.months.jul,
        aug: item.months.aug,
        sep: item.months.sep,
        oct: item.months.oct,
        nov: item.months.nov,
        dec: item.months.dec,
        jan: item.months.jan,
        feb: item.months.feb,
        mar: item.months.mar,
        apr: item.months.apr,
        may: item.months.may,
        jun: item.months.jun,
      };

      const totalPlanned = Object.values(monthlyPlans).reduce(
        (sum, plan) => sum + plan.planned,
        0,
      );
      const hasEmployeePlan =
        parseInt(item.no_of_employee_plans) > 0 ||
        Object.values(monthlyPlans).some(
          (plan) => plan.employeePlanId !== null,
        );

      // Create composite key: employeePositionId + serviceId
      // This is necessary because the API returns the same employeePosition_id
      // for different services (one employee can have multiple services)
      const compositeId = `${item.employeePosition_id}_${
        item.service_id || "no-service"
      }`;

      return {
        id: compositeId,
        employeeId: item.employee_id,
        employeeName: item.employee_name,
        positionId: item.employeePosition_position_id,
        employeePositionId: compositeId, // Use composite ID as unique identifier
        employeeStatus: item.employee_status,
        service: {
          serviceId: item.service_id,
          serviceName: item.service_name,
          serviceDescription: item.service_description,
          estimatedTime: item.service_estimatedTime,
          estimatedTimeUnit: item.service_estimatedTimeUnit,
        },
        monthlyPlans,
        totalPlanned,
        hasEmployeePlan,
      };
    });
  };

  // Calculate monthly data for display - FIXED VERSION
  const calculateEmployeeMonthlyData = (
    assignment: ProcessedEmployeeAssignment,
  ): MonthlyData[] => {
    return dynamicMonthsConfig.map((monthConfig) => {
      const monthPlan =
        assignment.monthlyPlans[
          monthConfig.key as keyof typeof assignment.monthlyPlans
        ];

      const planned = monthPlan?.planned || 0;
      const executed = 0; // You would get this from actuals API
      const variance = executed - planned;
      const completionRate =
        planned > 0 ? Math.min(100, (executed / planned) * 100) : 0;

      return {
        month: monthConfig.name,
        monthAbbr: monthConfig.abbr,
        planned,
        executed,
        variance,
        completionRate,
      };
    });
  };
  // Get all unique services for filtering
  const allServices = Array.from(
    new Set(
      assignments
        .map((assignment) => assignment.service.serviceId)
        .filter((id) => id),
    ),
  );

  // Toggle row expansion
  const toggleRowExpansion = (employeePositionId: string) => {
    const newExpanded = new Set(expandedRows);
    if (newExpanded.has(employeePositionId)) {
      newExpanded.delete(employeePositionId);
    } else {
      newExpanded.add(employeePositionId);
    }
    setExpandedRows(newExpanded);
  };

  // Filter assignments
  const filteredAssignments = assignments.filter((assignment) => {
    const matchesSearch =
      localizedName(assignment.employeeName)
        .toLowerCase()
        .includes(searchTerm.toLowerCase()) ||
      (assignment.service.serviceName
        ? localizedName(assignment.service.serviceName || undefined)
            .toLowerCase()
            .includes(searchTerm.toLowerCase())
        : false);

    const matchesService =
      selectedService === "all" ||
      assignment.service.serviceId === selectedService;

    const matchesStatus =
      statusFilter === "all" || assignment.employeeStatus === statusFilter;

    return matchesSearch && matchesService && matchesStatus;
  });

  // Helper function to extract actual employeePositionId from composite key
  // Composite key format: "employeePositionId_serviceId"
  const getActualPositionId = (compositeId: string): string => {
    return compositeId.split("_")[0];
  };

  // Start editing a single cell
  const startCellEdit = (
    employeePositionId: string,
    monthKey: string,
    currentValue: number,
  ) => {
    const monthConfig = dynamicMonthsConfig.find((m) => m.key === monthKey);
    console.log(`Editing ${monthConfig?.name} (value: ${monthConfig?.value})`);

    setEditingCell({
      employeePositionId,
      monthKey,
      value: currentValue.toString(),
    });
  };

  // Save single cell edit
  const saveCellEdit = async () => {
    if (!editingCell || !planId) return;

    const assignment = assignments.find(
      (a) => a.employeePositionId === editingCell.employeePositionId,
    );
    if (!assignment) return;

    const newValue = parseInt(editingCell.value) || 0;
    const monthConfig = dynamicMonthsConfig.find(
      (m) => m.key === editingCell.monthKey,
    );
    const monthValue = monthConfig?.value || 0;

    console.log("========== SAVE CELL EDIT DEBUG ==========");
    console.log("Month Key:", editingCell.monthKey);
    console.log("Month Config:", monthConfig);
    console.log("Month Value (API):", monthValue);
    console.log("New Planned Value:", newValue);

    // Store previous value for rollback
    const previousValue =
      assignment.monthlyPlans[
        editingCell.monthKey as keyof typeof assignment.monthlyPlans
      ]?.planned || 0;

    // OPTIMISTIC UPDATE: Update local state immediately
    setAssignments((prev) =>
      prev.map((a) => {
        if (a.employeePositionId === editingCell.employeePositionId) {
          const updatedMonthlyPlans = {
            ...a.monthlyPlans,
            [editingCell.monthKey]: {
              ...a.monthlyPlans[
                editingCell.monthKey as keyof typeof a.monthlyPlans
              ],
              planned: newValue,
            },
          };

          // Recalculate total
          const totalPlanned = Object.values(updatedMonthlyPlans).reduce(
            (sum, plan) => sum + plan.planned,
            0,
          );

          return {
            ...a,
            monthlyPlans: updatedMonthlyPlans,
            totalPlanned,
          };
        }
        return a;
      }),
    );

    // Close edit mode immediately for instant feedback
    setEditingCell(null);

    try {
      // Get the current monthly plan for this month
      const currentMonthlyPlan =
        assignment.monthlyPlans[
          editingCell.monthKey as keyof typeof assignment.monthlyPlans
        ];

      const employeePlanId = currentMonthlyPlan?.employeePlanId;

      console.log("Employee Plan ID:", employeePlanId);
      console.log("Current Monthly Plan:", currentMonthlyPlan);

      // Extract the actual employeePositionId from composite key
      const actualPositionId = getActualPositionId(
        assignment.employeePositionId,
      );

      console.log("========== SAVE CELL EDIT DEBUG ==========");
      console.log("Composite ID:", assignment.employeePositionId);
      console.log("Actual Position ID:", actualPositionId);
      console.log("Service ID:", assignment.service.serviceId);
      console.log("Service Name:", assignment.service.serviceName);
      console.log("Month Key:", editingCell.monthKey);
      console.log("Month Value (API):", monthValue);
      console.log("New Planned Value:", newValue);
      console.log("Employee Plan ID:", employeePlanId);
      console.log("Current Monthly Plan:", currentMonthlyPlan);

      // Create employee plan data
      const employeePlanData: ExtendedEmployeePlanDto = {
        employeePositionId: actualPositionId,
        planId: planId,
        serviceId: assignment.service.serviceId || undefined,
        planType: selectedPlanType === "percent" ? "percent" : "number",
        expectedQuantity: newValue,
        month: monthValue,
        timeframe: selectedTimeframe,
      };

      console.log(
        "API Request Data:",
        JSON.stringify(employeePlanData, null, 2),
      );

      // DECISION: CREATE or UPDATE based on whether we have an employeePlanId
      if (employeePlanId && newValue > 0) {
        // UPDATE existing plan (PUT)
        console.log("ACTION: UPDATE existing plan");
        const result = await update.mutateAsync({
          ...employeePlanData,
          id: employeePlanId,
        });
        console.log("UPDATE Response:", result);
      } else if (!employeePlanId && newValue > 0) {
        // CREATE new plan (POST)
        console.log("ACTION: CREATE new plan");
        const result = await create.mutateAsync(employeePlanData);
        console.log("CREATE Response:", result);
      } else if (employeePlanId && newValue === 0) {
        // UPDATE existing plan to 0 (PUT)
        console.log("ACTION: UPDATE to 0");
        const result = await update.mutateAsync({
          ...employeePlanData,
          id: employeePlanId,
        });
        console.log("UPDATE to 0 Response:", result);
      }
      // else: no plan ID and newValue === 0 → Do nothing

      console.log("Invalidating queries...");

      // Invalidate the query cache (refetch will happen automatically in background)
      queryClient.invalidateQueries({
        queryKey: EMPLOYEE_PLAN_KEYS.planId(planId),
      });

      console.log("Query invalidated successfully");

      toast({
        title: t("common.success", "Success"),
        description: t("employeePlans.planAssignments.monthlyTargetUpdated", {
          month: monthConfig?.name,
        }).replace("{month}", monthConfig?.name || ""),
        variant: "default",
      });
    } catch (error) {
      console.error("========== ERROR ==========");
      console.error("Failed to update monthly target:", error);
      console.error("Error details:", error);

      // ROLLBACK: Revert the optimistic update
      setAssignments((prev) =>
        prev.map((a) => {
          if (a.employeePositionId === editingCell.employeePositionId) {
            const revertedMonthlyPlans = {
              ...a.monthlyPlans,
              [editingCell.monthKey]: {
                ...a.monthlyPlans[
                  editingCell.monthKey as keyof typeof a.monthlyPlans
                ],
                planned: previousValue,
              },
            };

            const totalPlanned = Object.values(revertedMonthlyPlans).reduce(
              (sum, plan) => sum + plan.planned,
              0,
            );

            return {
              ...a,
              monthlyPlans: revertedMonthlyPlans,
              totalPlanned,
            };
          }
          return a;
        }),
      );

      toast({
        title: t("common.error", "Error"),
        description: t("employeePlans.planAssignments.failedToUpdateTarget"),
        variant: "destructive",
      });
    }
  };
  // Start bulk edit for an employee
  const startBulkEdit = (assignment: ProcessedEmployeeAssignment) => {
    const monthlyInputs: { [key: string]: number } = {};

    // Convert monthlyPlans to inputs
    dynamicMonthsConfig.forEach((monthConfig) => {
      const monthKey = monthConfig.key;
      const monthlyPlan =
        assignment.monthlyPlans[
          monthKey as keyof typeof assignment.monthlyPlans
        ];
      monthlyInputs[monthKey] = monthlyPlan?.planned || 0;
    });

    setBulkEditStates((prev) => ({
      ...prev,
      [assignment.employeePositionId]: {
        employeePositionId: assignment.employeePositionId,
        isEditing: true,
        monthlyInputs,
      },
    }));
  };

  // Update bulk edit input
  const updateBulkEditInput = (
    employeePositionId: string,
    monthKey: string,
    value: string,
  ) => {
    setBulkEditStates((prev) => {
      // Check if the employeePositionId exists in the state
      if (!prev[employeePositionId]) {
        console.error(
          `Employee Position ID ${employeePositionId} not found in bulk edit states`,
        );
        return prev;
      }

      return {
        ...prev,
        [employeePositionId]: {
          ...prev[employeePositionId],
          monthlyInputs: {
            ...prev[employeePositionId].monthlyInputs,
            [monthKey]: parseInt(value) || 0,
          },
        },
      };
    });
  };

  // Save bulk edit
  const saveBulkEdit = async (employeePositionId: string) => {
    const bulkEditState = bulkEditStates[employeePositionId];
    if (!bulkEditState || !planId) return;

    const assignment = assignments.find(
      (a) => a.employeePositionId === employeePositionId,
    );
    if (!assignment) return;

    // Store previous values for rollback
    const previousMonthlyPlans = { ...assignment.monthlyPlans };

    // OPTIMISTIC UPDATE: Update local state immediately
    setAssignments((prev) =>
      prev.map((a) => {
        if (a.employeePositionId === employeePositionId) {
          const updatedMonthlyPlans = { ...a.monthlyPlans };

          dynamicMonthsConfig.forEach((monthConfig) => {
            const monthKey = monthConfig.key;
            const newValue = bulkEditState.monthlyInputs[monthKey] || 0;

            updatedMonthlyPlans[monthKey as keyof typeof a.monthlyPlans] = {
              ...updatedMonthlyPlans[monthKey as keyof typeof a.monthlyPlans],
              planned: newValue,
            };
          });

          // Recalculate total
          const totalPlanned = Object.values(updatedMonthlyPlans).reduce(
            (sum, plan) => sum + plan.planned,
            0,
          );

          return {
            ...a,
            monthlyPlans: updatedMonthlyPlans,
            totalPlanned,
          };
        }
        return a;
      }),
    );

    // Exit edit mode immediately for instant feedback
    setBulkEditStates((prev) => ({
      ...prev,
      [employeePositionId]: { ...prev[employeePositionId], isEditing: false },
    }));

    try {
      // Process each month separately
      const promises = dynamicMonthsConfig.map(async (monthConfig) => {
        const monthKey = monthConfig.key;
        const newValue = bulkEditState.monthlyInputs[monthKey] || 0;

        const currentMonthlyPlan =
          assignment.monthlyPlans[
            monthKey as keyof typeof assignment.monthlyPlans
          ];

        const employeePlanId = currentMonthlyPlan?.employeePlanId;
        const monthValue = monthConfig.value;

        // Extract the actual employeePositionId from composite key
        const actualPositionId = getActualPositionId(
          assignment.employeePositionId,
        );

        const employeePlanData: ExtendedEmployeePlanDto = {
          employeePositionId: actualPositionId,
          planId: planId,
          serviceId: assignment.service.serviceId || undefined,
          planType:
            selectedPlanType === "percent" ? "percent" : selectedPlanType,
          expectedQuantity: newValue,
          month: monthValue,
          timeframe: selectedTimeframe,
        };

        if (employeePlanId && newValue > 0) {
          // UPDATE existing plan (PUT)
          return update.mutateAsync({
            ...employeePlanData,
            id: employeePlanId,
          });
        } else if (!employeePlanId && newValue > 0) {
          // CREATE new plan (POST)
          return create.mutateAsync(employeePlanData);
        } else if (employeePlanId && newValue === 0) {
          // UPDATE to 0 (PUT)
          return update.mutateAsync({
            ...employeePlanData,
            id: employeePlanId,
          });
        }
        return Promise.resolve(); // Skip if no action needed
      });

      // Wait for all promises to resolve
      await Promise.allSettled(promises);

      // Invalidate the query cache (refetch will happen automatically in background)
      queryClient.invalidateQueries({
        queryKey: EMPLOYEE_PLAN_KEYS.planId(planId),
      });

      toast({
        title: t("common.success", "Success"),
        description: t(
          "employeePlans.planAssignments.allMonthlyTargetsUpdated",
        ),
        variant: "default",
      });
    } catch (error) {
      console.error("Failed to save bulk edit:", error);

      // ROLLBACK: Revert the optimistic update
      setAssignments((prev) =>
        prev.map((a) => {
          if (a.employeePositionId === employeePositionId) {
            const totalPlanned = Object.values(previousMonthlyPlans).reduce(
              (sum, plan) => sum + plan.planned,
              0,
            );

            return {
              ...a,
              monthlyPlans: previousMonthlyPlans,
              totalPlanned,
            };
          }
          return a;
        }),
      );

      // Restore edit mode on error
      setBulkEditStates((prev) => ({
        ...prev,
        [employeePositionId]: { ...prev[employeePositionId], isEditing: true },
      }));

      toast({
        title: t("common.error", "Error"),
        description: t("employeePlans.planAssignments.failedToUpdateTargets"),
        variant: "destructive",
      });
    }
  };
  // Cancel bulk edit
  const cancelBulkEdit = (employeePositionId: string) => {
    setBulkEditStates((prev) => ({
      ...prev,
      [employeePositionId]: { ...prev[employeePositionId], isEditing: false },
    }));
  };

  // Quick set functions
  const quickSetForAllMonths = (employeePositionId: string, value: number) => {
    const newInputs: { [key: string]: number } = {};
    dynamicMonthsConfig.forEach((month) => {
      newInputs[month.key] = value;
    });

    setBulkEditStates((prev) => ({
      ...prev,
      [employeePositionId]: {
        ...prev[employeePositionId],
        monthlyInputs: newInputs,
      },
    }));
  };

  // Calculate total for bulk edit
  const calculateBulkEditTotal = (employeePositionId: string) => {
    const state = bulkEditStates[employeePositionId];
    if (!state) return 0;
    return Object.values(state.monthlyInputs).reduce(
      (sum, val) => sum + val,
      0,
    );
  };

  if (error) {
    return (
      <div className="p-6">
        <Card className="border-red-200 bg-red-50">
          <CardContent className="pt-6">
            <div className="text-center">
              <h3 className="text-lg font-semibold text-red-700">
                {t("employeePlans.planAssignments.errorLoadingAssignments")}
              </h3>
              <p className="text-red-600 mt-2">
                {t("employeePlans.planAssignments.failedToLoadAssignments")}
              </p>
              <Button onClick={() => refetch()} className="mt-4">
                {t("employeePlans.planAssignments.retry")}
              </Button>
              <Button
                variant="outline"
                onClick={() =>
                  navigate(`/performance-management/${yearId}/employee-plans`)
                }
                className="mt-4 ml-4"
              >
                <ArrowLeft className="h-4 w-4 mr-2" />
                {t("employeePlans.planAssignments.backToPlans")}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6">
      {/* Direct reports panel — refreshes automatically when the user
          switches position via the global PositionSelect dropdown. */}
      <MyTeamPanel />

      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            size="sm"
            onClick={() => navigate(`/performance-management/${yearId}/plans`)}
            className="gap-2"
          >
            <ArrowLeft className="h-4 w-4" />
            Back to Plans
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">
              Plan Assignments -{" "}
              {planData?.data?.name
                ? localizedName(planData.data.name)
                : "Unnamed Plan"}
            </h1>
            <p className="text-gray-600 mt-1">
              Manage monthly performance targets for assigned employees
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          {/* Plan Type Selector */}
          <Select
            value={selectedPlanType}
            onValueChange={(value: "number" | "percent") =>
              setSelectedPlanType(value)
            }
          >
            <SelectTrigger className="w-[120px]">
              <SelectValue
                placeholder={t("employeePlans.planAssignments.planType")}
              />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="number">
                <div className="flex items-center gap-2">
                  <Hash className="h-4 w-4" />
                  {t("employeePlans.planAssignments.number")}
                </div>
              </SelectItem>
              <SelectItem value="percent">
                <div className="flex items-center gap-2">
                  <Percent className="h-4 w-4" />
                  {t("employeePlans.planAssignments.percent")}
                </div>
              </SelectItem>
            </SelectContent>
          </Select>

          {/* Timeframe Selector */}
          <Select
            value={selectedTimeframe}
            onValueChange={(
              value: "yearly" | "quarterly" | "monthly" | "weekly" | "daily",
            ) => setSelectedTimeframe(value)}
          >
            <SelectTrigger className="w-[120px]">
              <SelectValue
                placeholder={t("employeePlans.planAssignments.timeframe")}
              />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="yearly">
                <div className="flex items-center gap-2">
                  <Calendar className="h-4 w-4" />
                  {t("employeePlans.planAssignments.yearly")}
                </div>
              </SelectItem>
              <SelectItem value="quarterly">
                <div className="flex items-center gap-2">
                  <CalendarDays className="h-4 w-4" />
                  {t("employeePlans.planAssignments.quarterly")}
                </div>
              </SelectItem>
              <SelectItem value="monthly">
                <div className="flex items-center gap-2">
                  <CalendarDays className="h-4 w-4" />
                  {t("employeePlans.planAssignments.monthly")}
                </div>
              </SelectItem>
              <SelectItem value="weekly">
                <div className="flex items-center gap-2">
                  <Clock4 className="h-4 w-4" />
                  {t("employeePlans.planAssignments.weekly")}
                </div>
              </SelectItem>
              <SelectItem value="daily">
                <div className="flex items-center gap-2">
                  <Clock className="h-4 w-4" />
                  {t("employeePlans.planAssignments.daily")}
                </div>
              </SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>
      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">
                  {t("employeePlans.planAssignments.assignedEmployees")}
                </p>
                <p className="text-2xl font-bold">{assignments.length}</p>
              </div>
              <div className="p-2 bg-purple-100 rounded-lg">
                <Users className="h-6 w-6 text-purple-600" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">
                  {t("employeePlans.planAssignments.totalPlanned")}
                </p>
                <p className="text-2xl font-bold">
                  {assignments.reduce((sum, emp) => sum + emp.totalPlanned, 0)}
                </p>
              </div>
              <div className="p-2 bg-blue-100 rounded-lg">
                <Target className="h-6 w-6 text-blue-600" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">
                  {t("employeePlans.planAssignments.planType")}
                </p>
                <div className="mt-1">
                  <Badge variant="outline" className="font-medium">
                    {selectedPlanType === "number"
                      ? t("employeePlans.planAssignments.number")
                      : t("employeePlans.planAssignments.percent")}
                  </Badge>
                </div>
              </div>
              <div className="p-2 bg-green-100 rounded-lg">
                {selectedPlanType === "number" ? (
                  <Hash className="h-6 w-6 text-primary-600" />
                ) : (
                  <Percent className="h-6 w-6 text-primary-600" />
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">
                  {t("employeePlans.planAssignments.timeframe")}
                </p>
                <div className="mt-1">
                  <Badge variant="outline" className="font-medium capitalize">
                    {t(`employeePlans.planAssignments.${selectedTimeframe}`)}
                  </Badge>
                </div>
              </div>
              <div className="p-2 bg-yellow-100 rounded-lg">
                <Calendar className="h-6 w-6 text-yellow-600" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card className="mb-6">
        <CardContent className="pt-6">
          <div className="flex flex-col md:flex-row gap-4 items-end">
            <div className="flex-1">
              <Label>{t("employeePlans.planAssignments.search")}</Label>
              <div className="relative mt-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <Input
                  placeholder={t(
                    "employeePlans.planAssignments.searchPlaceholder",
                  )}
                  className="pl-10"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            </div>

            <div>
              <Label>{t("employeePlans.planAssignments.service")}</Label>
              <Select
                value={selectedService}
                onValueChange={setSelectedService}
              >
                <SelectTrigger className="w-[200px] mt-1">
                  <SelectValue
                    placeholder={t("employeePlans.planAssignments.allServices")}
                  />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">
                    {t("employeePlans.planAssignments.allServices")}
                  </SelectItem>
                  {allServices.map((serviceId) => (
                    <SelectItem key={serviceId!} value={serviceId!}>
                      {localizedName(
                        assignments.find(
                          (a) => a.service.serviceId === serviceId,
                        )?.service.serviceName || undefined,
                      ) || serviceId}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>
      {/* Main Table */}
      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-purple-600" />
          <span className="ml-2 text-gray-600">
            {t("employeePlans.planAssignments.loadingAssignments")}
          </span>
        </div>
      ) : filteredAssignments.length === 0 ? (
        <Card className="border-dashed">
          <CardContent className="pt-12 pb-12 text-center">
            <Users className="h-12 w-12 mx-auto text-gray-400 mb-4" />
            <h3 className="text-lg font-semibold text-gray-900">
              {t("employeePlans.planAssignments.noEmployeeAssignments")}
            </h3>
            <p className="text-gray-600 mt-2 mb-6 max-w-md mx-auto">
              {searchTerm
                ? t("employeePlans.planAssignments.noEmployeesMatch")
                : t("employeePlans.planAssignments.noEmployeesAssigned")}
            </p>
          </CardContent>
        </Card>
      ) : (
        <Card className="overflow-hidden">
          <CardHeader>
            <div className="flex justify-between items-center">
              <div>
                <CardTitle>
                  {t("employeePlans.planAssignments.monthlyPerformanceTargets")}
                </CardTitle>
                <CardDescription>
                  {t("employeePlans.planAssignments.clickToEdit")}
                </CardDescription>
              </div>
              <div className="flex items-center gap-2">
                <Badge variant="outline" className="font-medium">
                  {filteredAssignments.length}{" "}
                  {t("employeePlans.planAssignments.employees")}
                </Badge>
                <Badge className="bg-blue-100 text-blue-800 border-blue-200">
                  {selectedPlanType === "number"
                    ? t("employeePlans.planAssignments.number")
                    : t("employeePlans.planAssignments.percent")}{" "}
                  {t("employeePlans.planAssignments.targets")}
                </Badge>
              </div>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            <div className="relative overflow-auto max-h-[600px]">
              <div className="min-w-[1500px] sticky top-0">
                <Table>
                  <TableHeader className="sticky top-0 bg-white z-10 shadow-sm">
                    <TableRow>
                      <TableHead className="w-[250px] sticky left-0 bg-white z-20">
                        {t("employeePlans.planAssignments.employee")}
                      </TableHead>
                      <TableHead className="w-[200px]">
                        {t("employeePlans.planAssignments.service")}
                      </TableHead>
                      <TableHead className="text-center w-[100px]">
                        {t("employeePlans.planAssignments.total")}
                      </TableHead>
                      <TableHead className="text-center w-[100px]">
                        {t("employeePlans.planAssignments.status")}
                      </TableHead>
                      {dynamicMonthsConfig.map((month) => (
                        <TableHead
                          key={month.key}
                          className="text-center min-w-[100px]"
                        >
                          <div className="flex flex-col items-center">
                            <span className="text-xs font-medium">
                              {month.abbr}
                            </span>
                            <span className="text-xs text-gray-500">
                              {t(
                                `employeePlans.planAssignments.months.${month.key}`,
                              )}
                            </span>
                          </div>
                        </TableHead>
                      ))}
                      <TableHead className="text-right w-[150px] sticky right-0 bg-white z-20">
                        {t("employeePlans.planAssignments.actions")}
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredAssignments.map((assignment) => {
                      const isBulkEditing =
                        bulkEditStates[assignment.employeePositionId]
                          ?.isEditing;
                      const monthlyData =
                        calculateEmployeeMonthlyData(assignment);
                      const isExpanded = expandedRows.has(
                        assignment.employeePositionId,
                      );

                      return (
                        <>
                          {/* Main Employee Row */}
                          <TableRow
                            key={assignment.employeePositionId}
                            className="hover:bg-gray-50"
                          >
                            <TableCell className="sticky left-0 bg-white z-10">
                              <div className="flex items-center gap-3">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-6 w-6 p-0"
                                  onClick={() =>
                                    toggleRowExpansion(
                                      assignment.employeePositionId,
                                    )
                                  }
                                >
                                  <ChevronDown
                                    className={`h-4 w-4 transition-transform ${
                                      isExpanded ? "rotate-180" : ""
                                    }`}
                                  />
                                </Button>
                                <div className="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center">
                                  <span className="text-purple-600 font-medium">
                                    {localizedName(
                                      assignment.employeeName,
                                    ).charAt(0)}
                                  </span>
                                </div>
                                <div>
                                  <p className="font-medium text-gray-900">
                                    {localizedName(assignment.employeeName)}
                                  </p>
                                  <p className="text-sm text-gray-500">
                                    ID: {assignment.employeeId}
                                  </p>
                                </div>
                              </div>
                            </TableCell>
                            <TableCell>
                              <div className="flex flex-col">
                                <span className="font-medium text-gray-900">
                                  {localizedName(
                                    assignment.service.serviceName || undefined,
                                  ) ||
                                    t(
                                      "employeePlans.planAssignments.noService",
                                    )}
                                </span>
                                {assignment.service.serviceDescription && (
                                  <span className="text-sm text-gray-500 truncate max-w-[180px]">
                                    {localizedName(
                                      assignment.service.serviceDescription ||
                                        undefined,
                                    )}
                                  </span>
                                )}
                              </div>
                            </TableCell>
                            <TableCell className="text-center">
                              <div
                                className={cn(
                                  "font-bold",
                                  isBulkEditing
                                    ? "text-blue-600"
                                    : "text-gray-900",
                                )}
                              >
                                {isBulkEditing
                                  ? calculateBulkEditTotal(
                                      assignment.employeePositionId,
                                    )
                                  : assignment.totalPlanned}
                              </div>
                            </TableCell>
                            <TableCell className="text-center">
                              <Badge
                                variant="outline"
                                className={
                                  assignment.employeeStatus === "active"
                                    ? "bg-green-50 text-primary-700 border-green-200"
                                    : assignment.employeeStatus === "pending"
                                      ? "bg-yellow-50 text-yellow-700 border-yellow-200"
                                      : "bg-gray-50 text-gray-700 border-gray-200"
                                }
                              >
                                {assignment.employeeStatus}
                              </Badge>
                            </TableCell>
                            {/* Monthly Target Cells */}
                            {dynamicMonthsConfig.map((monthConfig) => {
                              const monthKey = monthConfig.key;
                              const isEditingCell =
                                editingCell?.employeePositionId ===
                                  assignment.employeePositionId &&
                                editingCell?.monthKey === monthKey;

                              const monthlyPlan =
                                assignment.monthlyPlans[
                                  monthKey as keyof typeof assignment.monthlyPlans
                                ];

                              const displayValue = monthlyPlan?.planned || 0;
                              const hasPlanId = !!monthlyPlan?.employeePlanId;

                              return (
                                <TableCell
                                  key={monthKey}
                                  className="text-center p-1 relative group"
                                  onClick={() =>
                                    !isBulkEditing &&
                                    !isEditingCell &&
                                    startCellEdit(
                                      assignment.employeePositionId,
                                      monthKey,
                                      displayValue,
                                    )
                                  }
                                  title={`Month: ${monthConfig.value} (${
                                    monthConfig.name
                                  }) ${
                                    hasPlanId ? "✓ Has Plan ID" : "No Plan ID"
                                  }`}
                                >
                                  {isEditingCell ? (
                                    <div className="flex items-center justify-center gap-1">
                                      <div className="absolute -top-1 left-1 text-xs text-gray-500">
                                        {monthConfig.value}
                                        {hasPlanId && (
                                          <span className="text-green-500 ml-1">
                                            ✓
                                          </span>
                                        )}
                                      </div>
                                      <Input
                                        type="number"
                                        min="0"
                                        value={editingCell.value}
                                        onChange={(e) =>
                                          setEditingCell((prev) =>
                                            prev
                                              ? {
                                                  ...prev,
                                                  value: e.target.value,
                                                }
                                              : null,
                                          )
                                        }
                                        className="h-8 w-20 text-center"
                                        autoFocus
                                        onKeyDown={(e) => {
                                          if (e.key === "Enter") saveCellEdit();
                                          if (e.key === "Escape")
                                            setEditingCell(null);
                                        }}
                                      />
                                      <Button
                                        size="sm"
                                        variant="ghost"
                                        className="h-6 w-6 p-0"
                                        onClick={saveCellEdit}
                                      >
                                        <Check className="h-3 w-3" />
                                      </Button>
                                    </div>
                                  ) : isBulkEditing ? (
                                    <div className="relative">
                                      <div className="absolute -top-1 left-1 text-xs text-gray-500">
                                        {monthConfig.value}
                                        {hasPlanId && (
                                          <span className="text-green-500 ml-1">
                                            ✓
                                          </span>
                                        )}
                                      </div>
                                      <Input
                                        type="number"
                                        min="0"
                                        value={
                                          bulkEditStates[
                                            assignment.employeePositionId
                                          ]?.monthlyInputs[monthKey] ||
                                          displayValue
                                        }
                                        onChange={(e) =>
                                          updateBulkEditInput(
                                            assignment.employeePositionId,
                                            monthKey,
                                            e.target.value,
                                          )
                                        }
                                        className="h-8 w-20 text-center"
                                      />
                                    </div>
                                  ) : (
                                    <div
                                      className={cn(
                                        "font-medium px-3 py-1.5 rounded cursor-pointer hover:bg-gray-100 transition-colors relative",
                                        hasPlanId
                                          ? "text-primary-700 bg-green-50 border border-green-200"
                                          : displayValue > 0
                                            ? "text-blue-700 bg-blue-50 border border-blue-200"
                                            : "text-gray-400 italic",
                                      )}
                                    >
                                      <div className="absolute -top-1 left-1 text-xs text-gray-500 flex items-center">
                                        {monthConfig.value}
                                        {hasPlanId && (
                                          <span
                                            className="text-green-500 ml-1"
                                            title={`Plan ID: ${monthlyPlan.employeePlanId}`}
                                          >
                                            ✓
                                          </span>
                                        )}
                                      </div>
                                      {displayValue}
                                      {hasPlanId && (
                                        <div className="absolute -bottom-1 right-1">
                                          <Badge
                                            variant="outline"
                                            className="h-4 text-[10px] px-1 py-0 bg-green-100 text-primary-700 border-green-300"
                                          >
                                            ✓
                                          </Badge>
                                        </div>
                                      )}
                                    </div>
                                  )}
                                </TableCell>
                              );
                            })}
                            <TableCell className="text-right sticky right-0 bg-white z-10">
                              {isBulkEditing ? (
                                <div className="flex gap-1 justify-end">
                                  <Button
                                    size="sm"
                                    variant="default"
                                    onClick={() =>
                                      saveBulkEdit(
                                        assignment.employeePositionId,
                                      )
                                    }
                                    disabled={
                                      create.isPending || update.isPending
                                    }
                                    className="h-8"
                                  >
                                    {create.isPending || update.isPending ? (
                                      <Loader2 className="h-4 w-4 animate-spin" />
                                    ) : (
                                      <Save className="h-4 w-4" />
                                    )}
                                  </Button>
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() =>
                                      cancelBulkEdit(
                                        assignment.employeePositionId,
                                      )
                                    }
                                    className="h-8"
                                  >
                                    <X className="h-4 w-4" />
                                  </Button>
                                </div>
                              ) : (
                                <div className="flex gap-1 justify-end">
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() => startBulkEdit(assignment)}
                                    className="h-8"
                                  >
                                    <Edit2 className="h-4 w-4 mr-1" />
                                    {t("employeePlans.planAssignments.editAll")}
                                  </Button>
                                  <DropdownMenu>
                                    <DropdownMenuTrigger asChild>
                                      <Button
                                        size="sm"
                                        variant="ghost"
                                        className="h-8 w-8 p-0"
                                      >
                                        <MoreHorizontal className="h-4 w-4" />
                                      </Button>
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent align="end">
                                      <DropdownMenuLabel>
                                        {t(
                                          "employeePlans.planAssignments.quickSet",
                                        )}
                                      </DropdownMenuLabel>
                                      <DropdownMenuItem
                                        onClick={() =>
                                          quickSetForAllMonths(
                                            assignment.employeePositionId,
                                            100,
                                          )
                                        }
                                      >
                                        {t(
                                          "employeePlans.planAssignments.setAll",
                                        )}{" "}
                                        100
                                      </DropdownMenuItem>
                                      <DropdownMenuItem
                                        onClick={() =>
                                          quickSetForAllMonths(
                                            assignment.employeeId,
                                            50,
                                          )
                                        }
                                      >
                                        {t(
                                          "employeePlans.planAssignments.setHalf",
                                        )}
                                      </DropdownMenuItem>
                                      <DropdownMenuItem
                                        onClick={() =>
                                          quickSetForAllMonths(
                                            assignment.employeeId,
                                            0,
                                          )
                                        }
                                      >
                                        {t(
                                          "employeePlans.planAssignments.clearAll",
                                        )}
                                      </DropdownMenuItem>
                                      <DropdownMenuSeparator />
                                      <DropdownMenuItem className="text-red-600">
                                        <Trash2 className="h-4 w-4 mr-2" />
                                        {t(
                                          "employeePlans.planAssignments.removeAssignment",
                                          "Remove Assignment",
                                        )}
                                      </DropdownMenuItem>
                                    </DropdownMenuContent>
                                  </DropdownMenu>
                                </div>
                              )}
                            </TableCell>
                          </TableRow>

                          {/* Bulk Edit Controls Row (only shows during bulk edit) */}
                          {isBulkEditing && (
                            <TableRow className="bg-blue-50">
                              <TableCell
                                colSpan={4}
                                className="text-right font-medium"
                              >
                                Quick Set:
                              </TableCell>
                              <TableCell colSpan={13} className="p-2">
                                <div className="flex items-center gap-2">
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() =>
                                      quickSetForAllMonths(
                                        assignment.employeeId,
                                        100,
                                      )
                                    }
                                    className="h-7"
                                  >
                                    100
                                  </Button>
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() =>
                                      quickSetForAllMonths(
                                        assignment.employeeId,
                                        50,
                                      )
                                    }
                                    className="h-7"
                                  >
                                    50
                                  </Button>
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() =>
                                      quickSetForAllMonths(
                                        assignment.employeeId,
                                        25,
                                      )
                                    }
                                    className="h-7"
                                  >
                                    25
                                  </Button>
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() =>
                                      quickSetForAllMonths(
                                        assignment.employeeId,
                                        0,
                                      )
                                    }
                                    className="h-7"
                                  >
                                    Clear
                                  </Button>
                                  <div className="flex-1"></div>
                                  <span className="text-sm font-medium text-blue-700">
                                    Total:{" "}
                                    {calculateBulkEditTotal(
                                      assignment.employeeId,
                                    )}
                                  </span>
                                </div>
                              </TableCell>
                            </TableRow>
                          )}

                          {/* Expanded Row - Monthly Details */}
                          {isExpanded && (
                            <TableRow className="bg-gray-50">
                              <TableCell colSpan={17} className="p-0">
                                <div className="p-4">
                                  <div className="overflow-x-auto">
                                    <Table>
                                      <TableHeader>
                                        <TableRow>
                                          <TableHead className="w-[100px]">
                                            Month
                                          </TableHead>
                                          <TableHead className="text-right">
                                            Planned Target
                                          </TableHead>
                                          <TableHead className="text-right">
                                            Actual Executed
                                          </TableHead>
                                          <TableHead className="text-right">
                                            Variance
                                          </TableHead>
                                          <TableHead className="text-right">
                                            Completion Rate
                                          </TableHead>
                                        </TableRow>
                                      </TableHeader>
                                      <TableBody>
                                        {monthlyData.map((month) => (
                                          <TableRow key={month.month}>
                                            <TableCell className="font-medium">
                                              {month.month} ({month.monthAbbr})
                                            </TableCell>
                                            <TableCell className="text-right">
                                              {month.planned}
                                            </TableCell>
                                            <TableCell className="text-right">
                                              {month.executed}
                                            </TableCell>
                                            <TableCell className="text-right">
                                              <span
                                                className={`px-2 py-1 rounded text-xs ${
                                                  month.variance > 0
                                                    ? "bg-green-100 text-primary-700"
                                                    : month.variance < 0
                                                      ? "bg-red-100 text-red-700"
                                                      : "bg-gray-100 text-gray-700"
                                                }`}
                                              >
                                                {month.variance > 0 ? "+" : ""}
                                                {month.variance}
                                              </span>
                                            </TableCell>
                                            <TableCell className="text-right">
                                              <span
                                                className={`px-2 py-1 rounded text-xs ${
                                                  month.completionRate >= 90
                                                    ? "bg-green-100 text-primary-700"
                                                    : month.completionRate >= 70
                                                      ? "bg-yellow-100 text-yellow-700"
                                                      : month.completionRate >=
                                                          50
                                                        ? "bg-orange-100 text-orange-700"
                                                        : "bg-red-100 text-red-700"
                                                }`}
                                              >
                                                {Math.round(
                                                  month.completionRate,
                                                )}
                                                %
                                              </span>
                                            </TableCell>
                                          </TableRow>
                                        ))}
                                      </TableBody>
                                    </Table>
                                  </div>
                                </div>
                              </TableCell>
                            </TableRow>
                          )}
                        </>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default EmployeePlanAssignmentsPage;
