import { useState, useMemo, useEffect } from "react";
import { useAuth } from "@/shared/context/AuthContext";
import { Button } from "@/shared/common/ui/button";
import {
  PlusIcon,
  Pencil,
  Trash2,
  Loader2,
  Calendar,
  Target,
  BarChart3,
  Clock,
  Hash,
  Percent,
  Table as TableIcon,
  Grid3x3,
  ArrowUpRight,
  Filter,
  Search,
  Download,
  Eye,
  EyeOff,
  TrendingUp,
  TrendingDown,
  CheckCircle,
  XCircle,
  AlertCircle,
  RefreshCw,
  MoreVertical,
  ChevronDown,
  ChevronUp,
  Users,
  Star,
  Award,
  Activity,
  Target as TargetIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } 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 { deleteEmployeePlan } from "@/performance-management/services/api/employeePlanService";
import { useLocalizedName } from "@/shared/common/localizedName";
import { format, differenceInDays, isWithinInterval } from "date-fns";
import { Badge } from "@/shared/common/ui/badge";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { useMinePlan } from "@/performance-management/hooks/usePlans";
import { EPositionTypeKey } from "@/shared/dto/user/meDto";
import { getSelectedPositionType } from "@/performance-management/utils/positionTypeUtils";
import {
  calculateAvailableMonths,
  monthsConfig,
} from "@/performance-management/utils/ethiopianMonthCalculator";
import { useMineEmployeePlan } from "@/performance-management/hooks/useEmployeePlan";
import { MyTeamPanel } from "./MyTeamPanel";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { Input } from "@/shared/common/ui/input";
import { Progress } from "@/shared/common/ui/progress";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/shared/common/ui/tabs";
import { Separator } from "@/shared/common/ui/separator";
import { cn } from "@/shared/lib/utils";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";

export interface EmployeePlan {
  createdAt: string;
  updatedAt: string | null;
  amharicCreatedAt: string;
  amharicUpdatedAt: string | null;
  id: string;
  startDate: string;
  amharicStartDate: string;
  endDate: string;
  amharicEndDate: string;
  employeePositionId: string;
  serviceId?: string;
  service?: {
    name: {
      en: string;
      am: string;
    };
  };
  planId: string;
  expectedQuantity: number;
  currentQuantity: number;
  planType: "percent" | string;
  timeframe: "monthly" | string;
  year: number;
  month: number;
  week: number | null;
  parentEmployeePlanId: string | null;
  plan: { name?: { en: string; am: string } };
  description?: { en: string; am: string };
  weight?: number;
  status?: string;
  // initialGoal?: number;
  // expectedGoal?: number;
  name?: { en: string; am: string };
}

