import React, { useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  Building2,
  Target,
  TrendingUp,
  Users,
  ArrowRight,
  ArrowLeft,
  PlusIcon,
  ChevronDown,
  ChevronUp,
  Filter,
  Search,
  Grid,
  List,
  Download,
  Eye,
  MoreVertical,
  CheckCircle,
  XCircle,
  AlertCircle,
  Clock,
  UserPlus,
  Settings,
  Send,
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { useLocalizedName } from "@/shared/common/localizedName";
import {
  useMySubPlans,
  usePlanMutations,
  useSubPlans,
  useTeamSubPlans,
} from "@/performance-management/hooks/usePlans";
import { Button } from "@/shared/common/ui/button";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { SectorList } from "@/performance-management/types/planTypes";
import { EPositionTypeKey } from "@/shared/dto/user/meDto";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { Badge } from "@/shared/common/ui/badge";
import { Tabs, TabsList, TabsTrigger } from "@/shared/common/ui/tabs";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { Input } from "@/shared/common/ui/input";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { toast } from "sonner";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useTranslation } from "react-i18next";

export interface DepartmentListViewProps {
  positionType?: EPositionTypeKey;
}

// This will be moved inside the component to access t() function

export const DepartmentListView: React.FC<DepartmentListViewProps> = ({
  positionType = EPositionTypeKey.DEPUTY,
}) => {
  const navigate = useNavigate();
  const { yearId, planId } = useParams<{ yearId: string; planId: string }>();
  const localizedName = useLocalizedName();
  const { t } = useTranslation();

  const POSITION_TYPE_LABELS = {
    [EPositionTypeKey.DEPUTY]: {
      singular: t("departmentListView.department"),
      plural: t("departmentListView.departments"),
      title: t("departmentListView.title"),
      description: t("departmentListView.description"),
      icon: Building2,
    },
    [EPositionTypeKey.DIRECTOR]: {
      singular: t("departmentListView.director"),
      plural: t("departmentListView.directors"),
      title: t("subPlanListView.directorOverview"),
      description: t("subPlanListView.directorDescription"),
      icon: Users,
    },
    [EPositionTypeKey.TEAM_LEADER]: {
      singular: t("departmentListView.teamLeader"),
      plural: t("departmentListView.teamLeaders"),
      title: t("subPlanListView.teamLeaderOverview"),
      description: t("subPlanListView.teamLeaderDescription"),
      icon: Users,
    },
    [EPositionTypeKey.EMPLOYEE]: {
      singular: t("departmentListView.employee"),
      plural: t("departmentListView.employees"),
      title: t("subPlanListView.employeeOverview"),
      description: t("subPlanListView.employeeDescription"),
      icon: Users,
    },
  } as const;

  const [activeTab, setActiveTab] = useState("all");
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const [searchTerm, setSearchTerm] = useState("");
  const [sortBy, setSortBy] = useState<"name" | "weight" | "plans" | "rank">(
    "rank"
  );
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");

  const { data, isLoading, error } = useSubPlans(planId || "");
  const { data: teamSubPlansData } = useTeamSubPlans(planId || "");
  const { data: mySubPlansData } = useMySubPlans(planId || "");
  console.log("data", mySubPlansData);
  const departments: SectorList[] = Array.isArray(data?.data?.items)
    ? data!.data!.items
    : [];
  const teamDepartments: SectorList[] = Array.isArray(
    teamSubPlansData?.data?.items
  )
    ? teamSubPlansData!.data!.items
    : [];

  const myDepartments: SectorList[] = Array.isArray(mySubPlansData?.data)
    ? mySubPlansData.data
    : Array.isArray(mySubPlansData?.data?.items)
    ? mySubPlansData.data.items
    : mySubPlansData?.data && typeof mySubPlansData.data === "object"
    ? // wrap single object into an array
      ([mySubPlansData.data] as SectorList[])
    : [];
  const labels =
    POSITION_TYPE_LABELS[positionType as keyof typeof POSITION_TYPE_LABELS] ||
    POSITION_TYPE_LABELS[EPositionTypeKey.DEPUTY];
  const Icon = labels.icon;
  const { handleError } = useErrorHandler(t);
  // Combined data for tabs
  const allItems = [...departments, ...teamDepartments, ...myDepartments];
  const { requestApproval: requestApprovalMutation } = usePlanMutations();
  const calculateTotalWeight = (items: SectorList[]) => {
    if (items.length === 0) return 0;
    const total = items.reduce(
      (sum, item) => sum + Number(item.total_weight || 0),
      0
    );
    return total;
  };

  // Filter and sort items based on active tab and search
  const getFilteredItems = () => {
    let items: SectorList[] = [];

    switch (activeTab) {
      case "all":
        items = allItems;
        break;
      case "departments":
        items = departments;
        break;
      case "teams":
        items = teamDepartments;
        break;
      case "mine":
        items = myDepartments;
        break;
      default:
        items = allItems;
    }

    // Search filter
    if (searchTerm) {
      items = items.filter((item) =>
        localizedName(item.position_name)
          .toLowerCase()
          .includes(searchTerm.toLowerCase())
      );
    }

    // Sort
    items.sort((a, b) => {
      let aValue: any, bValue: any;

      switch (sortBy) {
        case "name":
          aValue = localizedName(a.position_name).toLowerCase();
          bValue = localizedName(b.position_name).toLowerCase();
          break;
        case "weight":
          aValue = a.total_weight || 0;
          bValue = b.total_weight || 0;
          break;
        case "plans":
          aValue = a.no_of_plans || 0;
          bValue = b.no_of_plans || 0;
          break;
        case "rank":
          aValue = a.position_rank || 0;
          bValue = b.position_rank || 0;
          break;
        default:
          return 0;
      }

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

    return items;
  };
  const [isRequestApprovalDialogOpen, setIsRequestApprovalDialogOpen] =
    useState(false);
  const filteredItems = getFilteredItems();

  const canRequestApproval = useMemo(() => {
    // Get all relevant items (adjust based on your business logic)
    const relevantItems = filteredItems; // Or use allItems depending on your requirement

    if (relevantItems.length === 0) return false;

    // Check if total weight sums to 100%
    const totalWeight = calculateTotalWeight(relevantItems);
    const hasFullWeight = Math.abs(totalWeight - 100) < 0.01; // Allow small floating point differences

    // Additional checks (you can add more as needed):
    const hasPlans = relevantItems.every((item) => (item.no_of_plans || 0) > 0);
    const allActive = relevantItems.every((item) => {
      const plans = item.no_of_plans || 0;
      return plans > 0; // Or plans >= 1 depending on your requirement
    });

    // You can customize this logic based on your exact requirements
    return hasFullWeight && hasPlans && allActive;
  }, [filteredItems]); // Or allItems, depending on which items should be considered

  // Also calculate the current total weight for display
  const currentTotalWeight = useMemo(() => {
    return calculateTotalWeight(filteredItems);
  }, [filteredItems]);
  console.log("canRequestApproval", canRequestApproval);
  console.log("currentTotalWeight", currentTotalWeight);
  const handleDepartmentClick = (item: SectorList, planId: string) => {
    console.log("itemmmmm ", item);
    const departmentId =
      item.planTeam_position_id ?? item.position_id ?? item.positionId;

    const planFor = item.positionId
      ? "self"
      : item.planTeam_id
      ? "team"
      : "position";

    if (yearId) {
      navigate(
        `/performance-management/${yearId}/plans-table/${departmentId}/${planId}/${planFor}`,
        { state: { planFor } }
      );
    }
  };

  const handleCreateSubPlan = (department: SectorList) => {
    const departmentId =
      department?.position_id ||
      department?.positionId ||
      department?.planTeam_position_id;
    if (yearId && planId) {
      navigate(
        `/performance-management/${yearId}/plans/new/${departmentId}/${planId}`
      );
    }
  };

  const getSectorColor = (index: number) => {
    const colors = [
      "bg-gradient-to-br from-blue-500 via-blue-600 to-cyan-500",
      "bg-gradient-to-br from-purple-500 via-purple-600 to-pink-500",
      "bg-gradient-to-br from-green-500 via-green-600 to-emerald-500",
      "bg-gradient-to-br from-orange-500 via-orange-600 to-red-500",
      "bg-gradient-to-br from-indigo-500 via-indigo-600 to-blue-500",
      "bg-gradient-to-br from-teal-500 via-teal-600 to-green-500",
      "bg-gradient-to-br from-rose-500 via-rose-600 to-pink-500",
      "bg-gradient-to-br from-amber-500 via-amber-600 to-orange-500",
    ];
    return colors[index % colors.length];
  };

  const getStatusBadge = (item: SectorList) => {
    const plans = item.no_of_plans || 0;
    if (plans === 0) {
      return (
        <Badge
          variant="outline"
          className="bg-red-50 text-red-700 border-red-200"
        >
          <XCircle className="h-3 w-3 mr-1" />
          {t("departmentListView.noPlansBadge")}
        </Badge>
      );
    } else if (plans >= 5) {
      return (
        <Badge
          variant="outline"
          className="bg-green-50 text-primary-700 border-green-200"
        >
          <CheckCircle className="h-3 w-3 mr-1" />
          {t("departmentListView.activeBadge")}
        </Badge>
      );
    } else {
      return (
        <Badge
          variant="outline"
          className="bg-yellow-50 text-yellow-700 border-yellow-200"
        >
          <AlertCircle className="h-3 w-3 mr-1" />
          {t("departmentListView.partialBadge")}
        </Badge>
      );
    }
  };
  const handleRequestApproval = async () => {
    if (!planId) return;

    requestApprovalMutation.mutate(planId, {
      onSuccess: () => {
        setIsRequestApprovalDialogOpen(false);
        toast.success("Plan deleted successfully");
      },
      onError: (error) => {
        handleError(error);
      },
    });
  };

  const getPerformanceRing = (weight: number) => {
    const percentage = Math.min(Math.max(weight || 0, 0), 100);
    const color =
      percentage >= 90
        ? "stroke-green-500"
        : percentage >= 70
        ? "stroke-blue-500"
        : percentage >= 50
        ? "stroke-yellow-500"
        : "stroke-red-500";

    return (
      <div className="relative w-16 h-16">
        <svg className="w-full h-full transform -rotate-90" viewBox="0 0 36 36">
          <path
            d="M18 2.0845
              a 15.9155 15.9155 0 0 1 0 31.831
              a 15.9155 15.9155 0 0 1 0 -31.831"
            fill="none"
            className="stroke-gray-200"
            strokeWidth="3"
          />
          <path
            d="M18 2.0845
              a 15.9155 15.9155 0 0 1 0 31.831
              a 15.9155 15.9155 0 0 1 0 -31.831"
            fill="none"
            className={color}
            strokeWidth="3"
            strokeDasharray={`${percentage}, 100`}
            strokeLinecap="round"
          />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center">
          <span className="text-sm font-bold">{percentage}%</span>
        </div>
      </div>
    );
  };

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

  if (isLoading) {
    return (
      <div className="p-6 space-y-6">
        <div className="flex justify-between items-center mb-8">
          <div className="space-y-2">
            <Skeleton className="h-8 w-48" />
            <Skeleton className="h-4 w-64" />
          </div>
          <Skeleton className="h-10 w-32" />
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          {[1, 2, 3].map((i) => (
            <Skeleton key={i} className="h-32 rounded-xl" />
          ))}
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <Skeleton key={i} className="h-64 rounded-2xl" />
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-6">
        <Card className="border-red-200 bg-red-50">
          <CardHeader>
            <CardTitle className="text-red-800 flex items-center gap-2">
              <AlertCircle className="h-5 w-5" />
              Error Loading {labels.plural}
            </CardTitle>
            <CardDescription className="text-red-600">
              {error instanceof Error
                ? error.message
                : `Failed to load ${labels.plural.toLowerCase()}`}
            </CardDescription>
          </CardHeader>
          <CardFooter>
            <Button
              variant="outline"
              onClick={() => navigate(-1)}
              className="border-red-200 text-red-600 hover:bg-red-100"
            >
              <ArrowLeft className="mr-2 h-4 w-4" />
              Go Back
            </Button>
          </CardFooter>
        </Card>
      </div>
    );
  }

  if (filteredItems.length === 0 && !searchTerm) {
    return (
      <div className="p-6">
        <Button variant="outline" onClick={() => navigate(-1)} className="mb-6">
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
        <Card className="border-dashed border-2">
          <CardContent className="pt-12 pb-12 text-center">
            <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-gradient-to-r from-blue-100 to-blue-50 flex items-center justify-center">
              <Icon className="h-10 w-10 text-blue-400" />
            </div>
            <h3 className="text-2xl font-bold text-gray-900 mb-3">
              No {labels.plural} Available
            </h3>
            <p className="text-gray-600 max-w-md mx-auto mb-8">
              There are no {labels.plural.toLowerCase()}/sub-plans to display
              for this plan.
            </p>
            <Button
              onClick={() => navigate(-1)}
              className="bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 text-white"
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              Return to Previous Page
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header Section */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="space-y-6"
      >
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4">
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-2">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => navigate(-1)}
                className="text-gray-500 hover:text-gray-700 -ml-2"
              >
                <ArrowLeft className="h-4 w-4 mr-1" />
                {t("departmentListView.back")}
              </Button>
              <Badge
                variant="outline"
                className="bg-blue-50 text-blue-700 border-blue-200"
              >
                <Icon className="h-3 w-3 mr-1" />
                {labels.singular}
              </Badge>
            </div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-900 via-gray-800 to-gray-700 bg-clip-text text-transparent">
              {labels.title}
            </h1>
            <p className="text-gray-600 mt-2 max-w-2xl">{labels.description}</p>
          </div>

          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" className="gap-2">
              <Download className="h-4 w-4" />
              {t("departmentListView.export")}
            </Button>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="sm">
                  <Settings className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem>
                  {t("departmentListView.viewSettings")}
                </DropdownMenuItem>
                <DropdownMenuItem>
                  {t("departmentListView.notificationSettings")}
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem>
                  {t("departmentListView.helpSupport")}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Card className="bg-gradient-to-br from-blue-50 to-blue-100/50 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("departmentListView.total")} {labels.plural}
                  </p>
                  <p className="text-2xl font-bold text-blue-900">
                    {filteredItems.length}
                  </p>
                  <p className="text-xs text-blue-500 mt-1">
                    {t("departmentListView.acrossAllCategories")}
                  </p>
                </div>
                <div className="w-12 h-12 bg-gradient-to-r from-blue-500 to-blue-600 rounded-xl flex items-center justify-center">
                  <Icon className="h-6 w-6 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-green-50 to-green-100/50 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("departmentListView.activePlans")}
                  </p>
                  <p className="text-2xl font-bold text-green-900">
                    {filteredItems.reduce(
                      (sum, item) => sum + Number(item.no_of_plans || 0),
                      0
                    )}
                  </p>
                  <p className="text-xs text-green-500 mt-1">
                    {t("departmentListView.totalSubPlansCreated")}
                  </p>
                </div>
                <div className="w-12 h-12 bg-gradient-to-r from-green-500 to-green-600 rounded-xl flex items-center justify-center">
                  <Target className="h-6 w-6 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-purple-50 to-purple-100/50 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("departmentListView.avgPerformance")}
                  </p>
                  <p className="text-2xl font-bold text-purple-900">
                    {Math.round(
                      filteredItems.reduce(
                        (sum, item) => sum + Number(item.total_weight || 0),
                        0
                      ) / Math.max(filteredItems.length, 1)
                    )}
                    %
                  </p>
                  <p className="text-xs text-purple-500 mt-1">
                    {t("departmentListView.averageWeightAcrossAll")}
                  </p>
                </div>
                <div className="w-12 h-12 bg-gradient-to-r from-purple-500 to-purple-600 rounded-xl flex items-center justify-center">
                  <TrendingUp className="h-6 w-6 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-orange-50 to-orange-100/50 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("departmentListView.completionRate")}
                  </p>
                  <p className="text-2xl font-bold text-orange-900">
                    {Math.round(
                      (filteredItems.filter(
                        (item) => Number(item.no_of_plans || 0) > 0
                      ).length /
                        Math.max(filteredItems.length, 1)) *
                        100
                    )}
                    %
                  </p>
                  <p className="text-xs text-orange-500 mt-1">
                    {labels.plural} {t("departmentListView.completionRateDesc")}
                  </p>
                </div>
                <div className="w-12 h-12 bg-gradient-to-r from-orange-500 to-orange-600 rounded-xl flex items-center justify-center">
                  <CheckCircle className="h-6 w-6 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </motion.div>

      {/* Filters and Controls */}
      <div className="space-y-4">
        <div className="flex flex-col lg:flex-row gap-4">
          {/* Search */}
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              placeholder={`${t(
                "departmentListView.searchDepartments"
              )} ${labels.plural.toLowerCase()}...`}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-9"
            />
          </div>

          {/* Tabs */}
          <Tabs
            defaultValue="all"
            className="w-full lg:w-auto"
            onValueChange={setActiveTab}
          >
            <TabsList className="grid grid-cols-4 w-full lg:w-auto">
              <TabsTrigger value="all" className="flex items-center gap-2">
                <Grid className="h-4 w-4" />
                {t("departmentListView.all")}
                <Badge
                  variant="secondary"
                  className="ml-1 px-1.5 py-0.5 text-xs"
                >
                  {allItems.length}
                </Badge>
              </TabsTrigger>
              <TabsTrigger
                value="departments"
                className="flex items-center gap-2"
              >
                <Building2 className="h-4 w-4" />
                {t("departmentListView.departments")}
                <Badge
                  variant="secondary"
                  className="ml-1 px-1.5 py-0.5 text-xs"
                >
                  {departments.length}
                </Badge>
              </TabsTrigger>
              <TabsTrigger value="teams" className="flex items-center gap-2">
                <Users className="h-4 w-4" />
                {t("departmentListView.teams")}
                <Badge
                  variant="secondary"
                  className="ml-1 px-1.5 py-0.5 text-xs"
                >
                  {teamDepartments.length}
                </Badge>
              </TabsTrigger>
              <TabsTrigger value="mine" className="flex items-center gap-2">
                <UserPlus className="h-4 w-4" />
                {t("departmentListView.mine")}
                <Badge
                  variant="secondary"
                  className="ml-1 px-1.5 py-0.5 text-xs"
                >
                  {myDepartments.length || 1}
                </Badge>
              </TabsTrigger>
            </TabsList>
          </Tabs>
        </div>

        {/* View Controls and Sort */}
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-gray-700">
              {t("departmentListView.view")}:
            </span>
            <div className="inline-flex rounded-lg border border-gray-200 p-1 bg-gray-50">
              <Button
                variant={viewMode === "grid" ? "default" : "ghost"}
                size="sm"
                onClick={() => setViewMode("grid")}
                className="gap-2"
              >
                <Grid className="h-4 w-4" />
                {t("departmentListView.gridView")}
              </Button>
              <Button
                variant={viewMode === "list" ? "default" : "ghost"}
                size="sm"
                onClick={() => setViewMode("list")}
                className="gap-2"
              >
                <List className="h-4 w-4" />
                {t("departmentListView.listView")}
              </Button>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {canRequestApproval && (
              <motion.div
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                className="relative"
              >
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        variant="outline"
                        size="lg"
                        className="w-9 h-9 p-0 bg-gradient-to-r from-green-50 to-emerald-50 border-green-200 text-primary-600 hover:bg-primary-100 hover:text-primary-700 hover:border-green-300 group relative overflow-hidden"
                        onClick={() => setIsRequestApprovalDialogOpen(true)}
                        disabled={requestApprovalMutation.isPending}
                      >
                        {/* Animated background effect */}
                        <div className="absolute inset-0 bg-gradient-to-r from-green-400/10 to-emerald-400/10 opacity-0 group-hover:opacity-100 transition-opacity duration-300" />

                        {/* Pulsing animation when ready for approval */}
                        <motion.div
                          className="absolute inset-0 border-2 border-green-400 rounded-lg"
                          animate={{
                            scale: [1, 1.05, 1],
                            opacity: [0.5, 0.8, 0.5],
                          }}
                          transition={{
                            duration: 2,
                            repeat: Infinity,
                            repeatType: "loop",
                          }}
                        />

                        <Send className="h-4 w-4 relative z-10" />
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent side="bottom">
                      <p>{t("departmentListView.allPlansTotal100")}</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              </motion.div>
            )}

            {/* If not ready for approval, show a disabled button with explanation */}
            {!canRequestApproval && (
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant="outline"
                      size="lg"
                      className="w-9 h-9 p-0 bg-gray-50 border-gray-200 text-gray-400 cursor-not-allowed relative"
                      disabled
                    >
                      <Send className="h-4 w-4" />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent side="bottom" className="max-w-xs">
                    <div className="space-y-2">
                      <p className="font-medium">
                        {t("departmentListView.approvalRequirementsNotMet")}:
                      </p>
                      <ul className="text-sm space-y-1">
                        <li className="flex items-center gap-1">
                          {Math.abs(currentTotalWeight - 100) < 0.01 ? (
                            <CheckCircle className="h-3 w-3 text-green-500" />
                          ) : (
                            <XCircle className="h-3 w-3 text-red-500" />
                          )}
                          {t("departmentListView.totalWeightMust100")} (
                          {t("departmentListView.current")}:{" "}
                          {currentTotalWeight.toFixed(1)}%)
                        </li>
                        <li className="flex items-center gap-1">
                          <CheckCircle className="h-3 w-3 text-green-500" />
                          {t("departmentListView.allDepartmentsMustHavePlans")}
                        </li>
                        <li className="flex items-center gap-1">
                          <CheckCircle className="h-3 w-3 text-green-500" />
                          {t("departmentListView.allPlansMustBeActive")}
                        </li>
                      </ul>
                      <p className="text-xs text-gray-500 pt-1">
                        {t("departmentListView.completeAllRequirements")} to
                        enable approval request
                      </p>
                    </div>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            )}
          </div>
          <div className="flex items-center gap-4">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="sm" className="gap-2">
                  <Filter className="h-4 w-4" />
                  {t("departmentListView.sort")}
                  {sortOrder === "asc" ? (
                    <ChevronUp className="h-4 w-4" />
                  ) : (
                    <ChevronDown className="h-4 w-4" />
                  )}
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => handleSort("name")}>
                  {t("departmentListView.name")}{" "}
                  {sortBy === "name" && (sortOrder === "asc" ? "↑" : "↓")}
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => handleSort("weight")}>
                  {t("departmentListView.weight")}{" "}
                  {sortBy === "weight" && (sortOrder === "asc" ? "↑" : "↓")}
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => handleSort("plans")}>
                  {t("departmentListView.plans")}{" "}
                  {sortBy === "plans" && (sortOrder === "asc" ? "↑" : "↓")}
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => handleSort("rank")}>
                  {t("departmentListView.rank")}{" "}
                  {sortBy === "rank" && (sortOrder === "asc" ? "↑" : "↓")}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </div>

      {/* Departments Grid/List View */}
      <AnimatePresence mode="wait">
        {viewMode === "grid" ? (
          <motion.div
            key="grid"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-6"
          >
            {filteredItems.map((item, index) => (
              <motion.div
                key={item.position_id}
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: index * 0.05 }}
                className="group"
              >
                <Card className="h-full hover:shadow-xl transition-all duration-300 border border-gray-200/50 hover:border-blue-300 overflow-hidden hover:-translate-y-1">
                  {/* Card Header with Gradient */}
                  <div
                    className={`${getSectorColor(
                      index
                    )} p-6 relative overflow-hidden`}
                  >
                    <div className="flex items-center justify-between mb-4">
                      <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-sm">
                        <Icon className="h-6 w-6 text-white" />
                      </div>
                      <motion.div
                        whileHover={{ x: 5 }}
                        className="opacity-0 group-hover:opacity-100 transition-opacity duration-300"
                      >
                        <ArrowRight className="h-5 w-5 text-white/80" />
                      </motion.div>
                    </div>

                    <div className="flex items-center justify-between">
                      <h3 className="text-lg font-bold text-white line-clamp-2 pr-2">
                        {localizedName(
                          item.position_name || item?.planTeam_name
                        ) || t("departmentListView.myDepartment")}
                      </h3>
                      {getStatusBadge(item)}
                    </div>
                  </div>

                  {/* Card Content */}
                  <CardContent className="p-6 space-y-4">
                    {/* Performance Ring */}
                    <div className="flex items-center justify-between">
                      {getPerformanceRing(item.total_weight || 0)}
                      <div className="space-y-2 flex-1 pl-4">
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <Target className="h-4 w-4 text-blue-500" />
                            <span className="text-sm font-medium">
                              {t("departmentListView.plans")}
                            </span>
                          </div>
                          <span className="font-bold">
                            {item.no_of_plans || 0}
                          </span>
                        </div>
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <TrendingUp className="h-4 w-4 text-green-500" />
                            <span className="text-sm font-medium">
                              {t("departmentListView.weight")}
                            </span>
                          </div>
                          <span className="font-bold">
                            {item.total_weight || 0}%
                          </span>
                        </div>
                      </div>
                    </div>

                    {/* Progress Bar */}
                    {item.total_weight && (
                      <div className="space-y-2">
                        <div className="flex justify-between text-xs text-gray-500">
                          <span>{t("departmentListView.progress")}</span>
                          <span>{item.total_weight}%</span>
                        </div>
                        <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                          <motion.div
                            initial={{ width: 0 }}
                            animate={{ width: `${item.total_weight}%` }}
                            transition={{ duration: 1, delay: 0.2 }}
                            className={`h-full rounded-full ${
                              item.total_weight >= 90
                                ? "bg-green-500"
                                : item.total_weight >= 70
                                ? "bg-blue-500"
                                : item.total_weight >= 50
                                ? "bg-yellow-500"
                                : "bg-red-500"
                            }`}
                          />
                        </div>
                      </div>
                    )}

                    {/* Action Buttons */}
                    <div className="flex items-center gap-2 pt-4">
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              onClick={() =>
                                handleDepartmentClick(item, planId as string)
                              }
                              variant="outline"
                              size="sm"
                              className="flex-1 border-blue-200 text-blue-600 hover:bg-blue-50 hover:text-blue-700"
                            >
                              <Eye className="h-4 w-4 mr-1" />
                              {t("departmentListView.view")}
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>
                            <p>
                              {t("departmentListView.viewDetails")}{" "}
                              {labels.singular.toLowerCase()}
                            </p>
                          </TooltipContent>
                        </Tooltip>
                      </TooltipProvider>

                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              onClick={() => handleCreateSubPlan(item)}
                              size="sm"
                              className="flex-1 bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 text-white"
                            >
                              <PlusIcon className="h-4 w-4 mr-1" />
                              {t("departmentListView.newPlan")}
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>
                            <p>
                              {t("departmentListView.newPlan")}{" "}
                              {labels.singular.toLowerCase()}
                            </p>
                          </TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </div>
                  </CardContent>

                  {/* Card Footer */}
                  <CardFooter className="px-6 pb-6 pt-0">
                    <div className="flex items-center justify-between text-xs text-gray-500 w-full">
                      <div className="flex items-center gap-1">
                        <Clock className="h-3 w-3" />
                        <span>{t("departmentListView.updatedRecently")}</span>
                      </div>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 w-8 p-0"
                          >
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem>
                            {t("departmentListView.viewDetailsAction")}
                          </DropdownMenuItem>
                          <DropdownMenuItem>
                            {t("departmentListView.managePermissions")}
                          </DropdownMenuItem>
                          <DropdownMenuItem>
                            {t("departmentListView.viewReports")}
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem className="text-red-600">
                            {t("departmentListView.archive")}
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </CardFooter>
                </Card>
              </motion.div>
            ))}
          </motion.div>
        ) : (
          <motion.div
            key="list"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="space-y-4"
          >
            <Card className="overflow-hidden">
              <CardContent className="p-0">
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          {labels.singular}
                        </th>

                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          {t("departmentListView.plans")}
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          {t("departmentListView.weight")}
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          {t("departmentListView.status")}
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          {t("departmentListView.actions")}
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                      {filteredItems.map((item, index) => (
                        <tr
                          key={item.position_id}
                          className="hover:bg-gray-50 transition-colors cursor-pointer"
                          onClick={() =>
                            handleDepartmentClick(item, planId as string)
                          }
                        >
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="flex items-center gap-3">
                              <div
                                className={`w-10 h-10 ${getSectorColor(
                                  index
                                )} rounded-lg flex items-center justify-center`}
                              >
                                <Icon className="h-5 w-5 text-white" />
                              </div>
                              <div>
                                <div className="font-medium text-gray-900">
                                  {localizedName(item.position_name)}
                                </div>
                                <div className="text-sm text-gray-500">
                                  {labels.singular} ID: {item.position_id}
                                </div>
                              </div>
                            </div>
                          </td>

                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="flex items-center gap-2">
                              <Target className="h-4 w-4 text-blue-500" />
                              <span className="font-medium">
                                {item.no_of_plans || 0}
                              </span>
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="flex items-center gap-2">
                              <TrendingUp className="h-4 w-4 text-green-500" />
                              <span
                                className={`font-medium ${
                                  (item.total_weight || 0) >= 90
                                    ? "text-primary-600"
                                    : (item.total_weight || 0) >= 70
                                    ? "text-blue-600"
                                    : (item.total_weight || 0) >= 50
                                    ? "text-yellow-600"
                                    : "text-red-600"
                                }`}
                              >
                                {item.total_weight || 0}%
                              </span>
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            {getStatusBadge(item)}
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="flex items-center gap-2">
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleCreateSubPlan(item);
                                }}
                                className="text-blue-600 hover:text-blue-700 hover:bg-blue-50"
                              >
                                <PlusIcon className="h-4 w-4" />
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleDepartmentClick(item, planId as string);
                                }}
                                className="text-gray-600 hover:text-gray-700 hover:bg-gray-50"
                              >
                                <Eye className="h-4 w-4" />
                              </Button>
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button
                                    size="sm"
                                    variant="ghost"
                                    onClick={(e) => e.stopPropagation()}
                                    className="h-8 w-8 p-0"
                                  >
                                    <MoreVertical className="h-4 w-4" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  <DropdownMenuItem>
                                    {t("departmentListView.viewDetails")}
                                  </DropdownMenuItem>
                                  <DropdownMenuItem>
                                    {t("departmentListView.exportData")}
                                  </DropdownMenuItem>
                                  <DropdownMenuItem>
                                    {t("departmentListView.manageAccess")}
                                  </DropdownMenuItem>
                                  <DropdownMenuSeparator />
                                  <DropdownMenuItem>
                                    {t("departmentListView.archive")}
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Empty State for Search */}
      {filteredItems.length === 0 && searchTerm && (
        <Card className="border-dashed border-2">
          <CardContent className="pt-12 pb-12 text-center">
            <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-gradient-to-r from-gray-100 to-gray-50 flex items-center justify-center">
              <Search className="h-10 w-10 text-gray-400" />
            </div>
            <h3 className="text-xl font-bold text-gray-900 mb-3">
              {t("departmentListView.noResultsFound")}
            </h3>
            <p className="text-gray-600 max-w-md mx-auto mb-8">
              {t("departmentListView.noResultsDesc")}{" "}
              {labels.plural.toLowerCase()}{" "}
              {t("departmentListView.noResultsDesc")} "{searchTerm}".{" "}
              {t("departmentListView.tryDifferentSearch")}.
            </p>
            <Button
              variant="outline"
              onClick={() => setSearchTerm("")}
              className="gap-2"
            >
              <XCircle className="h-4 w-4" />
              {t("departmentListView.clearSearch")}
            </Button>
          </CardContent>
        </Card>
      )}
      <AlertDialog
        open={isRequestApprovalDialogOpen}
        onOpenChange={setIsRequestApprovalDialogOpen}
      >
        <AlertDialogContent className="bg-white border-0 shadow-2xl rounded-2xl">
          <AlertDialogHeader>
            <div className="w-12 h-12 bg-blue-100 rounded-2xl flex items-center justify-center mb-4">
              <Send className="h-6 w-6 text-blue-500" />
            </div>
            <AlertDialogTitle className="text-xl font-bold text-gray-900">
              {t("departmentListView.confirmRequestApproval")}
            </AlertDialogTitle>
            <AlertDialogDescription className="text-gray-600">
              {t("departmentListView.requestApprovalDesc")}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel
              onClick={() => {
                setIsRequestApprovalDialogOpen(false);
              }}
              disabled={requestApprovalMutation.isPending}
              className="border-gray-300 text-gray-700 hover:bg-gray-50"
            >
              {t("departmentListView.cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleRequestApproval}
              disabled={requestApprovalMutation.isPending}
              className="bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white shadow-lg shadow-blue-500/25"
            >
              {requestApprovalMutation.isPending ? (
                <>
                  <div className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent mr-2" />
                  {t("departmentListView.approvalRequesting")}
                </>
              ) : (
                t("departmentListView.requestApproval")
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};
