/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState, useEffect, useMemo, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { useToast } from "@/shared/common/ui/use-toast";
import { useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { FormField } from "@/performance-management/utils/shared-field-types";
// Import your existing components
import { Button } from "@/shared/common/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import { Badge } from "@/shared/common/ui/badge";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Input } from "@/shared/common/ui/input";
import { Avatar, AvatarFallback } from "@/shared/common/ui/avatar";
import {
  Check,
  CheckCheckIcon,
  ChevronDown,
  ChevronUp,
  ClipboardList,
  ClockIcon,
  Download,
  Edit,
  Eye,
  Grid3x3,
  Loader2,
  MoreVertical,
  PlusIcon,
  RefreshCw,
  Search,
  Trash2,
  TrendingUp,
  UserPlus,
  Users,
  X,
} from "lucide-react";

// ADD THESE NEW IMPORTS
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";

import {
  usePlanTeamMutation,
  usePlanTeamList,
  usePlanTeamMemberList,
} from "@/performance-management/hooks/useTeamMemeberHook";
import useSettings from "@/record-management/components/hooks/useSettings";
import { useAuthUser } from "@/record-management/hooks/useAuthUser";
import { useAuth } from "@/shared/context/AuthContext";
import {
  CreatePlanBulkTeamMemberDto,
  CreatePlanTeamDto,
} from "@/performance-management/services/api/planTeamServices";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useTranslation } from "react-i18next";
import { GenericForm } from "@/performance-management/utils/generic-form";
import { useLocalizedName } from "@/shared/common/localizedName";

interface Memebers {
  createdAt: string;
  updatedAt: string;
  amharicCreatedAt: string;
  amharicUpdatedAt: string | null;
  id: string;
  planTeamId: string;
  employeePositionId: string;
  isActive: boolean;
  employeePosition: {
    createdAt: string;
    updatedAt: string;
    id: string;
    isDelegate: boolean;
    isCurrent: boolean;
    startDate: string;
    amharicStartDate: string;
    endDate: string | null;
    amharicEndDate: string | null;
    unitId: string;
    delegatorId: string | null;
    employeeId: string;
    positionId: string;
    delegationLetterId: string | null;
    employee: {
      createdAt: string;
      updatedAt: string;
      id: string;
      isCurrent: boolean;
      status: string;
      name: {
        am: string;
        en: string;
      };
      organizationId: string;
      unitId: string;
      userId: string;
    };
  };
}

// Types - No changes needed here
interface PlanTeamFormValues {
  id?: string;
  nameAm: string;
  nameEn: string;
  descriptionAm?: string;
  descriptionEn?: string;
  teamLeaderId: string;
  positionId: string;
}

