import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { Image as ImageIcon, PenTool, Wand2, ArrowRight, Check, X } from 'lucide-react';

const TILES = [
  { key: 'image_apply', Icon: ImageIcon, title: 'Upload an image', desc: 'Use a photo, logo, pattern or existing artwork.' },
  { key: 'sketch_3d', Icon: PenTool, title: 'Upload a drawing', desc: 'Turn a sketch or line drawing into raised, engraved or cut-out decoration.' },
  { key: 'promptforge', Icon: Wand2, title: 'Describe your idea', desc: 'Tell PromptForge what you want and receive original design concepts.' },
];

export default function Onboarding({ user, onComplete }) {
  const navigate = useNavigate();
  const [step, setStep] = useState(0);
  const [method, setMethod] = useState('image_apply');
  const [mode, setMode] = useState('guided');
  const [busy, setBusy] = useState(false);

  // Only show once the user record has loaded and onboarding is incomplete.
  if (!user || user.onboardingComplete) return null;

  const finish = async () => {
    if (busy) return;
    setBusy(true);
    try {
      await base44.auth.updateMe({ onboardingComplete: true, experienceMode: mode });
    } catch {
      /* non-fatal — let the user continue locally; preference saves later */
    }
    await onComplete?.();
    navigate(`/new-project?method=${method}`);
  };

  const skip = async () => {
    if (busy) return;
    setBusy(true);
    try {
      await base44.auth.updateMe({ onboardingComplete: true, experienceMode: 'guided' });
    } catch {
      /* non-fatal */
    }
    await onComplete?.();
    navigate('/');
  };

  return (
    <div className="fixed inset-0 z-[60] grid place-items-center bg-black/70 backdrop-blur-md p-4">
      <div className="panel-glass relative w-full max-w-xl overflow-hidden p-0">
        <button onClick={skip} className="icon-button absolute right-3 top-3 z-10" aria-label="Skip onboarding" title="Skip">
          <X size={16} />
        </button>

        {/* Progress dots */}
        <div className="flex items-center justify-center gap-2 pt-6">
          {[0, 1, 2].map((i) => (
            <span key={i} className={`h-1.5 rounded-full transition-all ${i === step ? 'w-8 bg-cyan-400' : 'w-3 bg-white/15'}`} />
          ))}
        </div>

        <div className="p-7 pt-5">
          {step === 0 && (
            <div className="fade-in text-center">
              <span className="eyebrow">Welcome</span>
              <h2 className="font-heading text-2xl font-semibold text-white">Create your custom prosthetic cover</h2>
              <p className="mx-auto mt-3 max-w-md text-sm leading-6 text-slate-400">
                CoverCanvas helps you turn an image, drawing or idea into a custom prosthetic-cover design — no CAD or 3D experience needed.
              </p>
              <div className="mt-7 flex flex-col items-center gap-3">
                <button onClick={() => setStep(1)} className="btn-primary w-full max-w-xs">Start designing <ArrowRight size={17} /></button>
                <button onClick={skip} className="btn-ghost w-full max-w-xs">Open an existing project</button>
              </div>
            </div>
          )}

          {step === 1 && (
            <div className="fade-in">
              <h2 className="font-heading text-xl font-semibold text-white text-center">How would you like to begin?</h2>
              <p className="mb-5 mt-1 text-center text-sm text-slate-400">Pick one — you can change your mind later.</p>
              <div className="space-y-3">
                {TILES.map(({ key, Icon, title, desc }) => (
                  <button
                    key={key}
                    onClick={() => { setMethod(key); setStep(2); }}
                    className={`flex w-full items-start gap-3 rounded-xl border p-4 text-left transition ${method === key ? 'border-cyan-400/50 bg-cyan-400/[0.08]' : 'border-white/10 bg-white/[0.02] hover:border-white/25'}`}
                  >
                    <span className="mt-0.5 grid h-10 w-10 shrink-0 place-items-center rounded-lg border border-cyan-400/30 bg-cyan-400/10 text-cyan-200"><Icon size={18} /></span>
                    <span>
                      <span className="block text-sm font-semibold text-white">{title}</span>
                      <span className="mt-0.5 block text-xs leading-5 text-slate-400">{desc}</span>
                    </span>
                  </button>
                ))}
              </div>
              <div className="mt-5 flex justify-between">
                <button onClick={() => setStep(0)} className="btn-ghost">Back</button>
                <button onClick={() => setStep(2)} className="btn-secondary">Continue</button>
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="fade-in">
              <h2 className="font-heading text-xl font-semibold text-white text-center">Choose your experience</h2>
              <p className="mb-5 mt-1 text-center text-sm text-slate-400">You can switch between these any time in Settings.</p>
              <div className="grid gap-3 sm:grid-cols-2">
                <button
                  onClick={() => setMode('guided')}
                  className={`rounded-xl border p-4 text-left transition ${mode === 'guided' ? 'border-cyan-400/50 bg-cyan-400/[0.08]' : 'border-white/10 bg-white/[0.02] hover:border-white/25'}`}
                >
                  <span className="mb-1 inline-flex items-center gap-1.5 rounded-full border border-cyan-400/40 bg-cyan-400/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-cyan-200">Recommended</span>
                  <span className="mt-2 block text-sm font-semibold text-white">Guided Mode</span>
                  <span className="mt-1 block text-xs leading-5 text-slate-400">CoverCanvas makes the technical decisions and guides you step by step.</span>
                </button>
                <button
                  onClick={() => setMode('advanced')}
                  className={`rounded-xl border p-4 text-left transition ${mode === 'advanced' ? 'border-violet-400/50 bg-violet-400/[0.08]' : 'border-white/10 bg-white/[0.02] hover:border-white/25'}`}
                >
                  <span className="mb-1 inline-flex items-center gap-1.5 rounded-full border border-violet-400/40 bg-violet-400/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-violet-200">Advanced</span>
                  <span className="mt-2 block text-sm font-semibold text-white">Advanced Mode</span>
                  <span className="mt-1 block text-xs leading-5 text-slate-400">Full professional controls for experienced users.</span>
                </button>
              </div>
              <div className="mt-6 flex flex-col items-center gap-3">
                <button onClick={finish} disabled={busy} className="btn-primary w-full max-w-xs">
                  <Check size={17} /> {busy ? 'Starting…' : `Start in ${mode === 'guided' ? 'Guided' : 'Advanced'} Mode`}
                </button>
                <button onClick={() => setStep(1)} className="text-xs text-slate-500 hover:text-slate-300">Back</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}