import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Wand2, PenTool, Image as ImageIcon, Combine, ArrowRight, ArrowLeft, Save, Loader2, Sparkles, Upload, ShieldCheck } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import { useExperienceMode } from '@/lib/ExperienceMode';
import PageHeader from '@/components/app/PageHeader';
import { Image as ContentImage } from '@/components/ui/image';
import { CHARACTER_CHOICES, INTENDED_RESULTS, PLACEMENT_CHOICES } from '@/lib/adaptation';

const SOURCES = [
  ['promptforge', 'Describe an idea', 'Use PromptForge to create original concepts.', Wand2],
  ['drawing', 'Upload a drawing', 'Turn a sketch or line drawing into a reusable design.', PenTool],
  ['image', 'Upload an image', 'Use a picture, logo, pattern or existing artwork.', ImageIcon],
  ['combined', 'Combine sources', 'Use more than one image, drawing or concept.', Combine]
];

const loadImageDims = (url) => new Promise((res) => { const i = new Image(); i.onload = () => res({ w: i.naturalWidth || 1024, h: i.naturalHeight || 1024 }); i.onerror = () => res({ w: 1024, h: 1024 }); i.src = url; });

export default function CreateDesign() {
  const [params] = useSearchParams();
  const editId = params.get('edit');
  const navigate = useNavigate();
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';

  const [step, setStep] = useState(editId ? 3 : 1);
  const [source, setSource] = useState('promptforge');
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [prompt, setPrompt] = useState('');
  const [intensity, setIntensity] = useState('standard');
  const [files, setFiles] = useState([]); // uploaded file refs
  const [uploads, setUploads] = useState([]); // {url} per piece
  const [character, setCharacter] = useState('');
  const [intended, setIntended] = useState('colour_texture');
  const [placement, setPlacement] = useState('let_shire_choose');
  const [symmetry, setSymmetry] = useState('let_shire_choose');
  const [busy, setBusy] = useState(false);
  const [edit, setEdit] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!editId) return;
    let alive = true;
    base44.entities.UniversalDesign.get(editId).then(async d => {
      if (!alive) return;
      setEdit(d);
      setName(d.name || ''); setDescription(d.description || ''); setSource(d.sourceType || 'promptforge');
      setPrompt(d.originalPrompt || ''); setCharacter(d.character || ''); setIntended(d.intendedApplicationMode || 'colour_texture');
      setPlacement(d.placementIntent || 'let_shire_choose'); setSymmetry(d.symmetryPreference || 'let_shire_choose');
      if (d.masterPreviewImageUrl) setUploads([{ url: d.masterPreviewImageUrl }]);
    }).catch(() => setError('Could not load design.'));
    return () => { alive = false; };
  }, [editId]);

  const onFiles = async (list) => {
    setError(null);
    const arr = Array.from(list || []);
    if (!arr.length) return;
    setBusy(true);
    try {
      const uploaded = await Promise.all(arr.map(async (f) => {
        const r = await base44.integrations.Core.UploadFile({ file: f });
        return { url: r.file_url };
      }));
      setUploads(u => [...u, ...uploaded]);
      setFiles(fs => [...fs, ...arr]);
    } catch { setError('Upload failed. Try again.'); }
    finally { setBusy(false); }
  };

  const generate = async () => {
    if (!prompt.trim()) return;
    setBusy(true); setError(null);
    try {
      const styleSuffix = character ? `, ${character.toLowerCase()} style` : '';
      const imgPrompt = `Original inspired prosthetic limb cover concept art, no copyrighted logos or franchise imagery. Theme: ${prompt}. Decorative surface design${styleSuffix}. High detail, studio render, centered emblem on plain background.`;
      const r = await base44.integrations.Core.GenerateImage({ prompt: imgPrompt });
      setUploads([{ url: r.url }]);
    } catch { setError('Concept generation failed. Try again or upload an image instead.'); }
    finally { setBusy(false); }
  };

  const save = async (andFit) => {
    if (!name.trim() || !uploads.length) { setError('Add a name and at least one design piece first.'); return; }
    setBusy(true); setError(null);
    try {
      const me = await base44.auth.me();
      const designId = edit?.id || null;
      const palette = [];

      // Create / update artwork assets + layers
      let assetIds = edit?.masterArtworkAssetIds || [];
      if (!edit || uploads.length) {
        const created = await Promise.all(uploads.map(async (u, i) => {
          const { w, h } = await loadImageDims(u.url);
          const a = await base44.entities.ArtworkAsset.create({
            projectId: designId || 'pending', originalFile: u.url, processedFile: u.url,
            width: w, height: h, backgroundRemoved: false, processingSettings: { sourceIndex: i }
          });
          return a.id;
        }));
        assetIds = created;
      }

      const payload = {
        name, owner: me.id, description, sourceType: source,
        status: 'saved', masterPreviewImageUrl: uploads[0].url,
        originalPrompt: source === 'promptforge' ? prompt : '',
        styleTags: character ? [character] : [], moodTags: [],
        colourPalette: palette, intendedApplicationMode: intended,
        preferredIntensity: intensity, symmetryPreference: symmetry,
        character, placementIntent: placement, masterArtworkAssetIds: assetIds,
        originalInspiredFlag: true, archived: false
      };

      let id = designId;
      if (edit) {
        await base44.entities.UniversalDesign.update(edit.id, { ...payload, version: (edit.version || 1) + 1 });
        // Recreate layers for the edit (simple: clear + re-create)
        const old = await base44.entities.UniversalDesignLayer.filter({ universalDesignId: edit.id }).catch(() => []);
        if (Array.isArray(old) && old.length) await base44.entities.UniversalDesignLayer.deleteMany({ id: { $in: old.map(o => o.id) } });
      } else {
        const d = await base44.entities.UniversalDesign.create({ ...payload, version: 1 });
        id = d.id;
        // Fix asset projectId to the real design id
        await base44.entities.ArtworkAsset.updateMany({ id: { $in: assetIds } }, { $set: { projectId: id } }).catch(() => {});
      }

      const roleFor = (i) => i === 0 ? 'primary_emblem' : 'accent_detail';
      await base44.entities.UniversalDesignLayer.bulkCreate(assetIds.map((aid, i) => ({
        universalDesignId: id, artworkAssetId: aid, name: `Piece ${i + 1}`, order: i,
        visible: true, locked: false, role: roleFor(i),
        applicationIntent: intended === 'mixed' ? 'colour_texture' : intended,
        relativePosition: { u: 0.5, v: 0.5 }, relativeScale: { w: 0.7, h: 0.7 }, relativeRotation: 0,
        aspectPolicy: i === 0 ? 'keep_shape' : 'flexible',
        focalPriority: i === 0 ? 10 : 1,
        protectedFromDistortion: i === 0, mayClip: i > 0, mayRepeat: i > 0
      })));

      if (andFit) navigate(`/fit-design?design=${id}`);
      else navigate('/designs');
    } catch (e) { setError(`Could not save design. ${e?.message || ''}`); }
    finally { setBusy(false); }
  };

  const StepDots = () => (
    <div className="mb-5 flex items-center gap-2">
      {[1, 2, 3, 4, 5, 6].map(n => (
        <span key={n} className={`h-1.5 flex-1 rounded-full ${step >= n ? 'bg-cyan-400' : 'bg-white/10'}`} />
      ))}
    </div>
  );

  return (
    <>
      <PageHeader
        eyebrow={guided ? 'Create a Universal Design' : 'Wizard · Universal Design'}
        title={edit ? 'Edit universal design' : 'Create a universal design'}
        description="Create your design once. Fit it to any compatible LimbForge cover later."
      />
      <div className="panel max-w-3xl">
        <StepDots />

        {step === 1 && (
          <div>
            <h2 className="section-title">How would you like to create it?</h2>
            <div className="grid gap-3 sm:grid-cols-2">
              {SOURCES.map(([k, t, d, Icon]) => (
                <button key={k} onClick={() => { setSource(k); setStep(2); }} className={`panel flex items-start gap-3 p-4 text-left transition hover:border-cyan-400/40 ${source === k ? 'border-cyan-400/50' : ''}`}>
                  <span className="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><b className="block text-sm font-semibold text-white">{t}</b><span className="mt-0.5 block text-xs text-slate-400">{d}</span></span>
                </button>
              ))}
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <h2 className="section-title">{source === 'promptforge' ? 'Describe your idea' : 'Upload your artwork'}</h2>
            <label className="form-label">Design name<input className="field" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Arachnid Hero" /></label>
            <label className="form-label">Description (optional)<input className="field" value={description} onChange={e => setDescription(e.target.value)} placeholder="What is this design about?" /></label>

            {source === 'promptforge' && (
              <div>
                <label className="form-label">Describe your idea<textarea className="field min-h-24 resize-none" value={prompt} onChange={e => setPrompt(e.target.value)} placeholder="e.g. Heroic arachnid-inspired cover with web patterns" /></label>
                <button disabled={!prompt.trim() || busy} onClick={generate} className="btn-violet">{busy ? <Loader2 size={16} className="animate-spin" /> : <Sparkles size={16} />} Generate design</button>
                <p className="mt-2 flex items-center gap-1 text-[11px] text-violet-200"><ShieldCheck size={12} />Original-inspired · copyright-safe (no franchise copies)</p>
              </div>
            )}

            {source !== 'promptforge' && (
              <div>
                <label className="tool-button w-full cursor-pointer justify-center"><Upload size={14} /> Upload {source === 'combined' ? 'multiple files' : 'a file'}
                  <input type="file" accept="image/*" multiple={source === 'combined'} className="hidden" onChange={e => onFiles(e.target.files)} />
                </label>
                {busy && <p className="mt-2 text-xs text-slate-400"><Loader2 size={12} className="mr-1 inline animate-spin" />Uploading…</p>}
              </div>
            )}

            {uploads.length > 0 && (
              <div className="mt-4 grid grid-cols-3 gap-2">
                {uploads.map((u, i) => (
                  <div key={i} className="overflow-hidden rounded-lg border border-white/10"><ContentImage src={u.url} alt={`Piece ${i + 1}`} fittingType="fill" className="aspect-square w-full" /></div>
                ))}
              </div>
            )}

            <div className="mt-5 flex justify-between">
              <button onClick={() => setStep(1)} className="btn-ghost"><ArrowLeft size={15} /> Back</button>
              <button disabled={!uploads.length || !name.trim()} onClick={() => setStep(3)} className="btn-primary">Continue <ArrowRight size={15} /></button>
            </div>
          </div>
        )}

        {step === 3 && (
          <div>
            <h2 className="section-title">Prepare the design</h2>
            <p className="mb-4 text-sm text-slate-400">Your artwork is ready. For drawings, you can refine the clean mask later in Image Processing. Choose the design character next.</p>
            <div className="flex justify-between">
              <button onClick={() => setStep(2)} className="btn-ghost"><ArrowLeft size={15} /> Back</button>
              <button onClick={() => setStep(4)} className="btn-primary">Continue <ArrowRight size={15} /></button>
            </div>
          </div>
        )}

        {step === 4 && (
          <div>
            <h2 className="section-title">Choose the design character</h2>
            <div className="flex flex-wrap gap-2">
              {CHARACTER_CHOICES.map(c => (
                <button key={c} onClick={() => setCharacter(c)} className={`chip ${character === c ? 'chip-active' : ''}`}>{c}</button>
              ))}
            </div>
            <div className="mt-5 flex justify-between">
              <button onClick={() => setStep(3)} className="btn-ghost"><ArrowLeft size={15} /> Back</button>
              <button disabled={!character} onClick={() => setStep(5)} className="btn-primary">Continue <ArrowRight size={15} /></button>
            </div>
          </div>
        )}

        {step === 5 && (
          <div>
            <h2 className="section-title">Choose the intended result</h2>
            <p className="mb-3 text-xs text-slate-400">These are design intentions, not final geometry.</p>
            <div className="grid gap-2 sm:grid-cols-2">
              {INTENDED_RESULTS.map(([k, t, d]) => (
                <button key={k} onClick={() => setIntended(k)} className={`panel flex flex-col items-start gap-1 p-3 text-left transition hover:border-cyan-400/40 ${intended === k ? 'border-cyan-400/50' : ''}`}>
                  <b className="text-sm text-white">{t}</b><span className="text-[11px] text-slate-400">{d}</span>
                </button>
              ))}
            </div>
            <h3 className="mt-5 mb-2 text-xs font-semibold uppercase tracking-wider text-slate-400">Where should it sit?</h3>
            <div className="flex flex-wrap gap-2">
              {PLACEMENT_CHOICES.map(([k, t]) => (
                <button key={k} onClick={() => setPlacement(k)} className={`chip ${placement === k ? 'chip-active' : ''}`}>{t}</button>
              ))}
            </div>
            <div className="mt-5 flex justify-between">
              <button onClick={() => setStep(4)} className="btn-ghost"><ArrowLeft size={15} /> Back</button>
              <button onClick={() => setStep(6)} className="btn-primary">Continue <ArrowRight size={15} /></button>
            </div>
          </div>
        )}

        {step === 6 && (
          <div>
            <h2 className="section-title">Save universal design</h2>
            <div className="mb-4 grid gap-2 sm:grid-cols-3">
              <label className="form-label">Intensity<select className="field" value={intensity} onChange={e => setIntensity(e.target.value)}><option value="subtle">Subtle</option><option value="standard">Standard</option><option value="bold">Bold</option></select></label>
              <label className="form-label">Symmetry<select className="field" value={symmetry} onChange={e => setSymmetry(e.target.value)}><option value="symmetrical">Symmetrical</option><option value="asymmetrical">Asymmetrical</option><option value="let_shire_choose">Let SHiRE choose</option></select></label>
            </div>
            <div className="rounded-lg border border-cyan-400/20 bg-cyan-400/[0.06] p-3 text-xs text-cyan-100">
              Saving a universal design keeps it independent of any cover. You can fit it to multiple covers later without losing the original.
            </div>
            {error && <div className="warning-box mt-3">{error}</div>}
            <div className="mt-5 flex flex-wrap justify-between gap-2">
              <button onClick={() => setStep(5)} className="btn-ghost"><ArrowLeft size={15} /> Back</button>
              <div className="flex gap-2">
                <button disabled={busy} onClick={() => save(false)} className="btn-secondary"><Save size={15} /> Save universal design</button>
                <button disabled={busy} onClick={() => save(true)} className="btn-primary">{busy ? <Loader2 size={15} className="animate-spin" /> : <Sparkles size={15} />} Save & fit to a cover</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
}