import { useState, useMemo, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  DownloadIcon,
  EditIcon,
  TrashIcon,
  EyeIcon,
  PlusIcon,
  ArrowLeft,
  Building2,
  Target,
  Users,
  RefreshCw,
  BarChart3,
  Send,
  Calendar,
  FolderTree,
  Clock,
  CalendarDays,
  Layers,
} from "lucide-react";
import { motion } from "framer-motion";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { Plan } from "../../types/planTypes";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { useToast } from "@/shared/common/ui/use-toast";
import { ColumnDef } from "@tanstack/react-table";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { Button } from "@/shared/common/ui/button";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { Badge } from "@/shared/common/ui/badge";

import {
  usePlanList,
  usePlanMutations,
  checkIsUnitAdmin,
  useMinePlan,
  usePlan,
} from "@/performance-management/hooks/usePlans";
import {
  usePlanYearById,
  usePlanYears,
} from "@/performance-management/hooks/usePlanYear";
import { useUnitContext } from "@/shared/context/UnitContext";
import { useAuth } from "@/shared/context/AuthContext";
import { useLocalizedName } from "@/shared/common/localizedName";
import { PlanYear } from "@/performance-management/types/planYearTypes";
import { getUserPositionType } from "@/performance-management/utils/positionTypeUtils";
import { EPositionTypeKey, MeDto } from "@/shared/dto/user/meDto";
import { useUserDetail } from "@/record-management/components/hooks/useUserDetail";
import { useAuthUser } from "@/record-management/hooks/useAuthUser";
import { useTranslation } from "react-i18next";
import { TimeFrame } from "@/performance-management/utils/shared-field-types";

interface PlanTableProps {
  useMinePlans?: boolean;
}

