import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { Check, Loader2, AlertTriangle, XCircle, Lock } from 'lucide-react';

const STAGES = [
  { key: 'cover', label: 'Cover', route: '/covers' },
  { key: 'input', label: 'Input', route: '/new-project' },
  { key: 'concept', label: 'Concept', route: '/promptforge' },
  { key: 'artwork', label: 'Artwork', route: '/image-apply' },
  { key: 'geometry', label: 'Geometry', route: '/sketch-3d' },
  { key: 'placement', label: 'Placement', route: '/studio' },
  { key: 'validation', label: 'Validation', route: '/validation' },
  { key: 'manufacture', label: 'Manufacture', route: '/jobs' }
];

const ROUTE_STAGE = {
  '/covers': 0, '/new-project': 1, '/promptforge': 2, '/image-apply': 3,
  '/sketch-3d': 4, '/studio': 5, '/validation': 6, '/jobs': 7
};

const STATUS_STAGE = { draft: 1, artwork: 4, studio: 5, validation: 6, processing: 6, ready_for_export: 7, exported: 7 };

function stateFor(i, current, projectStage, validation) {
  if (i === 6 && validation) {
    if (validation === 'fail') return 'fail';
    if (validation === 'warning') return 'warn';
    if (validation === 'simulation_only') return 'sim';
  }
  if (i < projectStage) return 'complete';
  if (i === current) return 'current';
  if (i < current) return 'complete';
  return 'upcoming';
}

const nodeCls = { complete: 'wf-complete', current: 'wf-current', upcoming: 'wf-upcoming', warn: 'wf-warn', fail: 'wf-fail', sim: 'wf-sim' };

export default function WorkflowStrip({ project }) {
  const location = useLocation();
  const navigate = useNavigate();
  const [params] = useSearchParams();
  const projectId = params.get('project');

  const current = ROUTE_STAGE[location.pathname];
  const projectStage = project ? (STATUS_STAGE[project.status] ?? 1) : 0;

  if (current === undefined) return null; // pages without a workflow stage (dashboard, history, settings)

  const reached = Math.max(projectStage, current);

  return (
    <div className="flex h-full items-center gap-1 overflow-x-auto px-3">
      {STAGES.map((s, i) => {
        const st = stateFor(i, current, projectStage, project?.validationStatus);
        const Icon = st === 'complete' ? Check : st === 'current' ? Loader2 : st === 'warn' ? AlertTriangle : st === 'fail' ? XCircle : st === 'sim' ? null : null;
        const clickable = i <= reached;
        return (
          <div key={s.key} className="flex items-center">
            <button
              disabled={!clickable}
              onClick={() => navigate(`${s.route}${projectId ? `?project=${projectId}` : ''}`)}
              className={`group flex items-center gap-2 rounded-md px-2 py-1 transition ${clickable ? 'hover:bg-white/[0.04]' : 'cursor-not-allowed'}`}
            >
              <span className={`wf-node ${nodeCls[st]} ${clickable ? 'wf-link' : ''}`}>
                {Icon ? <Icon size={13} className={st === 'current' ? 'animate-spin' : ''} /> : !clickable ? <Lock size={11} className="opacity-50" /> : i + 1}
              </span>
              <span className={`whitespace-nowrap text-[11px] font-medium ${st === 'upcoming' ? 'text-slate-600' : st === 'current' ? 'text-cyan-100' : 'text-slate-300'}`}>{s.label}</span>
            </button>
            {i < STAGES.length - 1 && <span className={`wf-bar mx-1 ${i < reached ? '' : 'opacity-30'}`} style={{ width: 18 }} />}
          </div>
        );
      })}
    </div>
  );
}