import React, { useEffect, useMemo } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useAuth } from "@/shared/context/AuthContext";
import { getUserPositionType } from "@/performance-management/utils/positionTypeUtils";
import { EPositionTypeKey } from "@/shared/dto/user/meDto";
import { Skeleton } from "@/shared/common/ui/skeleton";
import {
  checkIsPlanInitiator,
  useSectorList,
} from "@/performance-management/hooks/usePlans";
import { SectorListView } from "./SectorListView";
import { useAuthUser } from "@/record-management/hooks/useAuthUser";

const PlanHierarchy: React.FC = () => {
  const { positionId, yearId } = useParams<{
    positionId?: string;
    yearId?: string;
  }>();
  const navigate = useNavigate();
  const { user, selectedPositionId } = useAuth();
  const { isLoading: isAuthLoading } = useAuthUser();
  const isInitiator = useMemo(
    () => checkIsPlanInitiator(user, selectedPositionId || undefined),
    [user, selectedPositionId]
  );

  const positionType = getUserPositionType(user);

  // Fetch sector list
  const { data: sectorData, isLoading, error } = useSectorList(yearId);
  console.log("sectorData", sectorData);
  // Redirect non-initiators to their position-filtered plans
  useEffect(() => {
    if (isAuthLoading || !yearId) return;

    // If user is not an initiator, redirect them to their own plans
    if (!isInitiator) {
      // Deputy users go to "my-plans"
      if (positionType === EPositionTypeKey.DEPUTY) {
        navigate(`/performance-management/${yearId}/my-plans`, {
          replace: true,
        });
        return;
      }

      // Other users (directors, team leaders, employees) also go to my-plans
      navigate(`/performance-management/${yearId}/my-plans`, {
        replace: true,
      });
      return;
    }

    // If positionId is provided, redirect to the plans table with that position filter
    if (positionId) {
      navigate(`/performance-management/${yearId}/plans-table/${positionId}`, {
        replace: true,
      });
    }
  }, [positionId, yearId, navigate, positionType, isInitiator, isAuthLoading]);

  if (isLoading || isAuthLoading) {
    return (
      <div className="space-y-6 p-6">
        <Skeleton className="h-64 w-full rounded-lg" />
        <Skeleton className="h-96 w-full rounded-lg" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-6">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <h3 className="text-red-800 dark:text-red-200 font-semibold mb-2">
            Error Loading Hierarchy
          </h3>
          <p className="text-red-600 dark:text-red-400">
            {error instanceof Error
              ? error.message
              : "Failed to load plan hierarchy"}
          </p>
        </div>
      </div>
    );
  }

  if (!positionType) {
    return (
      <div className="p-6">
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
          <h3 className="text-yellow-800 dark:text-yellow-200 font-semibold mb-2">
            Position Type Not Found
          </h3>
          <p className="text-yellow-600 dark:text-yellow-400">
            Your user account does not have a valid position type assigned.
            Please contact your administrator.
          </p>
        </div>
      </div>
    );
  }

  // Show sector list
  return (
    <div className="p-6">
      <SectorListView sectors={sectorData?.data?.items || []} />
    </div>
  );
};

export default PlanHierarchy;
