import React, { useState } from 'react';
import {
  ChevronRight,
  ChevronDown,
  Briefcase,
  Target,
  Compass,
  Rocket,
  Plus,
  FileText,
} from 'lucide-react';
import { clsx } from 'clsx';
import type { BMADProject, Business, Mission, Approach, Deployment } from '../../../shared/types.js';
import { useBMADStore } from '../store/useBMADStore';

interface BMADHierarchyProps {
  project: BMADProject;
}

export const BMADHierarchy: React.FC<BMADHierarchyProps> = ({ project }) => {
  const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set());
  const { selectDeployment } = useBMADStore();

  const toggleNode = (nodeId: string) => {
    const newExpanded = new Set(expandedNodes);
    if (newExpanded.has(nodeId)) {
      newExpanded.delete(nodeId);
    } else {
      newExpanded.add(nodeId);
    }
    setExpandedNodes(newExpanded);
  };

  const phaseIcons = {
    business: <Briefcase className="w-4 h-4 text-purple-500" />,
    mission: <Target className="w-4 h-4 text-blue-500" />,
    approach: <Compass className="w-4 h-4 text-green-500" />,
    deployment: <Rocket className="w-4 h-4 text-amber-500" />,
  };

  const phaseColors = {
    business: 'hover:bg-purple-50 border-l-purple-500',
    mission: 'hover:bg-blue-50 border-l-blue-500',
    approach: 'hover:bg-green-50 border-l-green-500',
    deployment: 'hover:bg-amber-50 border-l-amber-500',
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
      <div className="mb-4 flex items-center justify-between">
        <h2 className="text-2xl font-bold text-gray-900">BMAD Hierarchy</h2>
        <button className="flex items-center gap-2 px-3 py-1.5 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors">
          <Plus className="w-4 h-4" />
          Add Business
        </button>
      </div>

      <div className="space-y-1">
        {project.business.map((business) => (
          <div key={business.id}>
            {/* Business Level */}
            <div
              className={clsx(
                'flex items-center gap-2 p-2 rounded cursor-pointer border-l-4 transition-colors',
                phaseColors.business
              )}
              onClick={() => toggleNode(business.id)}
            >
              <button className="p-0.5">
                {expandedNodes.has(business.id) ? (
                  <ChevronDown className="w-4 h-4" />
                ) : (
                  <ChevronRight className="w-4 h-4" />
                )}
              </button>
              {phaseIcons.business}
              <span className="font-medium">{business.title}</span>
              <span className="text-xs text-gray-500 ml-auto">
                {business.missions.length} missions
              </span>
            </div>

            {/* Missions */}
            {expandedNodes.has(business.id) && (
              <div className="ml-6 mt-1 space-y-1">
                {business.missions.map((mission) => (
                  <div key={mission.id}>
                    <div
                      className={clsx(
                        'flex items-center gap-2 p-2 rounded cursor-pointer border-l-4 transition-colors',
                        phaseColors.mission
                      )}
                      onClick={() => toggleNode(mission.id)}
                    >
                      <button className="p-0.5">
                        {expandedNodes.has(mission.id) ? (
                          <ChevronDown className="w-4 h-4" />
                        ) : (
                          <ChevronRight className="w-4 h-4" />
                        )}
                      </button>
                      {phaseIcons.mission}
                      <span className="font-medium">{mission.title}</span>
                      <span
                        className={clsx(
                          'text-xs px-2 py-0.5 rounded-full ml-2',
                          mission.priority === 'critical' && 'bg-red-100 text-red-700',
                          mission.priority === 'high' && 'bg-orange-100 text-orange-700',
                          mission.priority === 'medium' && 'bg-yellow-100 text-yellow-700',
                          mission.priority === 'low' && 'bg-green-100 text-green-700'
                        )}
                      >
                        {mission.priority}
                      </span>
                      <span className="text-xs text-gray-500 ml-auto">
                        {mission.approaches.length} approaches
                      </span>
                    </div>

                    {/* Approaches */}
                    {expandedNodes.has(mission.id) && (
                      <div className="ml-6 mt-1 space-y-1">
                        {mission.approaches.map((approach) => (
                          <div key={approach.id}>
                            <div
                              className={clsx(
                                'flex items-center gap-2 p-2 rounded cursor-pointer border-l-4 transition-colors',
                                phaseColors.approach
                              )}
                              onClick={() => toggleNode(approach.id)}
                            >
                              <button className="p-0.5">
                                {expandedNodes.has(approach.id) ? (
                                  <ChevronDown className="w-4 h-4" />
                                ) : (
                                  <ChevronRight className="w-4 h-4" />
                                )}
                              </button>
                              {phaseIcons.approach}
                              <span className="font-medium">{approach.title}</span>
                              <span className="text-xs text-gray-500 ml-auto">
                                {approach.deployments.length} tasks
                              </span>
                            </div>

                            {/* Deployments */}
                            {expandedNodes.has(approach.id) && (
                              <div className="ml-6 mt-1 space-y-1">
                                {approach.deployments.map((deployment) => (
                                  <div
                                    key={deployment.id}
                                    className={clsx(
                                      'flex items-center gap-2 p-2 rounded cursor-pointer border-l-4 transition-colors',
                                      phaseColors.deployment
                                    )}
                                    onClick={() => selectDeployment(deployment)}
                                  >
                                    <div className="w-5" />
                                    {phaseIcons.deployment}
                                    <span>{deployment.title}</span>
                                    <span
                                      className={clsx(
                                        'text-xs px-2 py-0.5 rounded-full ml-auto',
                                        deployment.status === 'backlog' && 'bg-gray-100 text-gray-700',
                                        deployment.status === 'todo' && 'bg-blue-100 text-blue-700',
                                        deployment.status === 'in_progress' && 'bg-yellow-100 text-yellow-700',
                                        deployment.status === 'review' && 'bg-purple-100 text-purple-700',
                                        deployment.status === 'done' && 'bg-green-100 text-green-700',
                                        deployment.status === 'blocked' && 'bg-red-100 text-red-700'
                                      )}
                                    >
                                      {deployment.status.replace('_', ' ')}
                                    </span>
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Statistics */}
      <div className="mt-6 pt-4 border-t border-gray-200">
        <div className="grid grid-cols-4 gap-4 text-center">
          <div>
            <div className="text-2xl font-bold text-purple-600">
              {project.business.length}
            </div>
            <div className="text-xs text-gray-500">Business Goals</div>
          </div>
          <div>
            <div className="text-2xl font-bold text-blue-600">
              {project.business.reduce((acc, b) => acc + b.missions.length, 0)}
            </div>
            <div className="text-xs text-gray-500">Missions</div>
          </div>
          <div>
            <div className="text-2xl font-bold text-green-600">
              {project.business.reduce(
                (acc, b) => acc + b.missions.reduce((acc2, m) => acc2 + m.approaches.length, 0),
                0
              )}
            </div>
            <div className="text-xs text-gray-500">Approaches</div>
          </div>
          <div>
            <div className="text-2xl font-bold text-amber-600">
              {project.business.reduce(
                (acc, b) =>
                  acc +
                  b.missions.reduce(
                    (acc2, m) =>
                      acc2 + m.approaches.reduce((acc3, a) => acc3 + a.deployments.length, 0),
                    0
                  ),
                0
              )}
            </div>
            <div className="text-xs text-gray-500">Tasks</div>
          </div>
        </div>
      </div>
    </div>
  );
};