import React, { useState } from "react";
import { Button } from "@/shared/common/ui/button";
import {
  Plus,
  ChevronDown,
  ChevronRight,
  User,
  Calendar,
  CheckCircle2,
} from "lucide-react";
import { PlansTable } from "./shared/PlansTable";
import { EPositionTypeKey } from "@/shared/dto/user/meDto";
import {
  WeeklyTask,
  Employee,
  TeamLead,
  Directorate,
} from "@/performance-management/types/planHierarchyTypes";

// Props for the unified view
interface UnifiedHierarchyViewProps {
  positionType: EPositionTypeKey;
  data: any; // Will be typed based on API response
  onAddPlan: (targetId?: string) => void;
  onManageWeekly?: () => void;
  onViewTeamLead?: (teamLeadId: string) => void;
  onViewEmployee?: (employeeId: string) => void;
}

export const UnifiedHierarchyView: React.FC<UnifiedHierarchyViewProps> = ({
  positionType,
  data,
  onAddPlan,
  onManageWeekly,
  onViewTeamLead,
  onViewEmployee,
}) => {
  const [expandedDirectorate, setExpandedDirectorate] = useState<string | null>(
    null
  );

  const toggleDirectorate = (id: string) => {
    setExpandedDirectorate((prev) => (prev === id ? null : id));
  };

  // Deputy (Sector) View
  if (positionType === EPositionTypeKey.DEPUTY) {
    return (
      <div className="space-y-6">
        {/* Sector Plans Overview */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              Sector Plans
            </h2>
            <Button onClick={() => onAddPlan()}>
              <Plus className="mr-2 h-4 w-4" />
              Add Sector Plan
            </Button>
          </div>
          <PlansTable plans={data?.plans || []} editable />
        </div>

        {/* Directorates Section */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
            Directorates
          </h2>

          <div className="space-y-2">
            {(data?.directorates || []).map((dir: Directorate) => (
              <div
                key={dir.id}
                className="border border-gray-200 dark:border-gray-700 rounded-lg">
                {/* Directorate Header */}
                <div
                  className="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800"
                  onClick={() => toggleDirectorate(dir.id)}>
                  <div className="flex items-center gap-3">
                    {expandedDirectorate === dir.id ? (
                      <ChevronDown className="h-5 w-5 text-gray-500" />
                    ) : (
                      <ChevronRight className="h-5 w-5 text-gray-500" />
                    )}
                    <div>
                      <h3 className="font-medium text-gray-900 dark:text-gray-100">
                        {dir.name}
                      </h3>
                      <p className="text-sm text-gray-500 dark:text-gray-400">
                        {dir.planCount} plans • {dir.progress}% complete
                      </p>
                    </div>
                  </div>
                  <Button
                    size="sm"
                    onClick={(e) => {
                      e.stopPropagation();
                      onAddPlan(dir.id);
                    }}>
                    <Plus className="h-4 w-4 mr-1" />
                    Add Plan
                  </Button>
                </div>

                {/* Expanded Directorate Plans */}
                {expandedDirectorate === dir.id && (
                  <div className="p-4 border-t border-gray-200 dark:border-gray-700">
                    {dir.plans?.length > 0 ? (
                      <PlansTable plans={dir.plans} />
                    ) : (
                      <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                        No plans added yet
                      </div>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // Director (Directorate) View
  if (positionType === EPositionTypeKey.DIRECTOR) {
    return (
      <div className="space-y-6">
        {/* Directorate Plans */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              My Plans
            </h2>
            <Button onClick={() => onAddPlan()}>
              <Plus className="mr-2 h-4 w-4" />
              Add Plan
            </Button>
          </div>
          <PlansTable plans={data?.plans || []} editable />
        </div>

        {/* Team Leads List */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
            Team Leads
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {(data?.teamLeads || []).map((tl: TeamLead) => (
              <div
                key={tl.id}
                className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition cursor-pointer"
                onClick={() => onViewTeamLead?.(tl.id)}>
                <h3 className="font-medium text-gray-900 dark:text-gray-100 mb-2">
                  {tl.name}
                </h3>
                <div className="space-y-1 text-sm text-gray-600 dark:text-gray-400">
                  <p>{tl.planCount} plans assigned</p>
                  <div className="flex items-center gap-2">
                    <div className="flex-1 bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                      <div
                        className="bg-purple-600 h-2 rounded-full transition-all"
                        style={{ width: `${tl.progress}%` }}
                      />
                    </div>
                    <span>{tl.progress}%</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // Team Leader View
  if (positionType === EPositionTypeKey.TEAM_LEADER) {
    return (
      <div className="space-y-6">
        {/* Team Lead Plans */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              My Plans
            </h2>
            <Button onClick={() => onAddPlan()}>
              <Plus className="mr-2 h-4 w-4" />
              Add Plan
            </Button>
          </div>
          <PlansTable plans={data?.plans || []} />
        </div>

        {/* Weekly Milestones */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              Weekly Milestones
            </h2>
            <Button onClick={onManageWeekly} variant="outline">
              Manage Weekly Tasks
            </Button>
          </div>
          <div className="space-y-2">
            {(data?.weeklyMilestones || []).length > 0 ? (
              data.weeklyMilestones.map((milestone: string, index: number) => (
                <div
                  key={index}
                  className="flex items-center gap-2 p-3 bg-gray-50 dark:bg-gray-800 rounded">
                  <div className="h-2 w-2 rounded-full bg-purple-600"></div>
                  <span className="text-sm text-gray-700 dark:text-gray-300">
                    {milestone}
                  </span>
                </div>
              ))
            ) : (
              <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                No weekly milestones set
              </div>
            )}
          </div>
        </div>

        {/* Team Members */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
            Team Members
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {(data?.employees || []).map((employee: Employee) => (
              <div
                key={employee.id}
                className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition cursor-pointer"
                onClick={() => onViewEmployee?.(employee.id)}>
                <div className="flex items-start gap-3">
                  <div className="p-2 bg-purple-100 dark:bg-purple-900 rounded">
                    <User className="h-5 w-5 text-purple-600 dark:text-purple-300" />
                  </div>
                  <div className="flex-1">
                    <h3 className="font-medium text-gray-900 dark:text-gray-100">
                      {employee.name}
                    </h3>
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                      {employee.position}
                    </p>
                    <div className="mt-2 space-y-1 text-xs text-gray-500 dark:text-gray-400">
                      <p>
                        {employee.planCount} plans • {employee.weeklyTasksCount}{" "}
                        weekly tasks
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // Employee View
  if (positionType === EPositionTypeKey.EMPLOYEE) {
    return (
      <div className="space-y-6">
        {/* Weekly Expectations */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4 flex items-center gap-2">
            <Calendar className="h-5 w-5" />
            My Weekly Expectations
          </h2>

          {(data?.weeklyTasks || []).length > 0 ? (
            <div className="space-y-3">
              {data.weeklyTasks.map((task: WeeklyTask) => (
                <div
                  key={task.id}
                  className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                  <div className="flex items-start justify-between mb-2">
                    <h3 className="font-medium text-gray-900 dark:text-gray-100">
                      {task.description}
                    </h3>
                    <span
                      className={`px-2 py-1 rounded-full text-xs font-medium ${
                        task.status === "completed"
                          ? "bg-green-100 text-green-800 dark:bg-green-900 dark:text-primary-300"
                          : task.status === "in-progress"
                          ? "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300"
                          : "bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300"
                      }`}>
                      {task.status}
                    </span>
                  </div>
                  <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                    <strong>Expected Outcome:</strong> {task.expectedOutcome}
                  </p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    <strong>Deadline:</strong> {task.deadline}
                  </p>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500 dark:text-gray-400">
              No weekly tasks assigned yet
            </div>
          )}
        </div>

        {/* Assigned Plans */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4 flex items-center gap-2">
            <CheckCircle2 className="h-5 w-5" />
            Assigned Plans
          </h2>
          <PlansTable plans={data?.plans || []} />
        </div>

        {/* Performance Summary */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
            Performance Summary
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="p-4 bg-purple-50 dark:bg-purple-900/20 rounded-lg">
              <div className="text-sm text-purple-600 dark:text-purple-400 mb-1">
                Total Plans
              </div>
              <div className="text-2xl font-bold text-purple-900 dark:text-purple-100">
                {data?.plans?.length || 0}
              </div>
            </div>
            <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
              <div className="text-sm text-blue-600 dark:text-blue-400 mb-1">
                Weekly Tasks
              </div>
              <div className="text-2xl font-bold text-blue-900 dark:text-blue-100">
                {data?.weeklyTasks?.length || 0}
              </div>
            </div>
            <div className="p-4 bg-green-50 dark:bg-primary-900/20 rounded-lg">
              <div className="text-sm text-primary-600 dark:text-primary-400 mb-1">
                Completed
              </div>
              <div className="text-2xl font-bold text-green-900 dark:text-green-100">
                {data?.weeklyTasks?.filter(
                  (t: WeeklyTask) => t.status === "completed"
                ).length || 0}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Fallback for unsupported position types
  return (
    <div className="p-6">
      <div className="bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4">
        <h3 className="text-gray-800 dark:text-gray-200 font-semibold mb-2">
          Unsupported Position Type
        </h3>
        <p className="text-gray-600 dark:text-gray-400">
          Your position type is not supported in the plan hierarchy view.
        </p>
      </div>
    </div>
  );
};