const EmployeePlanListPage = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { yearId } = useParams();
  const { toast } = useToast();
  const localizedName = useLocalizedName();
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [planToDelete, setPlanToDelete] = useState<string | null>(null);
  const [viewType, setViewType] = useState<"table" | "grid">("table");
  const [selectedService, setSelectedService] = useState<string>("all");
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [timeframeFilter, setTimeframeFilter] = useState<string>("all");
  const [sortBy, setSortBy] = useState<"name" | "progress" | "weight" | "date">(
    "name"
  );
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
  const [showCompleted, setShowCompleted] = useState(true);
  const [activeTab, setActiveTab] = useState("all");
  const { user, selectedPositionId } = useAuth();
  const positionType = getSelectedPositionType(user, selectedPositionId);
  // const calculateProgress = (initialGoal?: number, expectedGoal?: number) => {
  //   const initial = initialGoal ?? 0;
  //   const expected = expectedGoal ?? 1;
  //   if (expected === 0) return 0;
  //   return Math.min(100, (initial / expected) * 100);
  // };
  // Use the useMinePlan hook
  const {
    data: minePlanResponse,
    isLoading: isMinePlanLoading,
    error: isMinePlanError,
    refetch: minePlanRefetch,
  } = useMinePlan();

  const {
    data: mineEmployeePlanResponse,
    isLoading: isEmployeePlanLoading,
    error: isEmployeePlanError,
    refetch: employeePlanRefetch,
  } = useMineEmployeePlan({
    timeframe: "monthly",
  });

  // Determine which data to use:
  // - For EMPLOYEE position type, always use /employee-plans/mine
  // - For everyone else (team leads, directors, etc.), prefer /plans/mine but
  //   fall back to /employee-plans/mine when the user actually has monthly
  //   employee-plan assignments. This covers team leads whose own work is
  //   tracked at the employee-plan level.
  const isEmployee = positionType === EPositionTypeKey.EMPLOYEE;
  const minePlanItems = minePlanResponse?.data?.items?.length ?? 0;
  const mineEmployeePlanItems =
    mineEmployeePlanResponse?.data?.items?.length ?? 0;
  const useEmployeePlanData =
    isEmployee || (mineEmployeePlanItems > 0 && minePlanItems === 0);

  const currentData = useEmployeePlanData
    ? mineEmployeePlanResponse
    : minePlanResponse;
  const isLoading = useEmployeePlanData
    ? isEmployeePlanLoading
    : isMinePlanLoading;
  const error = useEmployeePlanData ? isEmployeePlanError : isMinePlanError;
  const refetch = useEmployeePlanData
    ? employeePlanRefetch
    : minePlanRefetch;

  const employeePlans = useMemo(
    () => currentData?.data?.items || [],
    [currentData]
  );

  // Get unique services from plans and check if any plan has a service
  const { services, hasAnyService } = useMemo(() => {
    const serviceMap = new Map();
    let hasService = false;
    employeePlans.forEach((plan: EmployeePlan) => {
      if (plan.service && plan.serviceId) {
        serviceMap.set(plan.serviceId, {
          id: plan.serviceId,
          name: plan.service?.name || { en: "Unknown", am: "Unknown" },
        });
        hasService = true;
      }
    });
    return {
      services: Array.from(serviceMap.values()),
      hasAnyService: hasService,
    };
  }, [employeePlans]);

  // Filter plans based on selected service
  const filteredPlans = useMemo(() => {
    let filtered = employeePlans;

    // Service filter
    if (selectedService !== "all") {
      filtered = filtered.filter(
        (plan: EmployeePlan) => plan.serviceId === selectedService
      );
    }

    // Status filter
    if (statusFilter !== "all") {
      filtered = filtered.filter(
        (plan: EmployeePlan) => plan.status === statusFilter
      );
    }

    // Timeframe filter
    if (timeframeFilter !== "all") {
      filtered = filtered.filter(
        (plan: EmployeePlan) => plan.timeframe === timeframeFilter
      );
    }

    // Search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      filtered = filtered.filter((plan: EmployeePlan) => {
        const name = localizedName(
          plan?.plan?.name || plan?.name || { en: "", am: "" }
        ).toLowerCase();
        const description = localizedName(
          plan.description || { en: "", am: "" }
        ).toLowerCase();
        return name.includes(term) || description.includes(term);
      });
    }

    // Show completed filter
    if (!showCompleted) {
      filtered = filtered.filter(
        (plan: EmployeePlan) => plan.status !== "accepted"
      );
    }

    // Active tab filter
    if (activeTab === "active") {
      filtered = filtered.filter(
        (plan: EmployeePlan) =>
          plan.status === "accepted" || plan.status === "pending"
      );
    } else if (activeTab === "completed") {
      filtered = filtered.filter(
        (plan: EmployeePlan) => plan.status === "accepted"
      );
    } else if (activeTab === "draft") {
      filtered = filtered.filter(
        (plan: EmployeePlan) => plan.status === "draft"
      );
    }

    // Sort plans
    filtered.sort((a: EmployeePlan, b: EmployeePlan) => {
      let aValue: string | number, bValue: string | number;

      switch (sortBy) {
        case "name":
          aValue = localizedName(a.plan?.name || a.name || { en: "", am: "" });
          bValue = localizedName(b.plan?.name || b.name || { en: "", am: "" });
          break;
        case "progress":
          // aValue = calculateProgress(a.initialGoal || 0, a.expectedGoal || 1);
          // bValue = calculateProgress(b.initialGoal || 0, b.expectedGoal || 1);
          aValue = 0;
          bValue = 0;
          break;
        case "weight":
          aValue = a.weight || 0;
          bValue = b.weight || 0;
          break;
        case "date":
          aValue = new Date(a.createdAt).getTime();
          bValue = new Date(b.createdAt).getTime();
          break;
        default:
          return 0;
      }

      if (sortOrder === "asc") {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

    return filtered;
  }, [
    employeePlans,
    selectedService,
    statusFilter,
    timeframeFilter,
    searchTerm,
    showCompleted,
    activeTab,
    sortBy,
    sortOrder,
    localizedName,
  ]);
  // Calculate statistics
  const stats = useMemo(() => {
    const total = filteredPlans.length;
    const completed = filteredPlans.filter(
      (p: EmployeePlan) => p.status === "accepted"
    ).length;
    const pending = filteredPlans.filter(
      (p: EmployeePlan) => p.status === "pending"
    ).length;
    const draft = filteredPlans.filter(
      (p: EmployeePlan) => p.status === "draft"
    ).length;

    const totalWeight = filteredPlans.reduce(
      (sum: number, plan: EmployeePlan) => sum + (plan.weight || 0),
      0
    );
    const avgWeight = total > 0 ? totalWeight / total : 0;

    const totalProgress = filteredPlans.reduce(
      (sum: number, plan: EmployeePlan) =>
        sum, // + calculateProgress(plan.initialGoal || 0, plan.expectedGoal || 1),
      0
    );
    const avgProgress = total > 0 ? totalProgress / total : 0;

    return {
      total,
      completed,
      pending,
      draft,
      avgWeight: parseFloat(avgWeight.toFixed(1)),
      avgProgress: parseFloat(avgProgress.toFixed(1)),
    };
  }, [filteredPlans]);

  // Handle delete
  const handleDeleteClick = (id: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    setPlanToDelete(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (!planToDelete) return;

    setDeletingId(planToDelete);
    setDeleteDialogOpen(false);

    try {
      await deleteEmployeePlan(planToDelete);
      toast({
        title: t("common.success", "Success"),
        description: t(
          "employeePlans.deleteSuccess",
          "Employee plan deleted successfully"
        ),
        variant: "default",
      });
      refetch();
    } catch (error) {
      console.error("Failed to delete employee plan:", error);
      toast({
        title: t("common.error", "Error"),
        description: t(
          "employeePlans.deleteFailed",
          "Failed to delete employee plan"
        ),
        variant: "destructive",
      });
    } finally {
      setDeletingId(null);
      setPlanToDelete(null);
    }
  };

  const handleEdit = (id: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    navigate(`/performance-management/${yearId}/employee-plans/edit/${id}`);
  };

  const handlePlanClick = (
    id: string,
    month: number,
    planData: EmployeePlan
  ) => {
    // Debug logging to check what we're getting
    console.log("handlePlanClick called with:", { id, month, planData });
    console.log("Position Type:", positionType);
    console.log("Plan Data:", planData);

    // Check if yearId exists
    if (!yearId) {
      console.error("yearId is undefined!");
      toast({
        title: t("common.error", "Error"),
        description: t("employeePlans.yearIdMissing", "Year ID is missing"),
        variant: "destructive",
      });
      return;
    }

    // Add null checks for planData properties
    const employeePositionId = planData?.employeePositionId || "";
    // If planId is missing (e.g. from minePlanResponse/Plan objects), use id as fallback
    const planId = planData?.planId || planData?.id || "";
    const serviceId = planData?.serviceId || "";

    if (!planId) {
      console.error("planId is undefined or empty!");
      toast({
        title: t("common.error", "Error"),
        description: t(
          "employeePlans.planIdMissing",
          "Plan data is incomplete: Missing Plan ID"
        ),
        variant: "destructive",
      });
      return;
    }
    const planType = planData?.planType || "percent";
    const currentQuantity = planData?.currentQuantity || 0;
    const expectedQuantity = planData?.expectedQuantity || 0;
    const timeframe = planData?.timeframe || "monthly";

    try {
      // Calculate month range from amharic start and end dates
      let monthsToPass: number[] = [];

      // For quarterly/monthly plans, calculate months from start and end dates
      if (planData?.amharicStartDate && planData?.amharicEndDate) {
        console.log("Calculating month range from:", {
          start: planData.amharicStartDate,
          end: planData.amharicEndDate,
          timeframe: planData.timeframe,
        });
        const availableMonths = calculateAvailableMonths(
          planData.amharicStartDate,
          planData.amharicEndDate,
          monthsConfig
        );
        monthsToPass = availableMonths.map((m) => m.value);
      } else if (month) {
        // Fallback: use the month field if available
        monthsToPass = [month];
      }

      const monthsParam = monthsToPass.join(",");

      if (
        positionType === EPositionTypeKey.TEAM_LEADER ||
        positionType === EPositionTypeKey.DIRECTOR
      ) {
        console.log("Navigating to leader/director view");
        navigate(
          `/performance-management/${yearId}/employee-plans/plans/${planId}?months=${monthsParam}`
        );
      } else if (positionType === EPositionTypeKey.EMPLOYEE) {
        // Create navigation state with fallbacks
        const navigationState = {
          parentEmployeePlanId: id,
          employeePositionId,
          planId,
          serviceId,
          planType,
          currentQuantity,
          expectedQuantity,
          month: month || 1, // Default to month 1 if not provided
          timeframe,
          planName: localizedName(
            planData?.plan?.name || planData?.name || { en: "Plan", am: "Plan" }
          ),
          serviceName: planData?.service?.name
            ? localizedName(planData.service.name)
            : "N/A",
          weight: planData?.weight || 0,
          status: planData?.status || "draft",
          // Add more properties as needed
          description: planData?.description
            ? localizedName(planData.description)
            : "",
          startDate: planData?.startDate,
          endDate: planData?.endDate,
          amharicStartDate: planData?.amharicStartDate,
          amharicEndDate: planData?.amharicEndDate,
          // Pass the specific months for this plan
          planMonths: monthsToPass,
        };

        // Handle weekly timeframe navigation
        if (timeframe === "monthly") {
          // For weekly plans, we need to pick a month to display.
          // Use the clicked month (if available) or the first available month from the plan range
          const targetMonth =
            month || (monthsToPass.length > 0 ? monthsToPass[0] : 1);

          navigate(
            `/performance-management/${yearId}/employee-plans/plans/${planId}/${targetMonth}/weekly`,
            {
              state: navigationState,
            }
          );
        } else {
          // Pass planMonths as URL query parameter to ensure it persists
          navigate(
            `/performance-management/${yearId}/employee-plans/plans/${planId}?months=${monthsParam}`,
            {
              state: navigationState,
            }
          );
        }
      } else {
        navigate(
          `/performance-management/${yearId}/employee-plans/plans/${planId}?months=${monthsParam}`
        );
      }
    } catch (error) {
      console.error("Navigation error:", error);
      toast({
        title: t("employeePlans.navigationError", "Navigation Error"),
        description: t(
          "employeePlans.navigationErrorMessage",
          "Could not navigate to plan details"
        ),
        variant: "destructive",
      });
    }
  };

  const formatDate = (dateString: string) => {
    try {
      return format(new Date(dateString), "MMM dd, yyyy");
    } catch {
      return dateString;
    }
  };

  const getTimeframeBadge = (timeframe: string) => {
    const colors = {
      yearly: "bg-blue-100 text-blue-800 border-blue-200",
      quarterly: "bg-purple-100 text-purple-800 border-purple-200",
      monthly: "bg-green-100 text-green-800 border-green-200",
      weekly: "bg-yellow-100 text-yellow-800 border-yellow-200",
      daily: "bg-red-100 text-red-800 border-red-200",
    };

    return (
      <Badge
        variant="outline"
        className={`${
          colors[timeframe as keyof typeof colors] ||
          "bg-gray-100 text-gray-800 border-gray-200"
        } font-medium`}>
        {timeframe.charAt(0).toUpperCase() + timeframe.slice(1)}
      </Badge>
    );
  };

  const getPlanTypeIcon = (planType: string) => {
    return planType === "number" ? (
      <Hash className="h-4 w-4" />
    ) : (
      <Percent className="h-4 w-4" />
    );
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      accepted: {
        bg: "bg-green-50",
        text: "text-primary-700",
        border: "border-green-200",
        label: "Accepted",
        icon: <CheckCircle className="h-3 w-3 mr-1" />,
      },
      pending: {
        bg: "bg-yellow-50",
        text: "text-yellow-700",
        border: "border-yellow-200",
        label: "Pending",
        icon: <Clock className="h-3 w-3 mr-1" />,
      },
      draft: {
        bg: "bg-gray-50",
        text: "text-gray-700",
        border: "border-gray-200",
        label: "Draft",
        icon: <EyeOff className="h-3 w-3 mr-1" />,
      },
      rejected: {
        bg: "bg-red-50",
        text: "text-red-700",
        border: "border-red-200",
        label: "Rejected",
        icon: <XCircle className="h-3 w-3 mr-1" />,
      },
    };

    const config =
      statusConfig[status as keyof typeof statusConfig] || statusConfig.draft;

    return (
      <Badge
        variant="outline"
        className={`${config.bg} ${config.text} ${config.border} font-medium flex items-center`}>
        {config.icon}
        {config.label}
      </Badge>
    );
  };

  const handleSort = (field: "name" | "progress" | "weight" | "date") => {
    if (sortBy === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("asc");
    }
  };

  const getSortIcon = (field: string) => {
    if (sortBy !== field) return null;
    return sortOrder === "asc" ? (
      <ChevronUp className="h-4 w-4" />
    ) : (
      <ChevronDown className="h-4 w-4" />
    );
  };

  const handleExport = () => {
    // Export functionality
    toast({
      title: t("employeePlans.exportStarted", "Export Started"),
      description: t(
        "employeePlans.exportMessage",
        "Your plans are being exported. You'll receive a download link shortly."
      ),
    });
  };

  const handleBulkAction = (action: string) => {
    // Bulk action functionality
    toast({
      title: "Bulk Action",
      description: `${action} action performed on selected items.`,
    });
  };

  const getProgressColor = (progress: number) => {
    if (progress >= 90) return "bg-gradient-to-r from-green-500 to-emerald-500";
    if (progress >= 70) return "bg-gradient-to-r from-blue-500 to-cyan-500";
    if (progress >= 50) return "bg-gradient-to-r from-yellow-500 to-amber-500";
    return "bg-gradient-to-r from-red-500 to-rose-500";
  };

  if (error) {
    return (
      <div className="p-6">
        <Card className="border-red-200 bg-gradient-to-br from-red-50/50 to-white">
          <CardContent className="pt-12 pb-12 text-center">
            <AlertCircle className="h-16 w-16 mx-auto text-red-400 mb-4" />
            <h3 className="text-2xl font-bold text-red-700 mb-2">
              {t("employeePlans.errorLoadingPlans", "Error Loading Plans")}
            </h3>
            <p className="text-red-600 max-w-md mx-auto mb-6">
              We encountered an error while loading your performance plans.
              Please check your connection and try again.
            </p>
            <div className="flex gap-3 justify-center">
              <Button
                onClick={() => refetch()}
                className="bg-gradient-to-r from-red-500 to-rose-500 hover:from-red-600 hover:to-rose-600 text-white">
                <RefreshCw className="h-4 w-4 mr-2" />
                Retry
              </Button>
              <Button
                variant="outline"
                onClick={() => navigate("/performance-management")}>
                {t("employeePlans.backToDashboard", "Back to Dashboard")}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gradient-to-br from-gray-50/50 to-white min-h-screen">
      <div className="max-w-7xl mx-auto">
        {/* Direct reports panel — uses /positions/children/{myPositionId}
            and refetches when the user switches position via the topbar. */}
        <MyTeamPanel />

        {/* Header */}
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 mb-8">
          <div>
            <div className="flex items-center gap-3 mb-2">
              <div className="p-2 bg-gradient-to-r from-purple-500 to-violet-600 rounded-lg">
                <Target className="h-6 w-6 text-white" />
              </div>
              <h1 className="text-3xl font-bold text-gray-900">
                {t("employeePlans.title", "My Performance Plans")}
              </h1>
            </div>
            <p className="text-gray-600">
              {t(
                "employeePlans.description",
                "Manage your personal performance goals and track progress in real-time"
              )}
            </p>
          </div>
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => refetch()}
              disabled={isLoading}
              className="gap-2">
              {isLoading ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <RefreshCw className="h-4 w-4" />
              )}
              {t("employeePlans.refresh", "Refresh")}
            </Button>
            {/* <Button
              onClick={() =>
                navigate(
                  `/performance-management/${yearId}/employee-plans/create`
                )
              }
              className="bg-gradient-to-r from-purple-500 to-violet-600 hover:from-purple-600 hover:to-violet-700 text-white gap-2"
            >
              <PlusIcon className="h-4 w-4" />
              {t("employeePlans.newPlan", "New Plan")}
            </Button> */}
          </div>
        </div>

        {/* Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="mb-8">
          <TabsList className="bg-gray-100 p-1">
            <TabsTrigger value="all" className="data-[state=active]:bg-white">
              {t("employeePlans.allPlans", "All Plans")}
              <Badge variant="secondary" className="ml-2">
                {stats.total}
              </Badge>
            </TabsTrigger>
            <TabsTrigger
              value="active"
              className="data-[state=active]:bg-white">
              <Activity className="h-4 w-4 mr-2" />
              {t("employeePlans.active", "Active")}
              <Badge variant="secondary" className="ml-2">
                {stats.pending}
              </Badge>
            </TabsTrigger>
            <TabsTrigger
              value="completed"
              className="data-[state=active]:bg-white">
              <CheckCircle className="h-4 w-4 mr-2" />
              {t("employeePlans.completed", "Completed")}
              <Badge variant="secondary" className="ml-2">
                {stats.completed}
              </Badge>
            </TabsTrigger>
            <TabsTrigger value="draft" className="data-[state=active]:bg-white">
              <EyeOff className="h-4 w-4 mr-2" />
              {t("employeePlans.drafts", "Drafts")}
              <Badge variant="secondary" className="ml-2">
                {stats.draft}
              </Badge>
            </TabsTrigger>
          </TabsList>
        </Tabs>

        {/* Stats Overview */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <Card className="bg-gradient-to-br from-purple-50 to-white border-purple-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-purple-600 mb-1">
                    {t("employeePlans.totalPlans", "Total Number of Plans")}
                  </p>
                  <p className="text-3xl font-bold text-purple-900">
                    {stats.total}
                  </p>
                  <p className="text-xs text-purple-500 mt-2">
                    {t(
                      "employeePlans.activePerformanceGoals",
                      "Active performance goals"
                    )}
                  </p>
                </div>
                <div className="p-3 bg-gradient-to-r from-purple-100 to-purple-200 rounded-xl">
                  <Target className="h-8 w-8 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-blue-50 to-white border-blue-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-blue-600 mb-1">
                    {t("employeePlans.avgProgress", "Avg. Progress")}
                  </p>
                  <p className="text-3xl font-bold text-blue-900">
                    {stats.avgProgress}%
                  </p>
                  <div className="w-full bg-blue-100 rounded-full h-2 mt-2">
                    <div
                      className={`h-2 rounded-full ${getProgressColor(
                        stats.avgProgress
                      )}`}
                      style={{ width: `${stats.avgProgress}%` }}
                    />
                  </div>
                </div>
                <div className="p-3 bg-gradient-to-r from-blue-100 to-blue-200 rounded-xl">
                  <TrendingUp className="h-8 w-8 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-green-50 to-white border-green-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-primary-600 mb-1">
                    {t("employeePlans.avgWeight", "Avg. Weight")}
                  </p>
                  <p className="text-3xl font-bold text-green-900">
                    {stats.avgWeight}%
                  </p>
                  <p className="text-xs text-green-500 mt-2">
                    {t(
                      "employeePlans.averagePlanImportance",
                      "Average plan importance"
                    )}
                  </p>
                </div>
                <div className="p-3 bg-gradient-to-r from-green-100 to-green-200 rounded-xl">
                  <Award className="h-8 w-8 text-primary-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-orange-50 to-white border-orange-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-orange-600 mb-1">
                    {t("employeePlans.completionRate", "Completion Rate")}
                  </p>
                  <p className="text-3xl font-bold text-orange-900">
                    {stats.total > 0
                      ? Math.round((stats.completed / stats.total) * 100)
                      : 0}
                    %
                  </p>
                  <p className="text-xs text-orange-500 mt-2">
                    {stats.completed} {t("employeePlans.of", "of")}{" "}
                    {stats.total} {t("employeePlans.completed", "completed")}
                  </p>
                </div>
                <div className="p-3 bg-gradient-to-r from-orange-100 to-orange-200 rounded-xl">
                  <Star className="h-8 w-8 text-orange-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Filters and Search */}
        <Card className="mb-8 border-0 shadow-lg">
          <CardContent className="p-6">
            <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
              {/* Search */}
              <div className="relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <Input
                  placeholder={t(
                    "employeePlans.searchPlans",
                    "Search plans..."
                  )}
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-9"
                />
              </div>

              {/* Service Filter */}
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  {t("employeePlans.service", "Service")}
                </label>
                <select
                  value={selectedService}
                  onChange={(e) => setSelectedService(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-white text-sm focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                  <option value="all">
                    {t("employeePlans.allServices", "All Services")}
                  </option>
                  {services.map((service) => (
                    <option key={service.id} value={service.id}>
                      {localizedName(service.name)}
                    </option>
                  ))}
                </select>
              </div>

              {/* Status Filter */}
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  {t("employeePlans.status", "Status")}
                </label>
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-white text-sm focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                  <option value="all">
                    {t("employeePlans.allStatus", "All Status")}
                  </option>
                  <option value="draft">
                    {t("employeePlans.draft", "Draft")}
                  </option>
                  <option value="pending">
                    {t("employeePlans.pending", "Pending")}
                  </option>
                  <option value="accepted">
                    {t("employeePlans.accepted", "Accepted")}
                  </option>
                  <option value="rejected">
                    {t("employeePlans.rejected", "Rejected")}
                  </option>
                </select>
              </div>

              {/* Timeframe Filter */}
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  {t("employeePlans.timeframe", "Timeframe")}
                </label>
                <select
                  value={timeframeFilter}
                  onChange={(e) => setTimeframeFilter(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-white text-sm focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                  <option value="all">
                    {t("employeePlans.allTimeframes", "All Timeframes")}
                  </option>
                  <option value="daily">
                    {t("employeePlans.daily", "Daily")}
                  </option>
                  <option value="weekly">
                    {t("employeePlans.weekly", "Weekly")}
                  </option>
                  <option value="monthly">
                    {t("employeePlans.monthly", "Monthly")}
                  </option>
                  <option value="quarterly">
                    {t("employeePlans.quarterly", "Quarterly")}
                  </option>
                  <option value="yearly">
                    {t("employeePlans.yearly", "Yearly")}
                  </option>
                </select>
              </div>
            </div>

            {/* Additional Filters */}
            <div className="flex flex-wrap items-center justify-between gap-4 mt-6 pt-6 border-t">
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="showCompleted"
                    checked={showCompleted}
                    onChange={(e) => setShowCompleted(e.target.checked)}
                    className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
                  />
                  <label
                    htmlFor="showCompleted"
                    className="text-sm text-gray-700">
                    {t("employeePlans.showCompleted", "Show completed plans")}
                  </label>
                </div>
              </div>

              <div className="flex items-center gap-4">
                <div className="inline-flex rounded-lg border border-gray-200 p-1 bg-gray-50">
                  <Button
                    variant={viewType === "table" ? "default" : "ghost"}
                    size="sm"
                    onClick={() => setViewType("table")}
                    className={`gap-2 ${
                      viewType === "table"
                        ? "bg-white shadow-sm"
                        : "text-gray-600 hover:text-gray-900"
                    }`}>
                    <TableIcon className="h-4 w-4" />
                    {t("employeePlans.table", "Table")}
                  </Button>
                  <Button
                    variant={viewType === "grid" ? "default" : "ghost"}
                    size="sm"
                    onClick={() => setViewType("grid")}
                    className={`gap-2 ${
                      viewType === "grid"
                        ? "bg-white shadow-sm"
                        : "text-gray-600 hover:text-gray-900"
                    }`}>
                    <Grid3x3 className="h-4 w-4" />
                    {t("employeePlans.grid", "Grid")}
                  </Button>
                </div>

                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="outline" className="gap-2">
                      <Download className="h-4 w-4" />
                      {t("employeePlans.export", "Export")}
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent>
                    <DropdownMenuItem onClick={handleExport}>
                      {t("employeePlans.exportAsCsv", "Export as CSV")}
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={handleExport}>
                      {t("employeePlans.exportAsPdf", "Export as PDF")}
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={handleExport}>
                      {t("employeePlans.exportAsExcel", "Export as Excel")}
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Loading State */}
        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-20">
            <div className="relative">
              <Loader2 className="h-16 w-16 animate-spin text-purple-600" />
              <div className="absolute inset-0 flex items-center justify-center">
                <Target className="h-8 w-8 text-purple-400" />
              </div>
            </div>
            <p className="text-gray-600 mt-4 text-lg">
              {t(
                "employeePlans.loadingPlans",
                "Loading your performance plans..."
              )}
            </p>
            <p className="text-gray-500 text-sm mt-2">
              {t(
                "employeePlans.loadingMessage",
                "Please wait while we fetch your data"
              )}
            </p>
          </div>
        ) : filteredPlans.length === 0 ? (
          <Card className="border-dashed border-2 bg-gradient-to-br from-gray-50/50 to-white">
            <CardContent className="pt-16 pb-16 text-center">
              <div className="w-24 h-24 mx-auto mb-6 rounded-full bg-gradient-to-r from-purple-100 to-violet-100 flex items-center justify-center">
                <Target className="h-12 w-12 text-purple-400" />
              </div>
              <h3 className="text-2xl font-bold text-gray-900 mb-3">
                {t("employeePlans.noPlansFound", "No Plans Found")}
              </h3>
              <p className="text-gray-600 max-w-md mx-auto mb-8">
                {searchTerm ||
                selectedService !== "all" ||
                statusFilter !== "all"
                  ? t(
                      "employeePlans.noPlansMessage",
                      "No plans match your current filters. Try adjusting your search criteria."
                    )
                  : t(
                      "employeePlans.noPlansInitial",
                      "You haven't created any performance plans yet. Start by creating your first plan to track your goals."
                    )}
              </p>
              <div className="flex gap-3 justify-center">
                {/* <Button
                  onClick={() => {
                    navigate(
                      `/performance-management/${yearId}/employee-plans/create`
                    );
                  }}
                  className="bg-gradient-to-r from-purple-500 to-violet-600 hover:from-purple-600 hover:to-violet-700 text-white"
                >
                  <PlusIcon className="h-4 w-4 mr-2" />
                  {t("employeePlans.createFirstPlan", "Create Your First Plan")}
                </Button> */}
                {(searchTerm ||
                  selectedService !== "all" ||
                  statusFilter !== "all") && (
                  <Button
                    variant="outline"
                    onClick={() => {
                      setSearchTerm("");
                      setSelectedService("all");
                      setStatusFilter("all");
                      setTimeframeFilter("all");
                    }}>
                    {t("employeePlans.clearFilters", "Clear Filters")}
                  </Button>
                )}
              </div>
            </CardContent>
          </Card>
        ) : viewType === "table" ? (
          <Card className="border-0 shadow-lg overflow-hidden">
            <CardHeader className="bg-gradient-to-r from-gray-50 to-gray-100/50 border-b">
              <div className="flex justify-between items-center">
                <div>
                  <CardTitle>
                    {t("employeePlans.performancePlans", "Performance Plans")}
                  </CardTitle>
                  <CardDescription>
                    {filteredPlans.length}{" "}
                    {t("employeePlans.allPlans", "plans")} •{" "}
                    {t("employeePlans.sortedBy", "Sorted by")} {sortBy} (
                    {sortOrder})
                  </CardDescription>
                </div>
                <div className="text-sm text-gray-500">
                  {t("employeePlans.showing", "Showing")} {filteredPlans.length}{" "}
                  {t("employeePlans.of", "of")} {employeePlans.length}{" "}
                  {t("employeePlans.totalPlansText", "total plans")}
                </div>
              </div>
            </CardHeader>
            <CardContent className="p-0">
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-gray-50/50">
                      <TableHead
                        className="cursor-pointer hover:bg-gray-100 transition-colors"
                        onClick={() => handleSort("name")}>
                        <div className="flex items-center gap-1">
                          {t("employeePlans.planName", "Plan Name")}
                          {getSortIcon("name")}
                        </div>
                      </TableHead>
                      {hasAnyService && (
                        <TableHead>
                          {t("employeePlans.service", "Service")}
                        </TableHead>
                      )}
                      <TableHead
                        className="cursor-pointer hover:bg-gray-100 transition-colors"
                        onClick={() => handleSort("progress")}>
                        <div className="flex items-center gap-1">
                          {t("employeePlans.progress", "Progress")}
                          {getSortIcon("progress")}
                        </div>
                      </TableHead>
                      <TableHead
                        className="cursor-pointer hover:bg-gray-100 transition-colors"
                        onClick={() => handleSort("weight")}>
                        <div className="flex items-center gap-1">
                          {t("employeePlans.weight", "Weight")}
                          {getSortIcon("weight")}
                        </div>
                      </TableHead>
                      <TableHead>
                        {t("employeePlans.timeframe", "Timeframe")}
                      </TableHead>
                      <TableHead>
                        {t("employeePlans.statusLabel", "Status")}
                      </TableHead>
                      <TableHead
                        className="cursor-pointer hover:bg-gray-100 transition-colors"
                        onClick={() => handleSort("date")}>
                        <div className="flex items-center gap-1">
                          {t("employeePlans.created", "Created")}
                          {getSortIcon("date")}
                        </div>
                      </TableHead>
                      <TableHead
                        className="cursor-pointer hover:bg-gray-100 transition-colors"
                        onClick={() => handleSort("date")}>
                        <div className="flex items-center gap-1">
                          {t("employeePlans.planMonth", "Plan Month")}
                        </div>
                      </TableHead>
                      <TableHead className="text-right">
                        {t("employeePlans.actions", "Actions")}
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredPlans.map((plan: EmployeePlan) => {
                      // const progress = calculateProgress(
                      //   plan.initialGoal || 0,
                      //   plan.expectedGoal || 1
                      // );
                      const progress = 0;

                      return (
                        <TableRow
                          key={plan.id}
                          className="hover:bg-purple-50/30 transition-colors cursor-pointer group"
                          onClick={(e) => {
                            // Prevent navigation if clicking on action buttons
                            if (
                              e.target instanceof HTMLElement &&
                              (e.target.closest("button") ||
                                e.target.closest('[role="menuitem"]') ||
                                e.target.closest('[data-state="open"]'))
                            ) {
                              return;
                            }
                            handlePlanClick(plan.id, plan.month || 1, plan);
                          }}>
                          <TableCell>
                            <div className="flex flex-col">
                              <div className="flex items-center gap-2">
                                <span className="font-semibold text-gray-900 group-hover:text-purple-600 transition-colors">
                                  {localizedName(
                                    plan?.plan?.name ||
                                      plan?.name || {
                                        en: "Unnamed Plan",
                                        am: "Unnamed Plan",
                                      }
                                  )}
                                </span>
                                <ArrowUpRight className="h-3 w-3 text-gray-400 group-hover:text-purple-400 transition-colors" />
                              </div>
                              <span className="text-sm text-gray-500 truncate max-w-xs">
                                {localizedName(
                                  plan.description || {
                                    en: "No description",
                                    am: "No description",
                                  }
                                )}
                              </span>
                            </div>
                          </TableCell>
                          {hasAnyService && (
                            <TableCell>
                              {plan.service ? (
                                <Badge
                                  variant="outline"
                                  className="bg-blue-50 text-blue-700 border-blue-200">
                                  {localizedName(plan.service.name)}
                                </Badge>
                              ) : (
                                <span className="text-gray-400">-</span>
                              )}
                            </TableCell>
                          )}
                          <TableCell>
                            <div className="flex items-center gap-3">
                              <TooltipProvider>
                                <Tooltip>
                                  <TooltipTrigger>
                                    <div className="w-24">
                                      {/* <div className="flex justify-between text-xs mb-1">
                                        <span className="font-medium">
                                          {plan.initialGoal || 0}
                                        </span>
                                        <span className="text-gray-500">
                                          {plan.expectedGoal || 0}
                                        </span>
                                      </div> */}
                                      <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                                        <div
                                          className={`h-full rounded-full transition-all duration-500 ${getProgressColor(
                                            progress
                                          )}`}
                                          style={{ width: `${progress}%` }}
                                        />
                                      </div>
                                    </div>
                                  </TooltipTrigger>
                                  <TooltipContent>
                                    <p>Progress: {progress.toFixed(1)}%</p>
                                  </TooltipContent>
                                </Tooltip>
                              </TooltipProvider>
                              <span className="text-sm font-medium text-gray-700 min-w-[40px]">
                                {progress.toFixed(0)}%
                              </span>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge variant="outline" className="font-medium">
                              {plan.weight || 0}%
                            </Badge>
                          </TableCell>
                          <TableCell>
                            {getTimeframeBadge(plan.timeframe)}
                          </TableCell>
                          <TableCell>
                            {getStatusBadge(plan.status || "draft")}
                          </TableCell>
                          <TableCell>
                            <div className="flex flex-col">
                              <span className="text-sm text-gray-700">
                                {formatDate(plan.createdAt)}
                              </span>
                              <span className="text-xs text-gray-500">
                                {plan.updatedAt &&
                                  `${t(
                                    "employeePlans.updated",
                                    "Updated"
                                  )}: ${formatDate(plan.updatedAt)}`}
                              </span>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="flex flex-col">
                              <span className="text-sm text-gray-700">
                                {formatDate(plan.amharicStartDate)}
                              </span>
                              <span className="text-xs text-gray-500">
                                {plan.amharicEndDate &&
                                  `${t(
                                    "employeePlans.endDate",
                                    "End Date"
                                  )}: ${formatDate(plan.amharicEndDate)}`}
                              </span>
                            </div>
                          </TableCell>
                          <TableCell className="text-right">
                            <div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={(e) => handleEdit(plan.id, e)}
                                className="h-8 w-8 p-0 text-blue-600 hover:text-blue-700 hover:bg-blue-50">
                                <Pencil className="h-3.5 w-3.5" />
                              </Button>
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={(e) => handleDeleteClick(plan.id, e)}
                                disabled={deletingId === plan.id}
                                className="h-8 w-8 p-0 text-red-600 hover:text-red-700 hover:bg-red-50">
                                {deletingId === plan.id ? (
                                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                ) : (
                                  <Trash2 className="h-3.5 w-3.5" />
                                )}
                              </Button>
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    className="h-8 w-8 p-0">
                                    <MoreVertical className="h-3.5 w-3.5" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  <DropdownMenuLabel>
                                    {t("employeePlans.actions", "Actions")}
                                  </DropdownMenuLabel>
                                  <DropdownMenuItem
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      handleEdit(plan.id, e);
                                    }}>
                                    <Pencil className="h-4 w-4 mr-2" />
                                    {t("employeePlans.editPlan", "Edit Plan")}
                                  </DropdownMenuItem>
                                  <DropdownMenuItem
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      handlePlanClick(
                                        plan.id,
                                        plan.month || 1,
                                        plan
                                      );
                                    }}>
                                    <Eye className="h-4 w-4 mr-2" />
                                    {t(
                                      "employeePlans.viewDetails",
                                      "View Details"
                                    )}
                                  </DropdownMenuItem>
                                  <DropdownMenuSeparator />
                                  <DropdownMenuItem
                                    onClick={(e) =>
                                      handleDeleteClick(plan.id, e)
                                    }
                                    className="text-red-600">
                                    <Trash2 className="h-4 w-4 mr-2" />
                                    {t(
                                      "employeePlans.deletePlanAction",
                                      "Delete Plan"
                                    )}
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </div>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        ) : (
          // Grid View
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredPlans.map((plan: EmployeePlan) => {
              // const progress = calculateProgress(
              //   plan.initialGoal || 0,
              //   plan.expectedGoal || 1
              // );
              const progress = 0;

              console.log("plans sdfsd f", plan);

              return (
                <Card
                  key={plan.id}
                  className="hover:shadow-xl transition-all duration-300 border hover:border-purple-300 cursor-pointer hover:scale-[1.02] group"
                  onClick={(e) => {
                    // Prevent navigation if clicking on action buttons
                    if (
                      e.target instanceof HTMLElement &&
                      (e.target.closest("button") ||
                        e.target.closest('[role="menuitem"]'))
                    ) {
                      return;
                    }
                    handlePlanClick(plan.id, plan.month || 1, plan);
                  }}>
                  <CardHeader className="pb-4">
                    <div className="flex justify-between items-start">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-2">
                          <div className="p-2 bg-gradient-to-r from-purple-100 to-violet-100 rounded-lg">
                            {getPlanTypeIcon(plan.planType || "number")}
                          </div>
                          <CardTitle className="text-lg text-gray-900 line-clamp-1 group-hover:text-purple-600 transition-colors">
                            {localizedName(
                              plan?.plan?.name ||
                                plan?.name || {
                                  en: "Unnamed Plan",
                                  am: "Unnamed Plan",
                                }
                            )}
                          </CardTitle>
                        </div>
                        <CardDescription className="line-clamp-2">
                          {localizedName(
                            plan.description || {
                              en: "No description",
                              am: "No description",
                            }
                          )}
                        </CardDescription>
                      </div>
                      <div className="flex flex-col items-end gap-2">
                        {getTimeframeBadge(plan.timeframe)}
                        {getStatusBadge(plan.status || "draft")}
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-5">
                      {/* Progress Bar */}
                      <div>
                        <div className="flex justify-between items-center mb-2">
                          <span className="text-sm font-medium text-gray-700">
                            {t("employeePlans.progress", "Progress")}
                          </span>
                          <span className="text-lg font-bold text-gray-900">
                            {progress.toFixed(0)}%
                          </span>
                        </div>
                        <div className="h-3 bg-gray-200 rounded-full overflow-hidden">
                          <div
                            className={`h-full rounded-full transition-all duration-1000 ${getProgressColor(
                              progress
                            )}`}
                            style={{ width: `${progress}%` }}
                          />
                        </div>
                        {/* <div className="flex justify-between text-sm text-gray-500 mt-1">
                          <span>{plan.initialGoal || 0}</span>
                          <span>{plan.expectedGoal || 0}</span>
                        </div> */}
                      </div>

                      {/* Stats Grid */}
                      <div className="grid grid-cols-2 gap-4">
                        <div className="bg-gradient-to-br from-blue-50 to-blue-100/50 p-3 rounded-lg">
                          <p className="text-xs text-blue-600 font-medium mb-1">
                            {t("employeePlans.weight", "Weight")}
                          </p>
                          <p className="text-xl font-bold text-blue-900">
                            {plan.weight || 0}%
                          </p>
                        </div>
                        <div className="bg-gradient-to-br from-green-50 to-green-100/50 p-3 rounded-lg">
                          <p className="text-xs text-primary-600 font-medium mb-1">
                            {t("employeePlans.type", "Type")}
                          </p>
                          <div className="flex items-center gap-1">
                            {getPlanTypeIcon(plan.planType || "number")}
                            <span className="text-lg font-bold text-green-900 capitalize">
                              {plan.planType || "number"}
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Service and Dates */}
                      <div className="space-y-3">
                        <div>
                          <p className="text-xs text-gray-500 mb-1">
                            {t("employeePlans.service", "Service")}
                          </p>
                          <p className="text-sm font-medium text-gray-900">
                            {plan.service?.name
                              ? localizedName(plan.service.name)
                              : "N/A"}
                          </p>
                        </div>
                        <div className="space-y-2">
                          <p className="text-xs text-gray-500">
                            {t("employeePlans.period", "Period")}
                          </p>
                          <div className="flex items-center justify-between text-sm">
                            <div className="flex items-center gap-1">
                              <Calendar className="h-3 w-3 text-gray-400" />
                              <span className="text-gray-700 font-medium">
                                {formatDate(plan.startDate)}
                              </span>
                            </div>
                            <span className="text-gray-300 mx-2">→</span>
                            <div className="flex items-center gap-1">
                              <Calendar className="h-3 w-3 text-gray-400" />
                              <span className="text-gray-700 font-medium">
                                {formatDate(plan.endDate)}
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* Action Buttons */}
                      <div
                        className="pt-4 border-t"
                        onClick={(e) => e.stopPropagation()}>
                        <div className="flex justify-between items-center">
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger asChild>
                                <span className="text-xs text-gray-500">
                                  {t("employeePlans.created", "Created")}:{" "}
                                  {formatDate(plan.createdAt)}
                                </span>
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>
                                  {t(
                                    "employeePlans.clickToViewDetails",
                                    "Click to view details"
                                  )}
                                </p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                          <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={(e) => handleEdit(plan.id, e)}
                              className="h-8 px-3 text-blue-600 border-blue-200 hover:bg-blue-50">
                              <Pencil className="h-3.5 w-3.5" />
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={(e) => handleDeleteClick(plan.id, e)}
                              disabled={deletingId === plan.id}
                              className="h-8 px-3 text-red-600 border-red-200 hover:bg-red-50">
                              {deletingId === plan.id ? (
                                <Loader2 className="h-3.5 w-3.5 animate-spin" />
                              ) : (
                                <Trash2 className="h-3.5 w-3.5" />
                              )}
                            </Button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        )}

        {/* Pagination and Summary */}
        {filteredPlans.length > 0 && (
          <div className="mt-8 flex flex-col sm:flex-row justify-between items-center gap-4">
            <div className="text-sm text-gray-600">
              {t("employeePlans.showing", "Showing")}{" "}
              <span className="font-semibold">{filteredPlans.length}</span>{" "}
              {t("employeePlans.of", "of")}{" "}
              <span className="font-semibold">{employeePlans.length}</span>{" "}
              {t("employeePlans.allPlans", "plans")}
            </div>
            <div className="flex items-center gap-4">
              <Button
                variant="outline"
                size="sm"
                onClick={() => refetch()}
                className="gap-2">
                <RefreshCw className="h-4 w-4" />
                {t("employeePlans.refreshData", "Refresh Data")}
              </Button>
            </div>
          </div>
        )}

        {/* Delete Confirmation Dialog */}
        <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
          <AlertDialogContent className="max-w-md">
            <AlertDialogHeader>
              <div className="flex items-center gap-3 mb-2">
                <div className="p-2 bg-gradient-to-r from-red-100 to-rose-100 rounded-lg">
                  <Trash2 className="h-6 w-6 text-red-600" />
                </div>
                <AlertDialogTitle className="text-red-700">
                  {t(
                    "employeePlans.deletePerformancePlan",
                    "Delete Performance Plan"
                  )}
                </AlertDialogTitle>
              </div>
              <AlertDialogDescription className="text-gray-600">
                {t(
                  "employeePlans.deletePerformancePlanMessage",
                  "Are you sure you want to delete this performance plan? This action cannot be undone and will permanently remove all associated data."
                )}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel className="border-gray-300 hover:bg-gray-50">
                {t("employeePlans.cancel", "Cancel")}
              </AlertDialogCancel>
              <AlertDialogAction
                onClick={confirmDelete}
                className="bg-gradient-to-r from-red-500 to-rose-600 hover:from-red-600 hover:to-rose-700 text-white">
                {deletingId ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    {t("employeePlans.deleting", "Deleting...")}
                  </>
                ) : (
                  <>
                    <Trash2 className="h-4 w-4 mr-2" />
                    {t("employeePlans.deletePlan", "Delete Plan")}
                  </>
                )}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    </div>
  );
};

export default EmployeePlanListPage;
