import { useState } from 'react';
import { Sparkles, Loader2, ArrowRight, ChevronDown, ShieldCheck, Wand2 } from 'lucide-react';
import { Image as ContentImage } from '@/components/ui/image';

const STYLES = ['Clean', 'Bold', 'Futuristic', 'Mechanical', 'Organic', 'Gothic', 'Playful'];
const INTENSITIES = ['Subtle', 'Balanced', 'Extreme'];
const EFFECT_LABEL = {
  colour_texture: 'Colour', raised_emboss: 'Raised', engraving: 'Engraved',
  stencil: 'Cut-out', sculpted_relief: 'Sculpted'
};

function Choice({ label, options, value, onChange }) {
  return (
    <div>
      <p className="mb-1.5 text-xs font-semibold uppercase tracking-wider text-slate-500">{label}</p>
      <div className="flex flex-wrap gap-1.5">
        {options.map(o => (
          <button key={o} onClick={() => onChange(o)} className={`chip ${value === o ? 'chip-active' : ''}`}>{o}</button>
        ))}
      </div>
    </div>
  );
}

export default function GuidedPromptForge({
  prompt, setPrompt,
  style, setStyle, intensity, setIntensity, colourMode, setColourMode, colour, setColour, layout, setLayout,
  generate, generating, concepts, applyConcept, applying, error
}) {
  const [whyOpen, setWhyOpen] = useState({});
  const safeConcepts = Array.isArray(concepts) ? concepts : [];

  return (
    <div className="grid gap-5 xl:grid-cols-[420px_1fr]">
      <section className="panel h-fit">
        <h2 className="section-title"><Wand2 size={18} className="text-violet-300" />Describe your cover idea</h2>
        <textarea className="field min-h-28 resize-none" value={prompt} onChange={e => setPrompt(e.target.value)}
          placeholder="Example: A bold red and blue spider-inspired heroic design with raised web lines and a unique emblem." />
        <div className="mt-4 space-y-4">
          <Choice label="Style" options={STYLES} value={style} onChange={setStyle} />
          <Choice label="Intensity" options={INTENSITIES} value={intensity} onChange={setIntensity} />
          <Choice label="Colours" options={['Let SHiRE choose', 'Choose colours']} value={colourMode} onChange={setColourMode} />
          {colourMode === 'Choose colours' && (
            <input className="field" value={colour} onChange={e => setColour(e.target.value)} placeholder="e.g. red & blue" />
          )}
          <Choice label="Layout" options={['Let SHiRE choose', 'Symmetrical', 'Asymmetrical']} value={layout} onChange={setLayout} />
        </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 — we create an original design, never a franchise copy.
        </div>
        <button disabled={!prompt.trim() || generating} onClick={generate} className="btn-violet mt-5 w-full">
          {generating ? <><Loader2 size={17} className="animate-spin" />Creating your designs…</> : <><Sparkles size={17} />Create my designs</>}
        </button>
        <p className="mt-3 text-xs text-slate-500">Uses 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">Your design ideas</h2>
        {!safeConcepts.length && !generating && <div className="panel empty">Describe an idea and tap Create my designs to see three original concepts.</div>}
        {generating && <div className="panel empty"><Loader2 className="mx-auto mb-2 animate-spin text-violet-300" />Creating original concept directions…</div>}
        <div className="grid gap-5 md:grid-cols-2">
          {safeConcepts.map(c => {
            const eff = EFFECT_LABEL[c.applicationModeSuggestion] || c.applicationModeSuggestion;
            const needsEngine = c.applicationModeSuggestion === 'stencil' || c.applicationModeSuggestion === 'sculpted_relief';
            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</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 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-3 flex flex-wrap items-center gap-2 text-xs text-slate-400">
                    <span className="rounded border border-cyan-400/25 bg-cyan-400/10 px-2 py-1 text-cyan-200">Recommended: {eff}</span>
                    {needsEngine && <span className="sim-badge">Geometry Engine</span>}
                  </div>
                  <button disabled={!!applying} onClick={() => applyConcept(c)} className="btn-violet mt-4 w-full">
                    {applying === c.id ? <><Loader2 size={16} className="animate-spin" />Applying…</> : <>Use this design<ArrowRight size={16} /></>}
                  </button>
                  <button onClick={() => setWhyOpen(s => ({ ...s, [c.id]: !s[c.id] }))} className="mt-2 flex items-center gap-1 text-[11px] text-slate-500 hover:text-slate-300">
                    <ChevronDown size={12} className={`transition ${whyOpen[c.id] ? 'rotate-180' : ''}`} />Why this works
                  </button>
                  {whyOpen[c.id] && (
                    <div className="mt-2 rounded-lg border border-white/10 bg-black/20 p-3 text-[11px] leading-4 text-slate-400">
                      <p><b className="text-slate-300">Originality:</b> {c.originalityNote || 'An original theme-inspired design — no franchise logos or copied artwork.'}</p>
                      <p className="mt-1"><b className="text-slate-300">Style:</b> {(c.styleTags || []).join(', ')}</p>
                      <p className="mt-1"><b className="text-slate-300">Mood:</b> {(c.moodTags || []).join(', ')}</p>
                    </div>
                  )}
                </div>
              </article>
            );
          })}
        </div>
      </section>
    </div>
  );
}