import React, { useEffect, useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "@/shared/common/ui/button";
import { ArrowLeft } from "lucide-react";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { getPlanList } from "@/performance-management/services/api/planService";
import { UnifiedHierarchyView } from "./UnifiedHierarchyView";
import { EPositionTypeKey } from "@/shared/dto/user/meDto";

interface SectorDetailViewProps {
  positionId: string;
  positionType: EPositionTypeKey;
}

export const SectorDetailView: React.FC<SectorDetailViewProps> = ({
  positionId,
  positionType,
}) => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [hierarchyData, setHierarchyData] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);

  const fetchSectorPlans = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      // Fetch plans for this specific position
      const response = await getPlanList(positionId, {
        positionId,
        take: 100,
        skip: 0,
      });

      setHierarchyData(response?.data);
    } catch (err: any) {
      console.error("Failed to fetch sector plans:", err);
      setError(err.message || "Failed to load sector plans");
    } finally {
      setLoading(false);
    }
  }, [positionId]);

  useEffect(() => {
    fetchSectorPlans();
  }, [fetchSectorPlans]);

  const handleAddPlan = (targetId?: string) => {
    console.log("Add plan clicked for:", targetId || "current level");
    // TODO: Implement plan creation modal
  };

  const handleManageWeekly = () => {
    console.log("Manage weekly tasks clicked");
    // TODO: Implement weekly tasks management modal
  };

  const handleViewTeamLead = (teamLeadId: string) => {
    console.log("View team lead:", teamLeadId);
    // TODO: Implement drill-down navigation
  };

  const handleViewEmployee = (employeeId: string) => {
    console.log("View employee:", employeeId);
    // TODO: Implement drill-down navigation
  };

  const handleBackToSectors = () => {
    navigate("/performance-management/plans");
  };

  if (loading) {
    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">
        <Button
          variant="outline"
          onClick={handleBackToSectors}
          className="mb-4">
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Sectors
        </Button>
        <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 Sector Plans
          </h3>
          <p className="text-red-600 dark:text-red-400">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6">
      <Button variant="outline" onClick={handleBackToSectors} className="mb-6">
        <ArrowLeft className="mr-2 h-4 w-4" />
        Back to Sectors
      </Button>

      <UnifiedHierarchyView
        positionType={positionType}
        data={hierarchyData}
        onAddPlan={handleAddPlan}
        onManageWeekly={handleManageWeekly}
        onViewTeamLead={handleViewTeamLead}
        onViewEmployee={handleViewEmployee}
      />
    </div>
  );
};
