import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { ArrowRight, ArrowLeft, Upload, PenTool, Image as ImageIcon, Wand2, Check } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import PageHeader from '@/components/app/PageHeader';
import CoverCard from '@/components/covers/CoverCard';
import { Image as ContentImage } from '@/components/ui/image';
import { useExperienceMode } from '@/lib/ExperienceMode';

const inputMethods = [
  ['sketch_3d', 'Sketch to 3D', PenTool, 'Upload a drawing, logo or line art and convert it to printable 3D decoration.'],
  ['image_apply', 'Image Apply', ImageIcon, 'Upload a photo or graphic and apply it as a texture, emboss, engraving or stencil.'],
  ['promptforge', 'PromptForge', Wand2, 'Type a theme and let AI generate original inspired concept directions.']
];

const STEPS = ['Cover', 'Method', 'Artwork'];

export default function NewProject() {
  const navigate = useNavigate();
  const [params] = useSearchParams();
  const methodParam = params.get('method');
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';
  const validMethods = ['sketch_3d', 'image_apply', 'promptforge'];

  const [covers, setCovers] = useState([]);
  const [selected, setSelected] = useState(null);
  const [name, setName] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);
  const [asset, setAsset] = useState(null); // { file_url, width, height, fileName }
  const [inputMethod, setInputMethod] = useState(validMethods.includes(methodParam) ? methodParam : 'sketch_3d');
  const [step, setStep] = useState(methodParam && validMethods.includes(methodParam) ? 2 : 1); // skip Method if onboarding pre-selected

  useEffect(() => {
    base44.entities.CoverModel.filter({ active: true, validationStatus: 'validated' })
      .then(res => setCovers(Array.isArray(res) ? res : []))
      .catch(() => setCovers([]));
  }, []);

  const upload = async e => {
    const file = e.target.files[0];
    if (!file) return;
    setBusy(true); setError(null);
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      const dims = await new Promise((res) => {
        const img = new Image();
        img.onload = () => res({ width: img.naturalWidth, height: img.naturalHeight });
        img.onerror = () => res({ width: 1024, height: 1024 });
        img.src = file_url;
      });
      // Hold the upload locally — the ArtworkAsset is created only after a real
      // project exists, so no orphaned "pending" records are left behind.
      setAsset({ file_url, width: dims.width, height: dims.height, fileName: file.name });
    } catch (err) {
      setError(`Could not upload your file. ${err?.message || ''}`);
    } finally {
      setBusy(false);
    }
  };

  const create = async () => {
    if (!selected) return;
    setBusy(true); setError(null);
    try {
      const user = await base44.auth.me();
      const project = await base44.entities.CoverCanvasProject.create({
        name: name || `${selected.name} design`, owner: user.id, coverModelId: selected.id, status: 'artwork', inputMethod,
        validationStatus: 'not_checked', shireVaultPath: `/SHiRELimbs/CoverCanvas/${Date.now()}`,
        artworkLayers: [], geometrySettings: {}, experienceMode: mode
      });
      if (asset) {
        const a = await base44.entities.ArtworkAsset.create({
          projectId: project.id, originalFile: asset.file_url,
          width: asset.width, height: asset.height, processingSettings: {}
        });
        if (inputMethod === 'sketch_3d') {
          await base44.entities.ArtworkLayer.create({
            projectId: project.id, artworkAssetId: a.id, name: asset.fileName?.replace(/\.[^.]+$/, '') || 'Artwork 1',
            order: 0, visible: true, locked: false, positionX: 0, positionY: 0, scaleX: 1, scaleY: 1, rotation: 0, mirrored: false,
            projectionMode: 'planar', embossHeight: 1, engravingDepth: 0.5, opacity: 1
          });
        }
      }
      const route = { sketch_3d: '/sketch-3d', image_apply: '/image-apply', promptforge: '/promptforge' }[inputMethod];
      navigate(`${route}?project=${project.id}`);
    } catch (err) {
      setError(`Could not create your project. ${err?.message || ''}`);
    } finally {
      setBusy(false);
    }
  };

  // Guided step gating.
  const canContinue = step === 1 ? !!selected : true;
  const next = () => { if (!canContinue) return; if (step < 3) setStep(step + 1); else create(); };
  const back = () => { if (step > 1) setStep(step - 1); };

  const Stepper = (
    <div className="mb-6 flex items-center gap-2">
      {STEPS.map((s, i) => {
        const n = i + 1;
        const done = n < step;
        const current = n === step;
        return (
          <div key={s} className="flex flex-1 items-center gap-2">
            <div className={`grid h-8 w-8 place-items-center rounded-full border text-xs font-semibold transition ${current ? 'border-cyan-400 bg-cyan-400/20 text-cyan-50' : done ? 'border-cyan-400/50 bg-cyan-400/10 text-cyan-200' : 'border-white/10 bg-white/[0.02] text-slate-600'}`}>
              {done ? <Check size={14} /> : n}
            </div>
            <span className={`text-xs font-medium ${current ? 'text-white' : done ? 'text-cyan-200' : 'text-slate-600'}`}>{s}</span>
            {n < STEPS.length && <div className={`mx-2 h-px flex-1 ${done ? 'bg-cyan-400/40' : 'bg-white/10'}`} />}
          </div>
        );
      })}
    </div>
  );

  const methodInfo = inputMethods.find(m => m[0] === inputMethod);

  if (guided) {
    return (
      <>
        <PageHeader eyebrow="New project" title="Create a new cover design" description="Answer a few quick questions and we'll set up your workspace." />
        {Stepper}

        {step === 1 && (
          <section className="panel">
            <h2 className="section-title">Pick your cover</h2>
            <label className="mb-5 block max-w-xl text-sm text-slate-400">Give it a name (optional)
              <input value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Morgan — left transtibial cover" className="field mt-2" />
            </label>
            <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
              {(Array.isArray(covers) ? covers : []).map(c => <CoverCard key={c.id} cover={c} selected={selected?.id === c.id} onSelect={setSelected} />)}
            </div>
            {!covers.length && <div className="empty">No validated cover found. Create or import a cover in the Cover Library first.</div>}
          </section>
        )}

        {step === 2 && (
          <section className="panel">
            <h2 className="section-title">How do you want to create your design?</h2>
            <div className="grid gap-3 sm:grid-cols-3">
              {inputMethods.map(([k, l, Icon, d]) => (
                <button key={k} onClick={() => setInputMethod(k)} className={`rounded-xl border p-4 text-left transition ${inputMethod === k ? 'border-cyan-400/50 bg-cyan-400/[0.08]' : 'border-white/[0.06] hover:border-white/20 hover:bg-white/[0.03]'}`}>
                  <Icon size={20} className={inputMethod === k ? 'text-cyan-300' : 'text-slate-400'} />
                  <b className="mt-3 block text-sm font-semibold text-white">{l}</b>
                  <span className="mt-1 block text-xs text-slate-400">{d}</span>
                </button>
              ))}
            </div>
          </section>
        )}

        {step === 3 && (
          <section className="panel">
            <h2 className="section-title">{inputMethod === 'sketch_3d' ? 'Add your first drawing' : 'Ready to create'}</h2>
            {inputMethod === 'sketch_3d' && (
              <label className="block cursor-pointer">
                <div className="viewport-grid grid min-h-56 place-items-center rounded-xl border border-dashed border-white/15 p-6 text-center">
                  {asset
                    ? <ContentImage src={asset.file_url} alt="Uploaded drawing" fittingType="fit" className="h-56 w-full" />
                    : (<div><Upload className="mx-auto mb-3 text-cyan-300" /><b>{busy ? 'Uploading…' : 'Choose drawing image'}</b><p className="mt-2 text-xs text-slate-500">PNG · JPG · JPEG · WEBP · SVG — temporary Base44 prototype storage</p></div>)}
                </div>
                <input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" onChange={upload} className="hidden" />
              </label>
            )}
            {inputMethod === 'image_apply' && <div className="empty">You can upload your photo or graphic in the Image Apply workspace.</div>}
            {inputMethod === 'promptforge' && <div className="empty">You can generate original concept directions in the PromptForge workspace.</div>}
            <div className="mt-4 rounded-lg border border-cyan-400/25 bg-cyan-400/[0.06] px-4 py-3 text-xs text-cyan-100">
              <b className="text-cyan-200">Your project:</b> {selected?.name || '—'} · {methodInfo?.[1]} {name ? `· “${name}”` : ''}
            </div>
          </section>
        )}

        {error && <div className="warning-box mt-4">{error}</div>}
        <div className="sticky bottom-4 mt-4 flex items-center justify-between">
          <button onClick={back} disabled={step === 1} className="btn-ghost"><ArrowLeft size={17} />Back</button>
          <button disabled={!canContinue || busy} onClick={next} className="btn-primary">{busy ? 'Creating…' : step === 3 ? <>Create project<ArrowRight size={18} /></> : <>Continue<ArrowRight size={18} /></>}</button>
        </div>
      </>
    );
  }

  return (
    <>
      <PageHeader eyebrow="Guided design sequence" title="New CoverCanvas project" description="Stages 1–3 happen here. Geometry, placement, validation and manufacture continue in dedicated workspaces." />

      {/* Step 1 — Cover */}
      <section className="panel mb-5">
        <h2 className="section-title">Stage 1 · Select a validated cover</h2>
        <label className="mb-5 block max-w-xl text-sm text-slate-400">Project name
          <input value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Morgan — left transtibial cover" className="field mt-2" />
        </label>
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {covers.map(c => <CoverCard key={c.id} cover={c} selected={selected?.id === c.id} onSelect={setSelected} />)}
        </div>
        {!covers.length && <div className="panel empty">No validated cover found. Create or import a cover before customising artwork.</div>}
      </section>

      {/* Step 2 — Input method */}
      <section className="panel mb-5">
        <h2 className="section-title">Stage 2 · Choose input method</h2>
        <div className="grid gap-3 sm:grid-cols-3">
          {inputMethods.map(([k, l, Icon, d]) => (
            <button key={k} onClick={() => setInputMethod(k)} className={`rounded-xl border p-4 text-left transition ${inputMethod === k ? 'border-cyan-400/50 bg-cyan-400/[0.08]' : 'border-white/[0.06] hover:border-white/20 hover:bg-white/[0.03]'}`}>
              <Icon size={20} className={inputMethod === k ? 'text-cyan-300' : 'text-slate-400'} />
              <b className="mt-3 block text-sm font-semibold text-white">{l}</b>
              <span className="mt-1 block text-xs text-slate-400">{d}</span>
            </button>
          ))}
        </div>
      </section>

      {/* Step 3 — Artwork (sketch only) */}
      {inputMethod === 'sketch_3d' && (
        <section className="panel mb-5">
          <h2 className="section-title">Stage 3 · Upload a drawing</h2>
          <label className="block cursor-pointer">
            <div className="viewport-grid grid min-h-56 place-items-center rounded-xl border border-dashed border-white/15 p-6 text-center">
              {asset
                ? <ContentImage src={asset.file_url} alt="Uploaded drawing" fittingType="fit" className="h-56 w-full" />
                : (<div><Upload className="mx-auto mb-3 text-cyan-300" /><b>{busy ? 'Uploading…' : 'Choose drawing image'}</b><p className="mt-2 text-xs text-slate-500">PNG · JPG · JPEG · WEBP · SVG — temporary Base44 prototype storage</p></div>)}
            </div>
            <input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" onChange={upload} className="hidden" />
          </label>
        </section>
      )}
      {inputMethod === 'image_apply' && <div className="panel empty mb-5">Continue to Image Apply to upload your photo or graphic.</div>}
      {inputMethod === 'promptforge' && <div className="panel empty mb-5">Continue to PromptForge to generate original concept directions.</div>}

      {error && <div className="warning-box mb-4">{error}</div>}
      <div className="sticky bottom-4 flex justify-end">
        <button disabled={!selected || busy} onClick={create} className="btn-primary">{busy ? 'Creating…' : 'Continue'}<ArrowRight size={18} /></button>
      </div>
    </>
  );
}