import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Wand2, Sparkles, ArrowRight, Loader2, ShieldCheck, Palette, Gauge, FlipHorizontal2, Layers } 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';
import GuidedPromptForge from '@/components/studio/GuidedPromptForge';

const chips = [
  'Spider-Man inspired heroic prosthetic cover',
  'Brutal demon armour cover',
  'Viking rune warrior leg cover',
  'Biomechanical black and silver shell',
  'Dinosaur jungle kids cover',
  'Futuristic stealth ninja prosthetic cover'
];

const decorations = [
  ['colour_texture', 'Colour texture'], ['raised_emboss', 'Emboss'], ['engraving', 'Engrave'], ['sculpted_relief', 'Relief'], ['stencil', 'Stencil']
];
const materials = ['Titanium', 'Carbon fibre', 'PA12 nylon', 'Resin', 'TPU', 'Polished steel'];

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

export default function PromptForge() {
  const [params] = useSearchParams();
  const projectId = params.get('project');
  const navigate = useNavigate();
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';

  const [project, setProject] = useState(null);
  const [cover, setCover] = useState(null);
  const [covers, setCovers] = useState([]);
  const [name, setName] = useState('');
  const [busy, setBusy] = useState(false);

  const [prompt, setPrompt] = useState('');
  const [styleTags, setStyleTags] = useState('');
  const [moodTags, setMoodTags] = useState('');
  const [colour, setColour] = useState('');
  const [material, setMaterial] = useState('Titanium');
  const [detail, setDetail] = useState(60);
  const [symmetry, setSymmetry] = useState(true);
  const [armour, setArmour] = useState('armour');
  const [edge, setEdge] = useState('aggressive');
  const [decoration, setDecoration] = useState('colour_texture');

  // Guided visual choices (mapped to the shared controls at generate time).
  const [style, setStyle] = useState('');
  const [intensity, setIntensity] = useState('Balanced');
  const [colourMode, setColourMode] = useState('Let SHiRE choose');
  const [layout, setLayout] = useState('Let SHiRE choose');

  const [generating, setGenerating] = useState(false);
  const [applying, setApplying] = useState(null);
  const [concepts, setConcepts] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!projectId) {
      base44.entities.CoverModel.filter({ active: true, validationStatus: 'validated' })
        .then(res => setCovers(Array.isArray(res) ? res : []))
        .catch(() => setCovers([]));
      return;
    }
    let alive = true;
    Promise.all([
      base44.entities.CoverCanvasProject.get(projectId).catch(() => null),
      base44.entities.PromptConcept.filter({ projectId }).catch(() => [])
    ]).then(async ([p, existing]) => {
      if (!alive) return;
      setProject(p);
      const safe = Array.isArray(existing) ? existing : [];
      if (safe.length) setConcepts(safe);
      if (p?.coverModelId) { try { setCover(await base44.entities.CoverModel.get(p.coverModelId)); } catch { setCover(null); } }
    });
    return () => { alive = false; };
  }, [projectId]);

  const startProject = async () => {
    if (!cover) return;
    setBusy(true);
    try {
      const user = await base44.auth.me();
      const p = await base44.entities.CoverCanvasProject.create({
        name: name || `${cover.name} promptforge`, owner: user.id, coverModelId: cover.id,
        status: 'artwork', inputMethod: 'promptforge', validationStatus: 'not_checked',
        shireVaultPath: `/SHiRELimbs/CoverCanvas/${Date.now()}`, artworkLayers: [], geometrySettings: {}, experienceMode: mode
      });
      navigate(`/promptforge?project=${p.id}`);
    } catch (e) {
      setError(`Could not create project. ${e?.message || ''}`);
    } finally {
      setBusy(false);
    }
  };

  const generate = async () => {
    if (!projectId || !prompt.trim()) return;
    setGenerating(true);
    setError(null);
    try {
      // IDOR guard: confirm the caller owns this project before any destructive write.
      const [me, p] = await Promise.all([base44.auth.me(), base44.entities.CoverCanvasProject.get(projectId).catch(() => null)]);
      if (!p || (p.created_by_id !== me.id && me.role !== 'admin')) {
        setError('You do not have access to this project.');
        return;
      }
      const controls = guided
        ? {
            styleTags: style || '', colour: colourMode === 'Choose colours' ? colour : '',
            detail: intensity === 'Subtle' ? 30 : intensity === 'Extreme' ? 95 : 65,
            symmetry: layout === 'Asymmetrical' ? false : layout === 'Symmetrical' ? true : symmetry,
            material, armour, edge, decoration
          }
        : { styleTags, moodTags, colour, material, detail, symmetry, armour, edge, decoration };
      const llm = await base44.integrations.Core.InvokeLLM({
        prompt: `You are a prosthetic-cover concept designer. Produce 3 ORIGINAL inspired concept directions for the user's prompt. Never copy copyrighted logos, official franchise artwork or exact costume layouts — create an original theme-inspired interpretation. Return JSON with "concepts": array of 3 objects, each with: title (short), summary (2 sentences), styleTags (array of 3), moodTags (array of 3), colourPalette (array of 4 hex codes), applicationModeSuggestion (one of colour_texture, raised_emboss, engraving, sculpted_relief, stencil), originalityNote (how it stays original). User prompt: "${prompt}". Controls: ${JSON.stringify(controls)}.`,
        response_json_schema: {
          type: 'object',
          properties: {
            concepts: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  title: { type: 'string' }, summary: { type: 'string' },
                  styleTags: { type: 'array', items: { type: 'string' } },
                  moodTags: { type: 'array', items: { type: 'string' } },
                  colourPalette: { type: 'array', items: { type: 'string' } },
                  applicationModeSuggestion: { type: 'string' }, originalityNote: { type: 'string' }
                }
              }
            }
          }
        }
      });
      const raw = Array.isArray(llm?.concepts) ? llm.concepts : [];
      const withImages = await Promise.all(raw.map(async (c) => {
        const imgPrompt = `Original inspired prosthetic cover concept art, no copyrighted logos or franchise imagery. Theme: ${c.title}. ${c.summary}. Palette: ${(c.colourPalette || []).join(', ')}. Style: ${(c.styleTags || []).join(', ')}. Mood: ${(c.moodTags || []).join(', ')}. ${symmetry ? 'Symmetrical' : 'Asymmetrical'}. ${armour === 'armour' ? 'Armoured' : 'Organic'} ${edge} styling. High detail decorative surface design for a prosthetic limb cover, studio render.`;
        let preview = '';
        try { const r = await base44.integrations.Core.GenerateImage({ prompt: imgPrompt }); preview = r.url; } catch { preview = ''; }
        return { ...c, previewImageUrl: preview, generationStatus: 'generated' };
      }));
      await base44.entities.PromptConcept.deleteMany({ projectId });
      const saved = await base44.entities.PromptConcept.bulkCreate(
        withImages.map(c => ({
          projectId, promptText: prompt, title: c.title, summary: c.summary,
          styleTags: c.styleTags, moodTags: c.moodTags, colourPalette: c.colourPalette,
          applicationModeSuggestion: c.applicationModeSuggestion || 'colour_texture',
          previewImageUrl: c.previewImageUrl, originalInspiredFlag: true, selected: false,
          generationStatus: c.generationStatus || 'generated'
        }))
      );
      setConcepts(Array.isArray(saved) ? saved : []);
    } catch (e) {
      setError(e.message || 'Concept generation failed.');
    } finally {
      setGenerating(false);
    }
  };

  // Apply a concept: create a real ArtworkAsset + ArtworkLayer, avoid duplicates,
  // record the selected concept, and open the Studio.
  const applyConcept = async (c) => {
    if (!projectId || applying) return;
    setApplying(c.id);
    try {
      const existingLayers = await base44.entities.ArtworkLayer.filter({ projectId }).catch(() => []);
      const existingAssets = await base44.entities.ArtworkAsset.filter({ projectId }).catch(() => []);
      const safeLayers = Array.isArray(existingLayers) ? existingLayers : [];
      const safeAssets = Array.isArray(existingAssets) ? existingAssets : [];
      const existingAsset = safeAssets.find(a => a?.processingSettings?.conceptId === c.id);
      let assetId = existingAsset?.id;
      if (!assetId) {
        const { w, h } = await loadImageDims(c.previewImageUrl);
        const a = await base44.entities.ArtworkAsset.create({
          projectId, originalFile: c.previewImageUrl, processedFile: c.previewImageUrl,
          width: w, height: h, processingSettings: { conceptId: c.id, colourPalette: c.colourPalette }, backgroundRemoved: false
        });
        assetId = a.id;
      }
      const hasLayer = safeLayers.some(l => l.artworkAssetId === assetId);
      if (!hasLayer) {
        await base44.entities.ArtworkLayer.create({
          projectId, artworkAssetId: assetId, name: c.title || 'Concept layer', order: safeLayers.length,
          visible: true, locked: false, positionX: 0, positionY: 0, scaleX: 1, scaleY: 1, rotation: 0, mirrored: false,
          projectionMode: 'planar', embossHeight: c.applicationModeSuggestion === 'raised_emboss' ? 1.2 : 1,
          engravingDepth: c.applicationModeSuggestion === 'engraving' ? 0.8 : 0.5, opacity: 1
        });
      }
      await base44.entities.PromptConcept.update(c.id, { selected: true });
      await base44.entities.CoverCanvasProject.update(projectId, {
        selectedConceptId: c.id, applicationMode: c.applicationModeSuggestion || 'colour_texture', status: 'studio'
      });
      navigate(`/studio?project=${projectId}`);
    } catch (e) {
      setError(`Could not apply concept. ${e?.message || ''}`);
    } finally {
      setApplying(null);
    }
  };

  return (
    <>
      <PageHeader
        eyebrow={guided ? 'Describe your idea' : 'Input · PromptForge'}
        title={guided ? 'Describe your cover idea' : 'PromptForge — AI concept chamber'}
        description={guided
          ? 'Tell PromptForge what you want and receive three original design concepts to choose from.'
          : 'Type a theme. The AI generates three original, inspired concept directions (never direct franchise copies). Each is previewed and selectable for conversion to cover decoration.'}
      />

      {!projectId && (
        <section className="panel mb-5">
          <h2 className="section-title">Start a PromptForge project</h2>
          <label className="form-label">Project name<input className="field" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Heroic arachnid cover" /></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={cover?.id === c.id} onSelect={setCover} />)}
          </div>
          {!covers.length && <div className="empty">No validated covers. Create or import one in the Cover Library first.</div>}
          <div className="mt-4 flex justify-end"><button disabled={!cover || busy} onClick={startProject} className="btn-primary">{busy ? 'Creating…' : 'Create project'}<ArrowRight size={17} /></button></div>
          {error && <div className="warning-box mt-3">{error}</div>}
        </section>
      )}

      {projectId && guided ? (
        <GuidedPromptForge
          prompt={prompt} setPrompt={setPrompt}
          style={style} setStyle={setStyle} intensity={intensity} setIntensity={setIntensity}
          colourMode={colourMode} setColourMode={setColourMode} colour={colour} setColour={setColour}
          layout={layout} setLayout={setLayout}
          generate={generate} generating={generating} concepts={concepts} applyConcept={applyConcept} applying={applying} error={error}
        />
      ) : projectId && (
        <div className="grid gap-5 xl:grid-cols-[400px_1fr]">
          <section className="panel h-fit">
            <h2 className="section-title"><Wand2 size={18} className="text-violet-300" />Prompt & controls</h2>
            <label className="form-label">Design prompt
              <textarea className="field min-h-28 resize-none" value={prompt} onChange={e => setPrompt(e.target.value)} placeholder="e.g. Spider-Man inspired heroic prosthetic cover" />
            </label>
            <div className="mb-4 flex flex-wrap gap-1.5">{chips.map(c => <button key={c} onClick={() => setPrompt(c)} className="chip">{c}</button>)}</div>
            <div className="grid grid-cols-2 gap-3">
              <label className="form-label">Style tags<input className="field" value={styleTags} onChange={e => setStyleTags(e.target.value)} placeholder="heroic, dynamic" /></label>
              <label className="form-label">Mood tags<input className="field" value={moodTags} onChange={e => setMoodTags(e.target.value)} placeholder="bold, energetic" /></label>
            </div>
            <label className="form-label"><Palette size={13} className="inline" />Colour preference<input className="field" value={colour} onChange={e => setColour(e.target.value)} placeholder="red & blue" /></label>
            <label className="form-label">Suggested material<select className="field" value={material} onChange={e => setMaterial(e.target.value)}>{materials.map(m => <option key={m} value={m}>{m}</option>)}</select></label>
            <label className="form-label"><Gauge size={13} className="inline" />Design intensity<span className="mono text-slate-200">{detail}%</span>
              <input type="range" min={0} max={100} value={detail} onChange={e => setDetail(Number(e.target.value))} className="w-full accent-violet-400" />
            </label>
            <div className="grid grid-cols-2 gap-3">
              <label className="flex items-center gap-2 rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2.5 text-sm text-slate-300"><FlipHorizontal2 size={14} className="text-slate-500" /><input type="checkbox" checked={symmetry} onChange={e => setSymmetry(e.target.checked)} className="h-4 w-4 accent-violet-400" />Symmetry</label>
              <select className="field" value={armour} onChange={e => setArmour(e.target.value)}><option value="armour">Armour</option><option value="organic">Organic</option></select>
              <select className="field" value={edge} onChange={e => setEdge(e.target.value)}><option value="aggressive">Aggressive</option><option value="soft">Soft</option></select>
              <select className="field" value={decoration} onChange={e => setDecoration(e.target.value)}>{decorations.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select>
            </div>
            <div className="mt-4 flex items-center gap-2 rounded-lg border border-violet-400/25 bg-violet-400/[0.07] px-3 py-2.5 text-xs text-violet-100"><ShieldCheck size={15} className="text-violet-300" />Original-inspired · copyright-safe (no franchise copies)</div>
            <button disabled={!prompt.trim() || generating} onClick={generate} className="btn-violet mt-5 w-full">{generating ? <><Loader2 size={17} className="animate-spin" />Generating concepts…</> : <><Sparkles size={17} />Generate 3 concepts</>}</button>
            <p className="mt-3 text-xs text-slate-500">AI concept generation uses built-in integration credits (1 LLM + 3 images per generation).</p>
            {error && <div className="warning-box mt-3">{error}</div>}
          </section>
          <section>
            <h2 className="section-title mb-4"><Layers size={16} className="text-violet-300" />Concept directions</h2>
            {!concepts.length && !generating && <div className="panel empty">No concepts yet. Enter a prompt and generate.</div>}
            {generating && <div className="panel empty"><Loader2 className="mx-auto mb-2 animate-spin text-violet-300" />Generating original concept directions…</div>}
            <div className="grid gap-5 md:grid-cols-2">
              {(Array.isArray(concepts) ? concepts : []).map(c => {
                const treatment = (decorations.find(d => d[0] === c.applicationModeSuggestion) || [])[1] || c.applicationModeSuggestion;
                return (
                  <article key={c.id} className="panel flex flex-col overflow-hidden p-0 fade-in">
                    <div className="relative aspect-[4/3] overflow-hidden bg-[radial-gradient(circle_at_50%_40%,#1a1530,#0a0e13_70%)]">
                      {c.previewImageUrl ? <ContentImage src={c.previewImageUrl} alt={c.title} fittingType="fill" className="h-full w-full" /> : <div className="grid h-full place-items-center text-center text-xs text-slate-500"><div><Sparkles size={26} className="mx-auto mb-2 text-violet-400/40" /><b className="block text-violet-200">Concept preview simulation</b></div></div>}
                      <span className="absolute left-3 top-3 rounded-md border border-violet-400/40 bg-violet-500/20 px-2 py-0.5 text-[10px] font-semibold text-violet-100 backdrop-blur">Original inspired concept</span>
                    </div>
                    <div className="flex flex-1 flex-col p-4">
                      <h3 className="font-heading text-base font-semibold text-white">{c.title}</h3>
                      <p className="mt-1 text-sm leading-5 text-slate-400">{c.summary}</p>
                      <div className="mt-3 flex flex-wrap gap-1.5">{(c.styleTags || []).map(t => <span key={t} className="chip">{t}</span>)}</div>
                      <div className="mt-4 space-y-2 text-xs">
                        <div className="readout"><span className="readout-label">Suggested material</span><span className="readout-value">{material}</span></div>
                        <div className="readout"><span className="readout-label">Printing method</span><span className="readout-value">{treatment}</span></div>
                        <div className="readout"><span className="readout-label">Emboss / engrave</span><span className="readout-value">{treatment}</span></div>
                      </div>
                      <div className="mt-3 flex items-center gap-1.5">{(c.colourPalette || []).map(col => <span key={col} className="h-5 w-5 rounded border border-white/20" style={{ background: col }} title={col} />)}</div>
                      <div className="mt-auto pt-4"><button disabled={!!applying} onClick={() => applyConcept(c)} className="btn-violet w-full">{applying === c.id ? <><Loader2 size={16} className="animate-spin" />Applying…</> : <>Apply to Cover<ArrowRight size={16} /></>}</button></div>
                    </div>
                  </article>
                );
              })}
            </div>
          </section>
        </div>
      )}
    </>
  );
}