'use client';

import { motion } from 'framer-motion';
import {
  LayoutDashboard, GitBranch, Activity, Workflow,
  SplitSquareHorizontal, ShieldCheck, FileCode2, Download,
  CheckCircle2, Lock, Shield
} from 'lucide-react';
import type { Project } from '../data/projectsData';

interface Props {
  projectId: string;
  activeSection: string;
  onNavigate: (section: string, projectId?: string) => void;
  maxReachedStep?: number;
  project?: Project | null;
}

const steps = [
  { id: 'conversion-dashboard', label: 'Overview', icon: LayoutDashboard, step: 0 },
  { id: 'repository', label: 'Repository', icon: GitBranch, step: 1 },
  { id: 'pre-analysis', label: 'Analysis', icon: Activity, step: 2 },
  { id: 'migration-flow', label: 'Migration', icon: Workflow, step: 3 },
  { id: 'comparison', label: 'Code Review', icon: SplitSquareHorizontal, step: 4 },
  { id: 'verification', label: 'Verification', icon: ShieldCheck, step: 5 },
  { id: 'security', label: 'Security', icon: Shield, step: 6 },
  { id: 'artifacts', label: 'Artifacts', icon: FileCode2, step: 7 },
  { id: 'export', label: 'Export', icon: Download, step: 8 },
];

const getStepStatus = (step: number, projectStatus: string, maxReached: number = 0): 'completed' | 'active' | 'locked' => {
  const statusStepMap: Record<string, number> = {
    'draft': 0,
    'analyzing': 2,
    'converting': 3,
    'validating': 5,
    'completed': 9,
    'failed': 3,
  };
  const currentStep = Math.max(statusStepMap[projectStatus] ?? 0, maxReached);
  if (step < currentStep) return 'completed';
  if (step === currentStep) return 'active';
  if (step <= currentStep + 1) return 'active';
  return 'locked';
};

export default function ProjectStepTracker({ projectId, activeSection, onNavigate, maxReachedStep = 0, project: propProject }: Props) {
  const project = propProject;
  if (!project) return null;

  const statusStepMap: Record<string, number> = {
    'draft': 0,
    'analyzing': 2,
    'converting': 3,
    'validating': 5,
    'completed': 9,
    'failed': 3,
  };
  const currentProjectStep = Math.max(statusStepMap[project.status] ?? 0, maxReachedStep);
  const progressPercent = Math.min(100, (currentProjectStep / 8) * 100);

  return (
    <motion.div
      initial={{ opacity: 0, y: -10 }}
      animate={{ opacity: 1, y: 0 }}
      className="glass rounded-xl p-4 mb-6"
    >
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-2">
          <h3 className="text-[10px] font-semibold text-muted uppercase tracking-wider">Conversion Pipeline</h3>
          <span className="text-[10px] px-2 py-0.5 rounded-full bg-accent/10 text-accent-light font-medium">
            {project.status === 'completed' ? 'Complete' : (project.status === 'draft' && maxReachedStep === 0) ? 'Not Started' : 'In Progress'}
          </span>
        </div>
        <span className="text-[10px] text-muted">
          {currentProjectStep > 0 ? `Step ${Math.min(currentProjectStep, 8)}/8` : 'Ready to begin'}
        </span>
      </div>

      <div className="relative">
        <div className="h-1 bg-surface-light rounded-full overflow-hidden mb-4">
          <motion.div
            initial={{ width: 0 }}
            animate={{ width: `${progressPercent}%` }}
            transition={{ duration: 1, ease: 'easeOut' }}
            className="h-full rounded-full gradient-accent"
          />
        </div>

        <div className="flex justify-between">
          {steps.map((step, index) => {
            const status = getStepStatus(step.step, project.status, maxReachedStep);
            const isActive = activeSection === step.id;
            const isCompleted = status === 'completed';
            const isLocked = status === 'locked';
            const isCurrent = status === 'active';
            const Icon = step.icon;

            return (
              <button
                key={step.id}
                onClick={() => !isLocked && onNavigate(step.id, projectId)}
                className={`flex flex-col items-center gap-1.5 transition-all group ${
                  isLocked ? 'cursor-not-allowed' : 'cursor-pointer'
                }`}
              >
                <div className={`w-8 h-8 rounded-full flex items-center justify-center transition-all ${
                  isActive
                    ? 'bg-accent text-white ring-2 ring-accent/30 ring-offset-2 ring-offset-[var(--bg)]'
                    : isCompleted
                      ? 'bg-success/20 text-success'
                      : isCurrent
                        ? 'bg-accent/20 text-accent-light'
                        : isLocked
                          ? 'bg-surface-light text-muted/30'
                          : 'bg-surface-light text-muted'
                }`}>
                  {isCompleted ? (
                    <CheckCircle2 className="w-4 h-4" />
                  ) : isLocked ? (
                    <Lock className="w-3 h-3" />
                  ) : (
                    <Icon className="w-3.5 h-3.5" />
                  )}
                </div>
                <span className={`text-[9px] font-medium transition-colors ${
                  isActive ? 'text-accent-light' : isCompleted ? 'text-success' : isLocked ? 'text-muted/30' : 'text-muted'
                } ${!isLocked ? 'group-hover:text-foreground' : ''}`}>
                  {step.label}
                </span>
              </button>
            );
          })}
        </div>
      </div>
    </motion.div>
  );
}