interface TeamMemberValues {
  employeePositionId: string;
}
const TeamsManagement = () => {
  const navigate = useNavigate();
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // State - No changes needed here
  const [selectedTeam, setSelectedTeam] = useState<PlanTeamFormValues | null>(
    null,
  );
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [teamToDelete, setTeamToDelete] = useState<string | null>(null);
  const [viewType, setViewType] = useState<"table" | "grid">("table");
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [sortBy, setSortBy] = useState<
    "name" | "members" | "performance" | "date"
  >("name");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
  const [showArchived, setShowArchived] = useState(false);
  const [teamDialogOpen, setTeamDialogOpen] = useState(false);
  const [teamMemberDialogOpen, setTeamMemberDialogOpen] = useState(false);
  const [selectedPositionId, setSelectedPositionId] = useState<string>("");

  const [currentTeamForMembers, setCurrentTeamForMembers] = useState<any>(null);
  const [selectedMemberIds, setSelectedMemberIds] = useState<string[]>([]);
  const { t } = useTranslation();
  const localizedName = useLocalizedName();

  const initialPlanTeamFormValues = useMemo(
    () => ({
      nameAm: "",
      nameEn: "",
      descriptionAm: "",
      descriptionEn: "",
      teamLeaderId: "",
      positionId: "",
    }),
    [],
  );

  // Forms - No changes needed here
  const teamForm = useForm<PlanTeamFormValues>({
    defaultValues: initialPlanTeamFormValues,
  });

  const teamMemberForm = useForm<TeamMemberValues>({
    defaultValues: {
      employeePositionId: "",
    },
  });

  const { userDetails } = useAuthUser();
  const { selectedPositionId: globalSelectedPositionId } = useAuth();

  // Get user's positions - No changes needed here
  const userPositions = useMemo(() => {
    if (!userDetails?.employee) return [];
    return userDetails.employee.flatMap((emp: any) =>
      emp.positions.map((pos: any) => ({
        id: pos.id,
        employeePositionId: pos.employeePositionId,
        name: localizedName(pos.name),
        positionId: pos.id,
      })),
    );
  }, [userDetails, localizedName]);

  // Map the globally-selected position (which may be an employeePositionId or a
  // delegation position id) to the underlying position id used by this page.
  const resolvedGlobalPositionId = useMemo(() => {
    if (!globalSelectedPositionId) return "";
    const match = userPositions.find(
      (p: any) =>
        p.employeePositionId === globalSelectedPositionId ||
        p.id === globalSelectedPositionId,
    );
    return match?.id ?? "";
  }, [globalSelectedPositionId, userPositions]);

  // Sync the local selection with the global position picker so that switching
  // position from the topbar updates the team list shown here.
  useEffect(() => {
    if (resolvedGlobalPositionId) {
      setSelectedPositionId(resolvedGlobalPositionId);
    } else if (userPositions.length > 0 && !selectedPositionId) {
      setSelectedPositionId(userPositions[0].id);
    }
  }, [resolvedGlobalPositionId, userPositions, selectedPositionId]);

  // Custom hooks for data fetching and mutations - Fixed to prevent API calls with empty position ID
  const {
    data: teamsData,
    isLoading: teamsLoading,
    refetch: refetchTeams,
  } = usePlanTeamList(selectedPositionId, {
    enabled: !!selectedPositionId, // Only fetch when we have a valid position ID
  });

  const { handleError } = useErrorHandler(t);
  const { alluser: usersData, isLoading: usersLoading } = useSettings();
  const {
    createPlanTeam: createTeam,
    updatePlanTeam: updateTeam,
    deletePlanTeam: deleteTeam,
    deletePlanTeamMember: deleteTeamMember,
    createPlanBulkTeamMember: createBulkTeamMember,
    isPlanTeamLoading,
  } = usePlanTeamMutation();

  // Extract data from hooks - Made stable to prevent re-renders
  const teams = useMemo(
    () => teamsData?.data?.items || [],
    [teamsData?.data?.items],
  );
  const users = useMemo(() => usersData || [], [usersData]);

  // Helper function to get display name - Made stable with useCallback
  const getDisplayName = useCallback(
    (nameObj: any): string => {
      if (!nameObj) return "";
      if (typeof nameObj === "string") return nameObj;
      if (nameObj && typeof nameObj === "object") {
        const result = localizedName(nameObj);
        return result || "";
      }
      return String(nameObj || "");
    },
    [localizedName],
  );

  // Get all users for team leader selection (filtered by position) - Fixed dependencies
  const userOptions = useMemo(() => {
    if (!users.length || !selectedPositionId) return [];

    return users.flatMap((user) =>
      user.employeePositions.map((pos) => ({
        value: pos.id,
        label: `${localizedName(user?.name)} - ${localizedName(
          pos?.position?.name,
        )}`,
        userId: user.id,
        userName: localizedName(user.name),
        positionName: localizedName(pos.position.name),
      })),
    );
  }, [users, selectedPositionId, localizedName]);

  // Get available users for team members (exclude already added members) - Fixed dependencies
  const getAvailableUsersForTeam = useMemo(() => {
    if (!userOptions.length || !currentTeamForMembers) return userOptions;

    const existingMemberIds =
      currentTeamForMembers.members
        ?.map((member: any) => {
          return (
            member.employeePositionId ||
            member.employeePosition?.id ||
            member.positionId || // fallback
            null
          );
        })
        .filter(Boolean) || [];

    return userOptions.filter(
      (option) =>
        !existingMemberIds.includes(option.value) &&
        option.value !== currentTeamForMembers.teamLeaderId,
    );
  }, [userOptions, currentTeamForMembers]);

  // Effects - No changes needed here
  useEffect(() => {
    if (selectedTeam && teamDialogOpen) {
      teamForm.reset({
        nameAm: selectedTeam.nameAm,
        nameEn: selectedTeam.nameEn,
        descriptionAm: selectedTeam.descriptionAm || "",
        descriptionEn: selectedTeam.descriptionEn || "",
        teamLeaderId: selectedTeam.teamLeaderId || "",
      });
    } else if (!teamDialogOpen) {
      teamForm.reset(initialPlanTeamFormValues);
    }
  }, [selectedTeam, teamDialogOpen, teamForm, initialPlanTeamFormValues]);

  // Filter and sort teams - Fixed dependencies to prevent infinite re-renders
  const filteredTeams = useMemo(() => {
    let filtered = [...teams];

    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      filtered = filtered.filter((team) => {
        const name = getDisplayName(team.name).toLowerCase();
        const description =
          getDisplayName(team.description)?.toLowerCase() || "";
        return name.includes(term) || description.includes(term);
      });
    }

    if (statusFilter !== "all") {
      filtered = filtered.filter((team) => team.status === statusFilter);
    }

    if (!showArchived) {
      filtered = filtered.filter((team) => team.status !== "archived");
    }

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

      switch (sortBy) {
        case "name":
          aValue = getDisplayName(a.name).toLowerCase();
          bValue = getDisplayName(b.name).toLowerCase();
          break;
        case "members":
          aValue = a.members?.length || 0;
          bValue = b.members?.length || 0;
          break;
        case "performance":
          aValue = a.averagePerformance || 0;
          bValue = b.averagePerformance || 0;
          break;
        case "date":
          aValue = new Date(a.createdAt).getTime();
          bValue = new Date(b.createdAt).getTime();
          break;
        default:
          return 0;
      }

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

    return filtered;
  }, [
    teams,
    searchTerm,
    statusFilter,
    showArchived,
    sortBy,
    sortOrder,
    getDisplayName,
  ]);

  // helper function for member
  const TeamMembersHoverCard = ({
    teamId,
    teamName,
  }: {
    teamId: string;
    teamName: string;
  }) => {
    const { data: membersData } = usePlanTeamMemberList(teamId);
    const [showTooltip, setShowTooltip] = useState(false);

    const members: Memebers[] = membersData?.data?.items || [];

    return (
      <div
        className="relative"
        onMouseEnter={() => setShowTooltip(true)}
        onMouseLeave={() => setShowTooltip(false)}
      >
        <div className="flex -space-x-2">
          {members.slice(0, 3).map((member: any) => (
            <Avatar
              key={member.id}
              className="h-8 w-8 border-2 border-white cursor-help"
            >
              <AvatarFallback className="bg-gradient-to-r from-blue-100 to-blue-50 text-blue-600 text-xs">
                {member.employeePosition.employee.name.en?.charAt(0) || "U"}
              </AvatarFallback>
            </Avatar>
          ))}
          {members.length > 3 && (
            <div className="h-8 w-8 rounded-full bg-gradient-to-r from-gray-100 to-gray-50 border-2 border-white flex items-center justify-center text-xs text-gray-600">
              +{members.length - 3}
            </div>
          )}
          <Badge variant="outline" className="bg-gray-50">
            {members.length || 0} members
          </Badge>
        </div>

        {showTooltip && members.length > 0 && (
          <div className="absolute z-50 top-full left-0 mb-2 p-3 bg-green-900 text-white text-xs rounded-lg shadow-xl min-w-[200px]">
            <div className="font-semibold mb-2 text-sm">
              Team {teamName} Members
            </div>
            <div className="space-y-2 max-h-60 overflow-y-auto">
              {members.map((member: any) => (
                <div
                  key={member.id}
                  className="flex items-center gap-2 p-2 hover:bg-gray-800 rounded"
                >
                  <Avatar className="h-6 w-6">
                    <AvatarFallback className="bg-blue-500 text-white text-xs">
                      {member.employeePosition?.employee?.name?.en.charAt(0) ||
                        "U"}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <div className="font-medium truncate">
                      {getDisplayName(
                        member.employeePosition?.employee?.name,
                      ) ||
                        t(
                          "teamMemberManagement.unknownMember",
                          "Unknown Member",
                        )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div className="absolute top-full left-4 border-4 border-transparent border-t-gray-900"></div>
          </div>
        )}
      </div>
    );
  };

  // Calculate statistics - Fixed dependencies
  const stats = useMemo(() => {
    const total = filteredTeams.length;
    const active = filteredTeams.filter((t) => t.status === "active").length;
    const totalMembers = filteredTeams.reduce(
      (sum, team) => sum + (team.members?.length || 0),
      0,
    );
    const avgPerformance =
      filteredTeams.length > 0
        ? filteredTeams.reduce(
            (sum, team) => sum + (team.averagePerformance || 0),
            0,
          ) / filteredTeams.length
        : 0;

    return {
      total,
      active,
      totalMembers,
      avgPerformance: parseFloat(avgPerformance.toFixed(1)),
    };
  }, [filteredTeams]);

  // Handlers - No changes needed here
  const handleCreateTeam = () => {
    setSelectedTeam(null);
    setTeamDialogOpen(true);
  };

  const handleEditTeam = (team: any) => {
    setSelectedTeam({
      id: team.id,
      nameAm: team.name?.am || "",
      nameEn: team.name?.en || "",
      descriptionAm: team.description?.am || "",
      descriptionEn: team.description?.en || "",
      teamLeaderId: team.teamLeaderId,
      positionId: team.positionId,
    });
    setTeamDialogOpen(true);
  };

  const handleDeleteClick = (teamId: string) => {
    setTeamToDelete(teamId);
    setDeleteDialogOpen(true);
  };

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

    try {
      await deleteTeam({ id: teamToDelete });
      toast({
        title: t("common.success", "Success"),
        description: t("teamMemberManagement.teamDeleted"),
      });
      setDeleteDialogOpen(false);
      setTeamToDelete(null);
      queryClient.invalidateQueries({ queryKey: ["plan-team-list"] });
    } catch (error) {
      handleError(error);
    }
  };

  const handleTeamSubmit = async (values: PlanTeamFormValues) => {
    try {
      const selectedLeader = userOptions.find(
        (user) => user.value === values.teamLeaderId,
      );

      if (!selectedLeader) {
        toast({
          title: t("common.error", "Error"),
          description: t("teamMemberManagement.selectValidLeader"),
          variant: "destructive",
        });
        return;
      }

      const teamData: CreatePlanTeamDto = {
        name: { am: values.nameAm, en: values.nameEn },
        description: {
          am: values.descriptionAm || "",
          en: values.descriptionEn || "",
        },
        teamLeaderId: values.teamLeaderId,
        positionId: selectedPositionId,
      };

      if (selectedTeam?.id) {
        await updateTeam({ id: selectedTeam.id, data: teamData });
        toast({
          title: t("common.success", "Success"),
          description: t("teamMemberManagement.teamUpdated"),
        });
      } else {
        await createTeam({ data: teamData });
        toast({
          title: t("common.success", "Success"),
          description: t("teamMemberManagement.teamCreated"),
        });
      }

      setTeamDialogOpen(false);
      queryClient.invalidateQueries({ queryKey: ["plan-team-list"] });
    } catch (error) {
      handleError(error);
    }
  };

  const handleAddTeamMember = (team: any) => {
    setCurrentTeamForMembers(team);
    setTeamMemberDialogOpen(true);
    setSelectedMemberIds([]);
  };

  const handleTeamMemberSubmit = async (values: TeamMemberValues) => {
    if (!currentTeamForMembers) return;

    try {
      // Normalize to an array because CreatePlanBulkTeamMemberDto expects string[]
      const employeePositions: string[] = Array.isArray(
        values.employeePositionId,
      )
        ? values.employeePositionId
        : values.employeePositionId
          ? [values.employeePositionId]
          : [];

      if (!employeePositions || employeePositions.length === 0) {
        toast({
          title: t("common.error", "Error"),
          description: t("teamMemberManagement.selectTeamMember"),
          variant: "destructive",
        });
        return;
      }

      const teamMemberData: CreatePlanBulkTeamMemberDto = {
        planTeamId: currentTeamForMembers.id,
        employeePositionIds: employeePositions,
      };

      await createBulkTeamMember({ data: teamMemberData });

      toast({
        title: t("common.success", "Success"),
        description: t("teamMemberManagement.memberAdded"),
      });

      setTeamMemberDialogOpen(false);
      teamMemberForm.reset();
      queryClient.invalidateQueries({ queryKey: ["plan-team-list"] });
    } catch (error) {
      handleError(error);
    }
  };

  const handleRemoveTeamMember = async (memberId: string) => {
    if (!currentTeamForMembers) return;

    try {
      await deleteTeamMember(memberId);
      toast({
        title: t("common.success", "Success"),
        description: t("teamMemberManagement.memberRemoved"),
      });
      queryClient.invalidateQueries({ queryKey: ["plan-team-list"] });
    } catch (error) {
      handleError(error);
    }
  };

  const handleRemoveMultipleMembers = async () => {
    if (!currentTeamForMembers || selectedMemberIds.length === 0) return;

    try {
      const deletePromises = selectedMemberIds.map((memberId) =>
        deleteTeamMember(memberId),
      );
      await Promise.all(deletePromises);

      toast({
        title: t("common.success", "Success"),
        description: `${selectedMemberIds.length} ${t(
          "teamMemberManagement.membersRemovedSuccessfully",
          "team members removed successfully",
        )}`,
      });

      setSelectedMemberIds([]);
      queryClient.invalidateQueries({ queryKey: ["plan-team-list"] });
    } catch (error) {
      handleError(error);
    }
  };

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

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      active: {
        bg: "bg-green-50",
        text: "text-primary-700",
        border: "border-green-200",
        label: t("teamMemberManagement.active"),
        icon: <Check className="h-3 w-3 mr-1" />,
      },
      inactive: {
        bg: "bg-yellow-50",
        text: "text-yellow-700",
        border: "border-yellow-200",
        label: t("teamMemberManagement.inactive"),
        icon: <ClockIcon className="h-3 w-3 mr-1" />,
      },
      archived: {
        bg: "bg-gray-50",
        text: "text-gray-700",
        border: "border-gray-200",
        label: t("teamMemberManagement.archived"),
        icon: <ArchiveIcon className="h-3 w-3 mr-1" />,
      },
    };

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

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

  const getPerformanceColor = (score?: number) => {
    if (!score) return "bg-gradient-to-r from-gray-300 to-gray-400";
    if (score >= 90) return "bg-gradient-to-r from-green-500 to-emerald-500";
    if (score >= 70) return "bg-gradient-to-r from-blue-500 to-cyan-500";
    if (score >= 50) return "bg-gradient-to-r from-yellow-500 to-amber-500";
    return "bg-gradient-to-r from-red-500 to-rose-500";
  };

  const formatDate = (dateString: string) => {
    try {
      return new Intl.DateTimeFormat("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
      }).format(new Date(dateString));
    } catch {
      return dateString;
    }
  };

  // Handle export - No changes needed here
  const handleExport = () => {
    toast({
      title: "Export Started",
      description:
        "Teams data is being exported. You'll receive a download link shortly.",
    });
  };

  // Form fields - No changes needed here
  const planFormFields: FormField<PlanTeamFormValues>[] = [
    {
      name: "nameAm",
      label: t("teamMemberManagement.nameAmharic", "Name Amharic"),
      type: "text",
      required: true,
    },
    {
      name: "nameEn",
      label: t("teamMemberManagement.nameEnglish", "Name English"),
      type: "text",
      required: true,
    },
    {
      name: "descriptionAm",
      label: t(
        "teamMemberManagement.descriptionAmharic",
        "Description Amharic",
      ),
      type: "textarea",
    },
    {
      name: "descriptionEn",
      label: "Description English",
      type: "textarea",
    },
    {
      name: "teamLeaderId",
      label: t("teamMemberManagement.teamLeader"),
      type: "select",
      options: userOptions,
      required: true,
    },
  ];

  const teamMemberFormFields: FormField<TeamMemberValues>[] = [
    {
      name: "employeePositionId",
      label: t("teamMemberManagement.teamMember", "Team Member"),
      type: "multiselect",
      options: getAvailableUsersForTeam,
      required: true,
    },
  ];

  const handleCancel = (): void => {
    setTeamDialogOpen(false);
    teamForm.reset();
  };

  const handleTeamMemberCancel = (): void => {
    setTeamMemberDialogOpen(false);
    teamMemberForm.reset();
    setSelectedMemberIds([]);
  };

  // Combined loading state - No changes needed here
  const isLoading = teamsLoading || usersLoading || isPlanTeamLoading;

  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">
        {/* Header - No changes needed here */}
        <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-blue-500 to-blue-600 rounded-lg">
                <Users className="h-6 w-6 text-white" />
              </div>
              <h1 className="text-3xl font-bold text-gray-900">
                {t("teamMemberManagement.title")}
              </h1>
            </div>
            <p className="text-gray-600">
              {t("teamMemberManagement.description")}
            </p>
            {selectedPositionId && (
              <div className="mt-2">
                <Badge
                  variant="outline"
                  className="bg-blue-50 text-blue-700 border-blue-200"
                >
                  Viewing teams for:{" "}
                  {getDisplayName(
                    userPositions.find((p: any) => p.id === selectedPositionId)
                      ?.name,
                  )}
                </Badge>
              </div>
            )}
          </div>
          <div className="flex items-center gap-4">
            {/* Position Selector */}
            {userPositions.length > 1 && (
              <div className="min-w-[200px]">
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  Select Position
                </label>
                <Select
                  value={selectedPositionId}
                  onValueChange={setSelectedPositionId}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select position" />
                  </SelectTrigger>
                  <SelectContent>
                    {userPositions.map((position: any) => (
                      <SelectItem key={position.id} value={position.id}>
                        {getDisplayName(position.name)}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
            <Button
              variant="outline"
              onClick={() => refetchTeams()}
              disabled={teamsLoading}
              className="gap-2"
            >
              {teamsLoading ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <RefreshCw className="h-4 w-4" />
              )}
              {t("teamMemberManagement.refresh")}
            </Button>
            <Button
              onClick={handleCreateTeam}
              disabled={isPlanTeamLoading || !selectedPositionId}
              className="bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 text-white gap-2"
            >
              {isPlanTeamLoading ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <PlusIcon className="h-4 w-4" />
              )}
              {t("teamMemberManagement.createTeam")}
            </Button>
          </div>
        </div>

        {/* Stats Overview - No changes needed here */}
        <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-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("teamMemberManagement.totalTeams")}
                  </p>
                  <p className="text-3xl font-bold text-blue-900">
                    {stats.total}
                  </p>
                  <p className="text-xs text-blue-500 mt-2">
                    {t(
                      "teamMemberManagement.activePerformanceTeams",
                      "Active performance teams",
                    )}
                  </p>
                </div>
                <div className="p-3 bg-gradient-to-r from-blue-100 to-blue-200 rounded-xl">
                  <Users 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("teamMemberManagement.activeTeams")}
                  </p>
                  <p className="text-3xl font-bold text-green-900">
                    {stats.active}
                  </p>
                  <p className="text-xs text-green-500 mt-2">
                    {t(
                      "teamMemberManagement.currentlyActive",
                      "Currently active",
                    )}
                  </p>
                </div>
                <div className="p-3 bg-gradient-to-r from-green-100 to-green-200 rounded-xl">
                  <CheckCheckIcon 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("teamMemberManagement.averagePerformance")}
                  </p>
                  <p className="text-3xl font-bold text-orange-900">
                    {stats.avgPerformance}%
                  </p>
                  <div className="w-full bg-orange-100 rounded-full h-2 mt-2">
                    <div
                      className={`h-2 rounded-full ${getPerformanceColor(
                        stats.avgPerformance,
                      )}`}
                      style={{
                        width: `${Math.min(stats.avgPerformance, 100)}%`,
                      }}
                    />
                  </div>
                </div>
                <div className="p-3 bg-gradient-to-r from-orange-100 to-orange-200 rounded-xl">
                  <TrendingUp className="h-8 w-8 text-orange-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

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

              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">
                  {t("teamMemberManagement.status")}
                </label>
                <Select value={statusFilter} onValueChange={setStatusFilter}>
                  <SelectTrigger>
                    <SelectValue
                      placeholder={t("teamMemberManagement.allStatuses")}
                    />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">
                      {t("teamMemberManagement.allStatuses")}
                    </SelectItem>
                    <SelectItem value="active">
                      {t("teamMemberManagement.active")}
                    </SelectItem>
                    <SelectItem value="inactive">
                      {t("teamMemberManagement.inactive")}
                    </SelectItem>
                    <SelectItem value="archived">
                      {t("teamMemberManagement.archived")}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="flex items-end">
                <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"
                    }`}
                  >
                    <ClipboardList className="h-4 w-4" />
                    {t("teamMemberManagement.tableView", "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("teamMemberManagement.gridView")}
                  </Button>
                </div>
              </div>
            </div>

            <div className="flex flex-wrap items-center justify-between gap-4 pt-4 border-t">
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="showArchived"
                    checked={showArchived}
                    onChange={(e) => setShowArchived(e.target.checked)}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <label
                    htmlFor="showArchived"
                    className="text-sm text-gray-700"
                  >
                    {t("teamMemberManagement.showArchived")}
                  </label>
                </div>
              </div>

              <div className="flex items-center gap-4">
                <Button
                  variant="outline"
                  className="gap-2"
                  onClick={handleExport}
                >
                  <Download className="h-4 w-4" />
                  {t("teamMemberManagement.export")}
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Loading State - No changes needed here */}
        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-20">
            <div className="relative">
              <Loader2 className="h-16 w-16 animate-spin text-blue-600" />
              <div className="absolute inset-0 flex items-center justify-center">
                <Users className="h-8 w-8 text-blue-400" />
              </div>
            </div>
            <p className="text-gray-600 mt-4 text-lg">
              {t("teamMemberManagement.loadingTeams")}
            </p>
            <p className="text-gray-500 text-sm mt-2">
              Please wait while we fetch your data
            </p>
          </div>
        ) : filteredTeams.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-blue-100 to-blue-50 flex items-center justify-center">
                <Users className="h-12 w-12 text-blue-400" />
              </div>
              <h3 className="text-2xl font-bold text-gray-900 mb-3">
                {t("teamMemberManagement.noTeams")}
              </h3>
              <div className="flex gap-3 justify-center">
                <Button
                  onClick={handleCreateTeam}
                  className="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-2" />
                  {t(
                    "teamMemberManagement.createFirstTeam",
                    "Create Your First Team",
                  )}
                </Button>
                {(searchTerm || statusFilter !== "all") && (
                  <Button
                    variant="outline"
                    onClick={() => {
                      setSearchTerm("");
                      setStatusFilter("all");
                    }}
                  >
                    {t("common.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(
                      "teamMemberManagement.performanceTeams",
                      "Performance Teams",
                    )}
                  </CardTitle>
                  <CardDescription>
                    {filteredTeams.length} teams • Sorted by {sortBy} (
                    {sortOrder})
                  </CardDescription>
                </div>
                <div className="text-sm text-gray-500">
                  Showing {filteredTeams.length} of {teams.length} total teams
                </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("teamMemberManagement.teamName", "Team Name")}
                          {sortBy === "name" &&
                            (sortOrder === "asc" ? (
                              <ChevronUp className="h-4 w-4" />
                            ) : (
                              <ChevronDown className="h-4 w-4" />
                            ))}
                        </div>
                      </TableHead>
                      <TableHead
                        className="cursor-pointer hover:bg-gray-100 transition-colors"
                        onClick={() => handleSort("members")}
                      >
                        <div className="flex items-center gap-1">
                          {t("teamMemberManagement.members", "Members")}
                          {sortBy === "members" &&
                            (sortOrder === "asc" ? (
                              <ChevronUp className="h-4 w-4" />
                            ) : (
                              <ChevronDown className="h-4 w-4" />
                            ))}
                        </div>
                      </TableHead>
                      <TableHead
                        className="cursor-pointer hover:bg-gray-100 transition-colors"
                        onClick={() => handleSort("performance")}
                      >
                        <div className="flex items-center gap-1">
                          {t("teamMemberManagement.performance", "Performance")}
                          {sortBy === "performance" &&
                            (sortOrder === "asc" ? (
                              <ChevronUp className="h-4 w-4" />
                            ) : (
                              <ChevronDown className="h-4 w-4" />
                            ))}
                        </div>
                      </TableHead>

                      <TableHead className="text-right">
                        {t("common.actions", "Actions")}
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredTeams.map((team) => (
                      <TableRow
                        key={team.id}
                        className="hover:bg-blue-50/30 transition-colors group"
                      >
                        <TableCell>
                          <div className="flex items-center gap-3">
                            <Avatar className="h-10 w-10 bg-gradient-to-r from-blue-100 to-blue-50 text-blue-600">
                              <Users className="h-5 w-5" />
                            </Avatar>
                            <div>
                              <div className="font-semibold text-gray-900 group-hover:text-blue-600 transition-colors">
                                {getDisplayName(team.name)}
                              </div>
                              {team.description && (
                                <div className="text-sm text-gray-500 truncate max-w-xs">
                                  {getDisplayName(team.description)}
                                </div>
                              )}
                            </div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center">
                            <div className="flex -space-x-2 mr-3">
                              {team.members?.slice(0, 3).map((member: any) => (
                                <Avatar
                                  key={member.id}
                                  className="h-8 w-8 border-2 border-white"
                                >
                                  <AvatarFallback className="bg-gradient-to-r from-blue-100 to-blue-50 text-blue-600 text-xs">
                                    {getDisplayName(
                                      member.employee?.name,
                                    )?.charAt(0) || "U"}
                                  </AvatarFallback>
                                </Avatar>
                              ))}
                              {(team.members?.length || 0) > 3 && (
                                <div className="h-8 w-8 rounded-full bg-gradient-to-r from-gray-100 to-gray-50 border-2 border-white flex items-center justify-center text-xs text-gray-600">
                                  +{(team.members?.length || 0) - 3}
                                </div>
                              )}
                            </div>
                            <Badge variant="outline" className="bg-gray-50">
                              {team.members?.length || 0} members
                            </Badge>
                          </div>
                        </TableCell>
                        {/* <TableCell>
                          <div className="flex items-center gap-2">
                            <Avatar className="h-6 w-6">
                              <AvatarFallback className="bg-blue-100 text-blue-600 text-xs">
                                {getDisplayName(team.teamLeader?.name)?.charAt(
                                  0
                                ) || "TL"}
                              </AvatarFallback>
                            </Avatar>
                            <span className="text-sm">
                              {getDisplayName(team.teamLeader?.name) ||
                                "Not assigned"}
                            </span>
                          </div>
                        </TableCell> */}
                        <TableCell>
                          <div className="flex items-center gap-3">
                            <div className="w-32">
                              <div className="flex justify-between text-xs mb-1">
                                <span className="font-medium">
                                  {team.averagePerformance || 0}%
                                </span>
                                <span className="text-gray-500">
                                  Target: 100%
                                </span>
                              </div>
                              <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                                <div
                                  className={`h-full rounded-full ${getPerformanceColor(
                                    team.averagePerformance,
                                  )}`}
                                  style={{
                                    width: `${team.averagePerformance || 0}%`,
                                  }}
                                />
                              </div>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end">
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-8 w-8 p-0 hover:bg-gray-100"
                                >
                                  <span className="sr-only">Open menu</span>
                                  <MoreVertical className="h-4 w-4" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end" className="w-48">
                                <DropdownMenuItem
                                  onClick={() => handleEditTeam(team)}
                                  className="flex items-center gap-2 cursor-pointer"
                                >
                                  <Edit className="h-4 w-4 text-blue-600" />
                                  <span>
                                    {t(
                                      "teamMemberManagement.editTeam",
                                      "Edit Team",
                                    )}
                                  </span>
                                </DropdownMenuItem>

                                <DropdownMenuItem
                                  onClick={() => handleAddTeamMember(team)}
                                  className="flex items-center gap-2 cursor-pointer"
                                >
                                  <UserPlus className="h-4 w-4 text-primary-600" />
                                  <span>
                                    {t(
                                      "teamMemberManagement.addMembers",
                                      "Add Members",
                                    )}
                                  </span>
                                </DropdownMenuItem>
                                {/* 
                                <DropdownMenuItem
                                  onClick={() => navigate(`/teams/${team.id}`)}
                                  className="flex items-center gap-2 cursor-pointer"
                                >
                                  <Eye className="h-4 w-4 text-purple-600" />
                                  <span>{t("teamMemberManagement.viewDetails", "View Details")}</span>
                                </DropdownMenuItem> */}

                                <DropdownMenuSeparator />

                                <DropdownMenuItem
                                  onClick={() => handleDeleteClick(team.id)}
                                  className="flex items-center gap-2 cursor-pointer text-red-600 focus:text-red-700 focus:bg-red-50"
                                >
                                  <Trash2 className="h-4 w-4" />
                                  <span>
                                    {t(
                                      "teamMemberManagement.deleteTeam",
                                      "Delete Team",
                                    )}
                                  </span>
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        ) : (
          // Grid View - Updated to use dropdown
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredTeams.map((team) => (
              <Card
                key={team.id}
                className="hover:shadow-xl transition-all duration-300 border hover:border-blue-300 group bg-gradient-to-br from-white to-gray-50/50"
              >
                <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">
                        <Avatar className="h-10 w-10 bg-gradient-to-r from-blue-100 to-blue-50 text-blue-600">
                          <Users className="h-5 w-5" />
                        </Avatar>
                        <CardTitle className="text-lg text-gray-900 line-clamp-1">
                          {getDisplayName(team.name)}
                        </CardTitle>
                      </div>
                      {team.description && (
                        <CardDescription className="line-clamp-2">
                          {getDisplayName(team.description)}
                        </CardDescription>
                      )}
                    </div>
                    <div className="flex items-start gap-2">
                      {getStatusBadge(team.status)}
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 w-8 p-0 hover:bg-gray-100"
                          >
                            <span className="sr-only">Open menu</span>
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-48">
                          <DropdownMenuItem
                            onClick={() => handleEditTeam(team)}
                            className="flex items-center gap-2 cursor-pointer"
                          >
                            <Edit className="h-4 w-4 text-blue-600" />
                            <span>
                              {t("teamMemberManagement.editTeam", "Edit Team")}
                            </span>
                          </DropdownMenuItem>

                          <DropdownMenuItem
                            onClick={() => handleAddTeamMember(team)}
                            className="flex items-center gap-2 cursor-pointer"
                          >
                            <UserPlus className="h-4 w-4 text-primary-600" />
                            <span>
                              {t(
                                "teamMemberManagement.addMembers",
                                "Add Members",
                              )}
                            </span>
                          </DropdownMenuItem>

                          <DropdownMenuItem
                            onClick={() => navigate(`/teams/${team.id}`)}
                            className="flex items-center gap-2 cursor-pointer"
                          >
                            <Eye className="h-4 w-4 text-purple-600" />
                            <span>
                              {t(
                                "teamMemberManagement.viewDetails",
                                "View Details",
                              )}
                            </span>
                          </DropdownMenuItem>

                          <DropdownMenuSeparator />

                          <DropdownMenuItem
                            onClick={() => handleDeleteClick(team.id)}
                            className="flex items-center gap-2 cursor-pointer text-red-600 focus:text-red-700 focus:bg-red-50"
                          >
                            <Trash2 className="h-4 w-4" />
                            <span>
                              {t(
                                "teamMemberManagement.deleteTeam",
                                "Delete Team",
                              )}
                            </span>
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-5">
                    {/* Team Leader */}
                    <div>
                      <div className="flex items-center gap-2 mb-2">
                        <Users className="h-4 w-4 text-blue-500" />
                        <span className="text-sm font-medium text-gray-700">
                          Team Leader
                        </span>
                      </div>
                      <div className="flex items-center gap-2 p-2 bg-blue-50 rounded-lg">
                        <Avatar className="h-6 w-6">
                          <AvatarFallback className="bg-blue-100 text-blue-600 text-xs">
                            {getDisplayName(team.teamLeader?.name)?.charAt(0) ||
                              "TL"}
                          </AvatarFallback>
                        </Avatar>
                        <span className="text-sm font-medium">
                          {getDisplayName(team.teamLeader?.name) ||
                            "Not assigned"}
                        </span>
                      </div>
                    </div>

                    {/* Team Members */}
                    <div>
                      <div className="flex justify-between items-center mb-2">
                        <span className="text-sm font-medium text-gray-700">
                          {t(
                            "teamMemberManagement.teamMembers",
                            "Team Members",
                          )}{" "}
                          ({team.members?.length || 0})
                        </span>
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => handleAddTeamMember(team)}
                          className="h-6 text-xs"
                        >
                          <PlusIcon className="h-3 w-3 mr-1" />
                          Add
                        </Button>
                      </div>
                      <div className="flex -space-x-2">
                        {team.members?.slice(0, 5).map((member: any) => (
                          <Avatar
                            key={member.id}
                            className="h-8 w-8 border-2 border-white"
                            title={getDisplayName(member.employee?.name)}
                          >
                            <AvatarFallback className="bg-gradient-to-r from-blue-100 to-blue-50 text-blue-600 text-xs">
                              {getDisplayName(member.employee?.name)?.charAt(
                                0,
                              ) || "U"}
                            </AvatarFallback>
                          </Avatar>
                        ))}
                        {(team.members?.length || 0) > 5 && (
                          <div
                            className="h-8 w-8 rounded-full bg-gradient-to-r from-gray-100 to-gray-50 border-2 border-white flex items-center justify-center text-xs text-gray-600"
                            title={`${
                              (team.members?.length || 0) - 5
                            } more members`}
                          >
                            +{(team.members?.length || 0) - 5}
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Performance */}
                    <div>
                      <div className="flex justify-between items-center mb-2">
                        <span className="text-sm font-medium text-gray-700">
                          Performance
                        </span>
                        <span className="text-lg font-bold text-gray-900">
                          {team.averagePerformance || 0}%
                        </span>
                      </div>
                      <div className="h-3 bg-gray-200 rounded-full overflow-hidden">
                        <div
                          className={`h-full rounded-full ${getPerformanceColor(
                            team.averagePerformance,
                          )}`}
                          style={{ width: `${team.averagePerformance || 0}%` }}
                        />
                      </div>
                    </div>

                    {/* Created Date */}
                    <div className="pt-4 border-t">
                      <div className="flex justify-between items-center">
                        <span className="text-xs text-gray-500">
                          Created: {formatDate(team.createdAt)}
                        </span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}

        {/* Dialogs - No changes needed here */}
        {/* Create/Edit Team Dialog */}
        <Dialog open={teamDialogOpen} onOpenChange={setTeamDialogOpen}>
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <Users className="h-5 w-5 text-blue-600" />
                {selectedTeam?.id
                  ? t("teamMemberManagement.editTeam")
                  : t("teamMemberManagement.createTeam")}
              </DialogTitle>
              <DialogDescription>
                {selectedTeam?.id
                  ? t(
                      "teamMemberManagement.editPlanTitle",
                      "Update team information",
                    )
                  : t(
                      "teamMemberManagement.createPlanTitle",
                      `Create a new performance team for ${
                        userPositions.find(
                          (p: any) => p.id === selectedPositionId,
                        )?.name || "selected position"
                      }`,
                    )}
              </DialogDescription>
            </DialogHeader>

            <GenericForm
              form={teamForm}
              fields={planFormFields}
              onSubmit={handleTeamSubmit}
              onCancel={handleCancel}
              isSubmitting={isPlanTeamLoading}
              submitButtonText={
                selectedTeam?.id
                  ? t("teamMemberManagement.updatePlan", "Update Plan")
                  : t("teamMemberManagement.createPlan", "Create Plan")
              }
              cancelButtonText={t("teamMemberManagement.cancel", "Cancel")}
            />
          </DialogContent>
        </Dialog>

        {/* Team Member Management Dialog */}
        <Dialog
          open={teamMemberDialogOpen}
          onOpenChange={setTeamMemberDialogOpen}
        >
          <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <UserPlus className="h-5 w-5 text-primary-600" />
                {t(
                  "teamMemberManagement.manageTeamMembers",
                  "Manage Team Members",
                )}
              </DialogTitle>
              <DialogDescription>
                {currentTeamForMembers && (
                  <div className="flex items-center gap-2">
                    Team:{" "}
                    <span className="font-semibold">
                      {getDisplayName(currentTeamForMembers.name)}
                    </span>
                    • Current members:{" "}
                    <span className="font-semibold">
                      {currentTeamForMembers.members?.length || 0}
                    </span>
                  </div>
                )}
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-6">
              {/* Current Team Members List */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <h4 className="font-semibold text-gray-900">
                    {t(
                      "teamMemberManagement.currentTeamMembers",
                      "Current Team Members",
                    )}
                  </h4>
                  {selectedMemberIds.length > 0 && (
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={handleRemoveMultipleMembers}
                      disabled={isPlanTeamLoading}
                    >
                      <Trash2 className="h-3.5 w-3.5 mr-2" />
                      Remove Selected ({selectedMemberIds.length})
                    </Button>
                  )}
                </div>

                {currentTeamForMembers?.members &&
                currentTeamForMembers.members.length > 0 ? (
                  <div className="space-y-2 max-h-60 overflow-y-auto">
                    {currentTeamForMembers.members.map((member: any) => (
                      <div
                        key={member.id}
                        className={`flex items-center justify-between p-3 rounded-lg border ${
                          selectedMemberIds.includes(member.id)
                            ? "bg-blue-50 border-blue-200"
                            : "bg-gray-50"
                        }`}
                      >
                        <div className="flex items-center gap-3">
                          <input
                            type="checkbox"
                            checked={selectedMemberIds.includes(member.id)}
                            onChange={(e) => {
                              if (e.target.checked) {
                                setSelectedMemberIds([
                                  ...selectedMemberIds,
                                  member.id,
                                ]);
                              } else {
                                setSelectedMemberIds(
                                  selectedMemberIds.filter(
                                    (id) => id !== member.id,
                                  ),
                                );
                              }
                            }}
                            className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                          />
                          <Avatar className="h-8 w-8">
                            <AvatarFallback className="bg-gradient-to-r from-blue-100 to-blue-50 text-blue-600">
                              {getDisplayName(member.employee?.name)?.charAt(
                                0,
                              ) || "U"}
                            </AvatarFallback>
                          </Avatar>
                          <div>
                            <p className="font-medium text-gray-900">
                              {getDisplayName(member.employee?.name) ||
                                "Unknown Member"}
                            </p>
                            <p className="text-sm text-gray-500">
                              {getDisplayName(
                                member.employeePosition?.position?.name,
                              )}
                            </p>
                          </div>
                        </div>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveTeamMember(member.id)}
                          disabled={isPlanTeamLoading}
                          className="h-8 w-8 p-0 text-red-600 hover:text-red-700 hover:bg-red-50"
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8 border-2 border-dashed rounded-lg bg-gray-50">
                    <Users className="h-12 w-12 text-gray-400 mx-auto mb-3" />
                    <p className="text-gray-600">
                      {t(
                        "teamMemberManagement.noMembersAdded",
                        "No team members added yet",
                      )}
                    </p>
                    <p className="text-sm text-gray-500 mt-1">
                      {t(
                        "teamMemberManagement.addMembersInstruction",
                        "Add members using the form below",
                      )}
                    </p>
                  </div>
                )}
              </div>

              {/* Add New Team Member Form */}
              <div>
                <h4 className="font-semibold text-gray-900 mb-3">
                  {t(
                    "teamMemberManagement.addNewTeamMember",
                    "Add New Team Member",
                  )}
                </h4>
                <GenericForm
                  form={teamMemberForm}
                  fields={teamMemberFormFields}
                  onSubmit={handleTeamMemberSubmit}
                  onCancel={handleTeamMemberCancel}
                  isSubmitting={isPlanTeamLoading}
                  submitButtonText={t(
                    "teamMemberManagement.addMember",
                    "Add Member",
                  )}
                  cancelButtonText={t("common.close", "Close")}
                />
              </div>
            </div>
          </DialogContent>
        </Dialog>

        {/* Delete Confirmation Dialog */}
        <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
          <DialogContent className="max-w-md">
            <DialogHeader>
              <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>
                <DialogTitle className="text-red-700">
                  {t("teamMemberManagement.deleteTeam", "Delete Team")}
                </DialogTitle>
              </div>
              <DialogDescription className="text-gray-600">
                {t(
                  "teamMemberManagement.deleteConfirmMessage",
                  "Are you sure you want to delete this team? This action cannot be undone and will remove all team data including member assignments.",
                )}
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setDeleteDialogOpen(false)}
                className="border-gray-300 hover:bg-gray-50"
              >
                {t("common.cancel", "Cancel")}
              </Button>
              <Button
                onClick={confirmDelete}
                className="bg-gradient-to-r from-red-500 to-rose-600 hover:from-red-600 hover:to-rose-700 text-white"
                disabled={isPlanTeamLoading}
              >
                {isPlanTeamLoading ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    {t("common.deleting", "Deleting...")}
                  </>
                ) : (
                  <>
                    <Trash2 className="h-4 w-4 mr-2" />
                    {t("teamMemberManagement.deleteTeam", "Delete Team")}
                  </>
                )}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
};

// ArchiveIcon component
const ArchiveIcon = (props: any) => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="24"
    height="24"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
    {...props}
  >
    <rect width="20" height="5" x="2" y="3" rx="1" />
    <path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" />
    <path d="M10 12h4" />
  </svg>
);

export default TeamsManagement;