const PlanTable = ({ useMinePlans = false }: PlanTableProps) => {
  const navigate = useNavigate();
  const { toast } = useToast();
  const { t } = useTranslation();
  const { yearId, positionId, planId, planFor } = useParams<{
    yearId?: string;
    positionId?: string;
    planId?: string;
    planFor?: string;
  }>();

  // Support both year numbers (2024) and UUIDs for backward compatibility
  const { data: planYearData } = usePlanYearById(yearId as string);

  // Get the year number for display (works with both UUID and year number)
  const displayYear = planYearData?.data?.year || yearId;
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState<Plan | null>(null);
  const [pageIndex, setPageIndex] = useState(0);
  const { user, selectedPositionId } = useAuth();
  const localizedName = useLocalizedName();
  const { userDetails } = useAuthUser();
  const { permissionKeys } = useUserDetail(userDetails as MeDto);
  const isInitiator = permissionKeys?.includes("can:initiatePlan");

  const organizationId =
    user?.employee?.length && user.employee.length > 0
      ? user.employee[0].organizationId
      : undefined;

  const unitContext = useUnitContext();
  const unitsQuery = unitContext?.getList(organizationId!, {
    take: 300,
    skip: 0,
  });
  const unitId = unitsQuery?.data?.data?.items?.[0]?.id ?? "";

  // Get the current year from planYearData
  const currentYear = planYearData?.data?.year || "N/A";

  // Resolve the active position by matching the globally-selected employeePositionId.
  // Falls back to the user's first position when none has been selected yet.
  const currentPositionId = useMemo(() => {
    const allPositions =
      user?.employee?.flatMap((emp) => emp.positions ?? []) ?? [];
    if (selectedPositionId) {
      const active = allPositions.find(
        (p) =>
          p.employeePositionId === selectedPositionId ||
          p.id === selectedPositionId,
      );
      if (active?.id) return active.id;
    }
    return allPositions[0]?.id ?? "";
  }, [user, selectedPositionId]);

  // Reflect the effective positionId in the URL so it's never undefined on the plans-table route
  useEffect(() => {
    if (useMinePlans) return;
    if (positionId) return;
    if (!currentPositionId || !yearId) return;

    const path = planId
      ? `/performance-management/${yearId}/plans-table/${currentPositionId}/${planId}${
          planFor ? `/${planFor}` : ""
        }`
      : `/performance-management/${yearId}/plans-table/${currentPositionId}`;

    navigate(path, { replace: true });
  }, [
    useMinePlans,
    positionId,
    currentPositionId,
    yearId,
    planId,
    planFor,
    navigate,
  ]);

  // Check if user is unit admin
  const isUnitAdmin = useMemo(() => checkIsUnitAdmin(user), [user]);

  // Check if user is deputy
  const isDeputy = useMemo(() => {
    return getUserPositionType(user) === EPositionTypeKey.DEPUTY;
  }, [user]);

  // Build params based on role, year filter, and positionId from URL
  const planParams = useMemo(() => {
    const baseParams: Record<string, string> = {
      orderBy: "createdAt:DESC",
    };

    if (yearId) {
      baseParams.planYearId = yearId;
    }

    // Use positionId from URL, falling back to the logged-in user's positionId
    const effectivePositionId = positionId || currentPositionId;
    if (effectivePositionId) {
      baseParams.positionId = effectivePositionId;
    }

    if (planFor) {
      baseParams.planFor = planFor;
    }
    if (planId) {
      baseParams.parentPlanId = planId;
    }

    return Object.keys(baseParams).length > 0 ? baseParams : undefined;
  }, [yearId, positionId, currentPositionId, planFor, planId]);

  const minePlanParams = useMemo(() => {
    const basicParams: Record<string, string> = {
      orderBy: "createdAt:DESC",
    };
    if (yearId) {
      basicParams.planYearId = yearId;
    }
    if (planId) {
      basicParams.parentPlanId = planId;
    }
    return Object.keys(basicParams).length > 0 ? basicParams : undefined;
  }, [yearId, planId]);

  const {
    data: minePlanData,
    isLoading: isMinePlanLoading,
    isError: isMinePlanError,
    error: minePlanError,
    refetch: refetchMinePlan,
  } = useMinePlan(minePlanParams);

  // On the /my-plans route, fall back to /plans/list/{currentPositionId} when /plans/mine
  // finishes loading and returns no items.
  const minePlansEmpty =
    useMinePlans &&
    !isMinePlanLoading &&
    !isMinePlanError &&
    !!minePlanData &&
    (minePlanData?.data?.items?.length ?? 0) === 0;

  const {
    data: planListData,
    isLoading: isPlanListLoading,
    isError: isPlanListError,
    error: planListError,
    refetch: refetchPlanList,
  } = usePlanList(
    useMinePlans
      ? minePlansEmpty
        ? currentPositionId
        : ""
      : positionId || currentPositionId,
    useMinePlans ? (minePlansEmpty ? planParams : undefined) : planParams,
  );

  // On /my-plans: prefer mine results, fall back to list results when mine is empty.
  const data = useMinePlans
    ? minePlansEmpty
      ? planListData
      : minePlanData
    : planListData;
  const isLoading = useMinePlans
    ? isMinePlanLoading || (minePlansEmpty && isPlanListLoading)
    : isPlanListLoading;
  const isError = useMinePlans
    ? isMinePlanError || (minePlansEmpty && isPlanListError)
    : isPlanListError;
  const error = useMinePlans
    ? minePlansEmpty
      ? planListError
      : minePlanError
    : planListError;
  const refetch = useMinePlans
    ? () => {
        refetchMinePlan();
        if (minePlansEmpty) refetchPlanList();
      }
    : refetchPlanList;

  const plans = data?.data?.items?.length ? data.data.items : [];
  const { delete: deletePlan } = usePlanMutations();
  console.log("mine plans ", planListData);
  // Get parent plan info if planId exists and not in mine plans view
  const planIdForQuery = planId && !useMinePlans ? (planId as string) : "";
  console.log("planId for Query ", planIdForQuery);
  const { data: parentPlanData, isLoading: isParentPlanLoading } =
    usePlan(planIdForQuery);
  console.log("parentPlanData time frame", parentPlanData?.data.timeframe);
  // Helper function to format time frame
  const formatTimeFrame = (timeFrame: string) => {
    if (!timeFrame) return "N/A";

    const timeFrameMap: Record<string, string> = {
      [TimeFrame.YEAR]: "Yearly",
      [TimeFrame.QUARTER]: "Quarterly",
      [TimeFrame.MONTH]: "Monthly",
      [TimeFrame.WEEK]: "Weekly",
      [TimeFrame.DAY]: "Daily",
    };

    return (
      timeFrameMap[timeFrame] ||
      timeFrame.charAt(0).toUpperCase() + timeFrame.slice(1).replace("ly", "")
    );
  };
  console.log("first Plan ");
  // Get time frame for mine plans (check first plan's time frame if available)
  const minePlanTimeFrame = useMemo(() => {
    if (!useMinePlans || !plans.length) return null;
    const firstPlan = plans[0];
    return firstPlan.timeframe ? formatTimeFrame(firstPlan.timeframe) : null;
  }, [useMinePlans, plans]);

  console.log("minePlanTimeFrame", minePlanTimeFrame);
  // Get plan year info for mine plans - use yearId from params
  const minePlanYearInfo = useMemo(() => {
    if (!useMinePlans) return null;
    return currentYear;
  }, [useMinePlans, currentYear]);

  // Get quarter/month/week/day info for mine plans
  const minePlanPeriodInfo = useMemo(() => {
    if (!useMinePlans || !plans.length) return null;
    const firstPlan = plans[0];

    if (firstPlan.timeframe === TimeFrame.QUARTER && firstPlan.quarter) {
      return { type: "Quarter", value: firstPlan.quarter };
    } else if (firstPlan.timeframe === TimeFrame.MONTH && firstPlan.month) {
      return { type: "Month", value: firstPlan.month };
    } else if (firstPlan.timeframe === TimeFrame.WEEK && firstPlan.week) {
      return { type: "Week", value: firstPlan.week };
    } else if (firstPlan.timeframe === TimeFrame.DAY && firstPlan.day) {
      return { type: "Day", value: firstPlan.day };
    }

    return null;
  }, [useMinePlans, plans]);

  // Get quarter/month/week/day info for parent plan
  const parentPlanPeriodInfo = useMemo(() => {
    if (!parentPlanData?.data) return null;
    const parent = parentPlanData.data;

    if (parent.timeframe === TimeFrame.QUARTER && parent.quarter) {
      return { type: "Quarter", value: parent.quarter };
    } else if (parent.timeframe === TimeFrame.MONTH && parent.month) {
      return { type: "Month", value: parent.month };
    } else if (parent.timeframe === TimeFrame.WEEK && parent.week) {
      return { type: "Week", value: parent.week };
    } else if (parent.timeframe === TimeFrame.DAY && parent.day) {
      return { type: "Day", value: parent.day };
    }

    return null;
  }, [parentPlanData]);

  const handleNavigation = (item: Plan) => {
    let path = "";

    if (item.planFor === "team") {
      path = `/performance-management/${yearId}/employee-plans`;
    } else if (useMinePlans) {
      path = `/performance-management/${yearId}/plan/${item.id}/departments`;
    } else {
      path = `/performance-management/${yearId}/plan/${item.id}?positionId=${
        positionId || ""
      }`;
    }

    navigate(path);
  };

  const handleDelete = async () => {
    if (!selectedPlan) return;

    deletePlan.mutate(selectedPlan.id, {
      onSuccess: () => {
        setIsDeleteDialogOpen(false);
        setSelectedPlan(null);
        toast({
          title: t("planTable.success", "Success"),
          description: t(
            "planTable.planDeletedSuccessfully",
            "Plan deleted successfully",
          ),
          variant: "default",
        });
      },
      onError: (error) => {
        toast({
          title: t("planTable.error", "Error"),
          description:
            error.message ||
            t("planTable.failedToDeletePlan", "Failed to delete plan"),
          variant: "destructive",
        });
      },
    });
  };

  const columns: ColumnDef<Plan>[] = [
    {
      accessorKey: "name",
      header: t("planTable.planName"),
      size: 200,
      enableColumnFilter: true,
      enableSorting: true,
      cell: ({ row }) => (
        <div className="flex items-center space-x-3">
          <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-blue-500 rounded-xl flex items-center justify-center">
            <Target className="h-5 w-5 text-white" />
          </div>
          <div className="flex flex-col">
            <div className="font-semibold text-gray-900">
              {localizedName(row.original.name)}
            </div>
          </div>
        </div>
      ),
    },
    {
      accessorKey: "description",
      header: t("common.description", "Description"),
      size: 220,
      enableColumnFilter: true,
      enableSorting: false,
      cell: ({ row }) => (
        <div className="max-w-[200px]">
          <p className="text-sm text-gray-600 line-clamp-2">
            {localizedName(row.original.description) ||
              t("planTable.noDescription", "No description")}
          </p>
        </div>
      ),
    },

    {
      accessorKey: "weight",
      header: t("planTable.weight"),
      size: 140,
      enableColumnFilter: true,
      enableSorting: true,
      cell: ({ row }) => (
        <div className="flex items-center space-x-2">
          <Users className="h-4 w-4 text-gray-400" />
          <span className="text-sm font-medium truncate max-w-[100px]">
            {row.original.weight || "N/A"}
          </span>
        </div>
      ),
    },
    {
      accessorKey: "planFor",
      header: t("planTable.planFor", "Plan For"),
      size: 140,
      enableColumnFilter: true,
      enableSorting: true,
      cell: ({ row }) => (
        <div className="flex items-center space-x-2">
          <span className="text-sm font-medium truncate max-w-[100px]">
            {row.original.planFor || "N/A"}
          </span>
        </div>
      ),
    },
    {
      accessorKey: "timeframe",
      header: t("planTable.timeframe", "Time Frame"),
      size: 160,
      enableColumnFilter: true,
      enableSorting: true,
      cell: ({ row }) => {
        const plan = row.original;
        const timeframeValue = plan.timeframe?.toString() || "";
        const timeframeLabel = timeframeValue
          ? formatTimeFrame(timeframeValue)
          : "N/A";

        // Determine period info based on timeframe
        let periodInfo = "";
        if (timeframeValue === TimeFrame.QUARTER && plan.quarter) {
          periodInfo = ` - Q${plan.quarter}`;
        } else if (timeframeValue === TimeFrame.MONTH && plan.month) {
          periodInfo = ` - M${plan.month}`;
        } else if (timeframeValue === TimeFrame.WEEK && plan.week) {
          periodInfo = ` - W${plan.week}`;
        } else if (timeframeValue === TimeFrame.DAY && plan.day) {
          periodInfo = ` - D${plan.day}`;
        }

        return (
          <div className="flex items-center space-x-2">
            <Clock className="h-4 w-4 text-gray-400" />
            <span className="text-sm font-medium truncate max-w-[120px]">
              {timeframeLabel}
              {periodInfo && (
                <span className="text-xs text-blue-600 font-semibold">
                  {periodInfo}
                </span>
              )}
            </span>
          </div>
        );
      },
    },
    {
      accessorKey: "planType",
      header: t("planTable.planType"),
      size: 140,
      enableColumnFilter: true,
      enableSorting: true,
      cell: ({ row }) => (
        <div className="flex items-center space-x-2">
          <Building2 className="h-4 w-4 text-gray-400" />
          <span className="text-sm font-medium truncate max-w-[100px]">
            {row.original.planType || "N/A"}
          </span>
        </div>
      ),
    },
    {
      id: "actions",
      header: t("planTable.actions"),
      size: 160,
      cell: ({ row }) => (
        <div className="flex gap-2">
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  className="w-9 h-9 p-0 bg-blue-50 border-blue-200 text-blue-600 hover:bg-blue-100 hover:text-blue-700"
                  onClick={() => handleNavigation(row.original)}
                >
                  <EyeIcon className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>
                <p>{t("planTable.viewDetailsTooltip", "View details")}</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>

          {!useMinePlans && (
            <>
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant="outline"
                      size="sm"
                      className="w-9 h-9 p-0 bg-green-50 border-green-200 text-primary-600 hover:bg-primary-100 hover:text-primary-700"
                      onClick={() =>
                        navigate(
                          `/performance-management/${yearId}/plan/${row.original.id}/edit`,
                        )
                      }
                    >
                      <EditIcon className="h-4 w-4" />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>{t("planTable.editTooltip", "Edit")}</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>

              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant="outline"
                      size="sm"
                      className="w-9 h-9 p-0 bg-red-50 border-red-200 text-red-600 hover:bg-red-100 hover:text-red-700"
                      onClick={() => {
                        setSelectedPlan(row.original);
                        setIsDeleteDialogOpen(true);
                      }}
                      disabled={deletePlan.isPending}
                    >
                      <TrashIcon className="h-4 w-4" />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>{t("planTable.deleteTooltip", "Delete")}</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </>
          )}
        </div>
      ),
    },
  ];

  // Information Section Component
  const renderInformationSection = () => {
    if (useMinePlans) {
      return (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-100 rounded-2xl p-6 mb-8 shadow-sm"
        >
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
            <div className="flex items-start gap-4">
              <div className="w-12 h-12 bg-blue-100 rounded-2xl flex items-center justify-center">
                <CalendarDays className="h-6 w-6 text-blue-600" />
              </div>
              <div>
                <h3 className="text-lg font-semibold text-gray-900">
                  {t("planTable.planInformation")}
                </h3>
                <div className="flex flex-wrap gap-4 mt-3">
                  <div className="flex items-center gap-2">
                    <Calendar className="h-4 w-4 text-blue-500" />
                    <span className="text-sm font-medium text-gray-700">
                      {t("planTable.year")}:
                    </span>
                    <Badge className="bg-blue-100 text-blue-700 hover:bg-blue-200">
                      {minePlanYearInfo || "N/A"}
                    </Badge>
                  </div>
                  <div className="flex items-center gap-2">
                    <Clock className="h-4 w-4 text-purple-500" />
                    <span className="text-sm font-medium text-gray-700">
                      {t("planTable.timeframe")}
                    </span>
                    <Badge className="bg-purple-100 text-purple-700 hover:bg-purple-200">
                      {minePlanTimeFrame || "N/A"}
                    </Badge>
                  </div>
                  {minePlanPeriodInfo && (
                    <div className="flex items-center gap-2">
                      <CalendarDays className="h-4 w-4 text-indigo-500" />
                      <span className="text-sm font-medium text-gray-700">
                        {minePlanPeriodInfo.type}:
                      </span>
                      <Badge className="bg-indigo-100 text-indigo-700 hover:bg-indigo-200">
                        {minePlanPeriodInfo.value}
                      </Badge>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </motion.div>
      );
    }

    // For regular plan list with parent plan
    if (planId && parentPlanData) {
      return (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-100 rounded-2xl p-6 mb-8 shadow-sm"
        >
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
            <div className="flex items-start gap-4">
              <div className="w-12 h-12 bg-green-100 rounded-2xl flex items-center justify-center">
                <Layers className="h-6 w-6 text-primary-600" />
              </div>
              <div>
                <h3 className="text-lg font-semibold text-gray-900">
                  {t("planTable.parentInformation")}
                </h3>
                <div className="flex flex-wrap gap-4 mt-3">
                  <div className="flex items-center gap-2">
                    <FolderTree className="h-4 w-4 text-green-500" />
                    <span className="text-sm font-medium text-gray-700">
                      {t("planTable.parentPlan")}:
                    </span>
                    <Badge className="bg-green-100 text-primary-700 hover:bg-primary-200">
                      {localizedName(parentPlanData?.data?.name)}
                    </Badge>
                  </div>
                  <div className="flex items-center gap-2">
                    <Clock className="h-4 w-4 text-amber-500" />
                    <span className="text-sm font-medium text-gray-700">
                      {t("planTable.timeframe")}
                    </span>
                    <Badge className="bg-amber-100 text-amber-700 hover:bg-amber-200">
                      {parentPlanData?.data?.timeframe
                        ? formatTimeFrame(parentPlanData?.data.timeframe)
                        : "N/A"}
                    </Badge>
                  </div>
                  {parentPlanPeriodInfo && (
                    <div className="flex items-center gap-2">
                      <CalendarDays className="h-4 w-4 text-teal-500" />
                      <span className="text-sm font-medium text-gray-700">
                        {parentPlanPeriodInfo.type}:
                      </span>
                      <Badge className="bg-teal-100 text-teal-700 hover:bg-teal-200">
                        {parentPlanPeriodInfo.value}
                      </Badge>
                    </div>
                  )}
                  {yearId && (
                    <div className="flex items-center gap-2">
                      <Calendar className="h-4 w-4 text-blue-500" />
                      <span className="text-sm font-medium text-gray-700">
                        {t("planTable.year")}:
                      </span>
                      <Badge className="bg-blue-100 text-blue-700 hover:bg-blue-200">
                        {currentYear}
                      </Badge>
                    </div>
                  )}
                </div>
              </div>
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() =>
                navigate(`/performance-management/${yearId}/plan/${planId}`)
              }
              className="border-green-300 text-primary-700 hover:bg-green-50"
            >
              <EyeIcon className="h-4 w-4 mr-2" />
              {t("planTable.parentPlan")}
            </Button>
          </div>
        </motion.div>
      );
    }

    // For regular plan list without parent plan but with year info
    if (yearId && currentYear !== "N/A") {
      return (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-gradient-to-r from-purple-50 to-violet-50 border border-purple-100 rounded-2xl p-6 mb-8 shadow-sm"
        >
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 bg-purple-100 rounded-2xl flex items-center justify-center">
              <Calendar className="h-6 w-6 text-purple-600" />
            </div>
            <div>
              <div className="flex items-center gap-4 mt-3">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium text-gray-700">
                    {t("planTable.currentYear", "Current Year:")}
                  </span>
                  <Badge className="bg-purple-100 text-purple-700 hover:bg-purple-200">
                    {currentYear}
                  </Badge>
                </div>
              </div>
            </div>
          </div>
        </motion.div>
      );
    }

    return null;
  };

  const extraToolbar = (
    <div className="flex gap-3">
      {positionId && yearId && (
        <Button
          variant="outline"
          className="border-gray-300 text-gray-700 hover:bg-gray-50"
          onClick={() => navigate(`/performance-management/${yearId}/plans`)}
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          {t("planTable.back")}
        </Button>
      )}

      {yearId && !positionId && (
        <Button
          variant="outline"
          className="border-gray-300 text-gray-700 hover:bg-gray-50"
          onClick={() => navigate("/performance-management/plan-years")}
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          {t("planTable.backToPlanYears", "Back to Plan Years")}
        </Button>
      )}

      {(isUnitAdmin || isInitiator || (isDeputy && positionId)) && (
        <Button
          onClick={() => {
            navigate(
              planId
                ? `/performance-management/${yearId}/plans/new/${positionId}/${planId}`
                : `/performance-management/${yearId}/plans/new/${positionId}`,
              {
                state: {
                  from: "plan-table",
                  positionId: positionId || "",
                  yearId: yearId || "",
                  planId: planId || "",
                  planFor: planFor,
                },
              },
            );
          }}
          className="bg-gradient-to-r from-purple-500 to-violet-600 hover:from-purple-600 hover:to-violet-700 text-white shadow-lg shadow-purple-500/25"
        >
          <PlusIcon className="h-4 w-4 mr-2" />
          {t("planTable.createPlan", "Create Plan")}
        </Button>
      )}

      <Button
        variant="outline"
        onClick={() => {
          toast({
            title: t("planTable.exportStarted", "Export Started"),
            description: t(
              "planTable.preparingPlansData",
              "Preparing plans data for export...",
            ),
            variant: "default",
          });
        }}
        className="border-blue-200 text-blue-600 hover:bg-blue-50"
      >
        <DownloadIcon className="h-4 w-4 mr-2" />
        {t("planTable.exportAll", "Export All")}
      </Button>
    </div>
  );

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-6">
        <div className="max-w-7xl mx-auto space-y-6">
          {/* Information Section Skeleton */}
          <Skeleton className="h-32 bg-white/80 rounded-2xl" />

          {/* Header Skeleton */}
          <div className="flex justify-between items-center">
            <div className="space-y-3">
              <Skeleton className="h-8 w-64 bg-gray-300 rounded-xl" />
              <Skeleton className="h-4 w-96 bg-gray-300 rounded" />
            </div>
            <Skeleton className="h-10 w-32 bg-gray-300 rounded-xl" />
          </div>

          {/* Stats Skeleton */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
            {[...Array(4)].map((_, i) => (
              <Skeleton
                key={i}
                className="h-24 bg-white rounded-2xl shadow-sm"
              />
            ))}
          </div>

          {/* Table Skeleton */}
          <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50 p-6">
            <div className="space-y-4">
              <Skeleton className="h-12 w-full bg-gray-300 rounded-xl" />
              {[...Array(5)].map((_, i) => (
                <Skeleton
                  key={i}
                  className="h-16 w-full bg-gray-300 rounded-xl"
                />
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-6 flex items-center justify-center">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center bg-white/80 backdrop-blur-sm rounded-2xl p-8 shadow-lg border border-gray-200/50 max-w-md"
        >
          <div className="w-16 h-16 bg-red-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
            <BarChart3 className="h-8 w-8 text-red-500" />
          </div>
          <h3 className="text-xl font-semibold text-gray-900 mb-2">
            Error Loading Plans
          </h3>
          <p className="text-gray-600 mb-6">
            {error?.message || "Failed to load plans data. Please try again."}
          </p>
          <Button
            onClick={() => refetch()}
            className="bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600 text-white"
          >
            <RefreshCw className="h-4 w-4 mr-2" />
            {t("planTable.tryAgain", "Try Again")}
          </Button>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-4 sm:p-6">
      <div className="max-w-7xl mx-auto">
        {/* Information Section */}
        {renderInformationSection()}

        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex flex-col lg:flex-row justify-between items-start lg:items-center mb-8"
        >
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-transparent">
              {useMinePlans
                ? t("planTable.myPlans", "My Plans")
                : t("planTable.planManagement", "Plan Management")}
            </h1>
            
          </div>

          <div className="flex items-center gap-3 bg-white/80 backdrop-blur-sm rounded-2xl px-4 py-2 shadow-sm border border-gray-200 mt-4 lg:mt-0">
            <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
            <span className="text-sm font-medium text-gray-700">
              {plans.length}{" "}
              {plans.length === 1
                ? t("planTable.plan", "Plan")
                : t("planTable.plans", "Plans")}{" "}
              {t("planTable.total", "Total")}
            </span>
          </div>
        </motion.div>

        {/* Stats Cards */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="mb-8"
        >
          <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-gray-200/50 max-w-sm">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-gray-600 text-sm font-medium">
                  {t("planTable.totalPlansLabel", "Total Plans")}
                </p>
                <p className="text-3xl font-bold text-gray-900">
                  {plans.length}
                </p>
              </div>
              <div className="w-12 h-12 bg-blue-500/10 rounded-2xl flex items-center justify-center">
                <Target className="h-6 w-6 text-blue-500" />
              </div>
            </div>
          </div>
        </motion.div>

        {/* Table */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
        >
          <AdvancedTable<Plan, unknown>
            columns={columns}
            data={plans}
            tableName={
              useMinePlans
                ? t("planTable.myPlansTable", "My Plans")
                : t("planTable.performancePlansTable", "Performance Plans")
            }
            extraToolbar={extraToolbar}
            toolBarPosition="right"
            isLoading={isLoading}
            itemCount={plans.length}
            pageIndex={pageIndex}
            onPageChange={setPageIndex}
            nextFunction={() => setPageIndex((prev) => prev + 1)}
            prevFunction={() => setPageIndex((prev) => Math.max(0, prev - 1))}
            refresh={refetch}
          />
        </motion.div>

        {/* Delete Confirmation Dialog */}
        <AlertDialog
          open={isDeleteDialogOpen}
          onOpenChange={setIsDeleteDialogOpen}
        >
          <AlertDialogContent className="bg-white border-0 shadow-2xl rounded-2xl">
            <AlertDialogHeader>
              <div className="w-12 h-12 bg-red-100 rounded-2xl flex items-center justify-center mb-4">
                <TrashIcon className="h-6 w-6 text-red-500" />
              </div>
              <AlertDialogTitle className="text-xl font-bold text-gray-900">
                {t("planTable.confirmDeletion", "Confirm Deletion")}
              </AlertDialogTitle>
              <AlertDialogDescription className="text-gray-600">
                {t(
                  "planTable.deleteConfirmationMessage",
                  "Are you sure you want to delete the plan",
                )}{" "}
                "
                <span className="font-semibold text-gray-900">
                  {localizedName(selectedPlan?.name)}
                </span>
                "
                {t(
                  "planTable.deleteConfirmationWarning",
                  "? This action cannot be undone and all associated data will be permanently removed.",
                )}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel
                onClick={() => {
                  setIsDeleteDialogOpen(false);
                  setSelectedPlan(null);
                }}
                disabled={deletePlan.isPending}
                className="border-gray-300 text-gray-700 hover:bg-gray-50"
              >
                {t("planTable.cancel", "Cancel")}
              </AlertDialogCancel>
              <AlertDialogAction
                onClick={handleDelete}
                disabled={deletePlan.isPending}
                className="bg-gradient-to-r from-red-500 to-pink-600 hover:from-red-600 hover:to-pink-700 text-white shadow-lg shadow-red-500/25"
              >
                {deletePlan.isPending ? (
                  <>
                    <div className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent mr-2" />
                    {t("planTable.deleting", "Deleting...")}
                  </>
                ) : (
                  t("planTable.deletePlanButton", "Delete Plan")
                )}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    </div>
  );
};

export default PlanTable;
