import { useRef, useState } from 'react';
import { Wand2, Loader2, Upload, PenTool, ImageIcon, Replace, Trash2, Sparkles, Check } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import { CONCEPT_PRESETS, uid, DEMO_SVGS } from '@/lib/canvasDemo';

export default function CreateDesignPanel({ onAddPiece, onSetMeta, hasSource, sourceThumb, onReplace, onRemove, onPrepare }) {
  const [prompt, setPrompt] = useState('');
  const [busy, setBusy] = useState(false);
  const [concepts, setConcepts] = useState(null);
  const [error, setError] = useState('');
  const [uploading, setUploading] = useState(false);
  const fileRef = useRef(null);
  const drawRef = useRef(null);

  const generate = async () => {
    setError(''); setBusy(true); setConcepts(null);
    try {
      const res = await base44.integrations.Core.InvokeLLM({
        prompt: `Create three clearly different, ORIGINAL, copyright-safe prosthetic cover design concepts inspired by this idea: "${prompt || 'a heroic arachnid-inspired design'}". For each concept return a short title, a one-sentence description, a colour palette (3 hex codes), and a suggested 3D treatment (Colour design, Raised design, Engraved design, Cut-out design, or Sculpted design). Keep them original — never copy official logos or costume patterns.`,
        response_json_schema: { type: 'object', properties: { concepts: { type: 'array', items: { type: 'object', properties: { title: { type: 'string' }, description: { type: 'string' }, palette: { type: 'array', items: { type: 'string' } }, treatment: { type: 'string' } } } } } }
      });
      const list = Array.isArray(res?.concepts) ? res.concepts.slice(0, 3) : [];
      // Merge LLM text with our distinct visual presets so previews look clearly different.
      const merged = CONCEPT_PRESETS.map((p, i) => ({ ...p, ...(list[i] || {}) }));
      setConcepts(merged);
      onSetMeta({ sourceType: 'promptforge', originalPrompt: prompt });
    } catch (e) {
      // PromptForge unavailable — fall back to the local original-inspired presets.
      setConcepts(CONCEPT_PRESETS);
      onSetMeta({ sourceType: 'promptforge', originalPrompt: prompt });
      setError('PromptForge is unavailable — showing original-inspired demo concepts.');
    } finally {
      setBusy(false);
    }
  };

  const selectConcept = (c, i) => {
    onSetMeta({ name: c.title, originalPrompt: prompt, character: (c.tags || [])[0] || 'Heroic', intendedApplicationMode: treatmentToMode(c.treatment) });
    onAddPiece({ name: c.title, src: CONCEPT_PRESETS[i].svg, role: 'primary_emblem', behaviour: 'keep_shape', placement: 'front_centre', effect: treatmentToMode(c.treatment), intensity: 'bold', mainColour: (c.palette || [])[0] || '#38e0f2' });
    onPrepare?.();
  };

  const handleFile = async (file, kind) => {
    if (!file) return;
    setUploading(true); setError('');
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      onSetMeta({ sourceType: kind === 'drawing' ? 'drawing' : 'image' });
      onAddPiece({ name: kind === 'drawing' ? 'My drawing' : 'Uploaded image', src: file_url, role: 'primary_emblem', behaviour: 'keep_shape', placement: 'front_centre', effect: 'colour_texture', intensity: 'standard' });
      onPrepare?.();
    } catch (e) {
      setError('Upload failed — please try a different file.');
    } finally {
      setUploading(false);
    }
  };

  return (
    <aside className="panel flex w-full flex-col gap-4 p-4 lg:w-[300px] lg:shrink-0">
      <h2 className="section-title">Create your design</h2>

      {!hasSource ? (
        <div className="space-y-3">
          <div className="rounded-xl border border-violet-400/25 bg-violet-400/[0.05] p-3">
            <p className="mb-2 flex items-center gap-2 text-xs font-semibold text-violet-200"><Wand2 size={13} /> Describe an idea</p>
            <textarea value={prompt} onChange={e => setPrompt(e.target.value)} placeholder="Describe the design you want…" className="field min-h-[64px] resize-none" />
            <p className="mt-1.5 text-[10px] text-slate-500">e.g. “A bold red and blue arachnid-inspired heroic design with raised web lines and a unique central emblem.”</p>
            <button onClick={generate} disabled={busy} className="btn-violet mt-2 w-full text-sm">{busy ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />} Create concepts</button>
          </div>

          <div className="rounded-xl border border-white/10 bg-white/[0.02] p-3">
            <p className="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-200"><PenTool size={13} /> Upload a drawing</p>
            <input ref={drawRef} type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" className="hidden" onChange={e => handleFile(e.target.files?.[0], 'drawing')} />
            <button onClick={() => drawRef.current?.click()} disabled={uploading} className="btn-secondary w-full text-sm">{uploading ? <Loader2 size={14} className="animate-spin" /> : <PenTool size={14} />} Choose drawing</button>
          </div>

          <div className="rounded-xl border border-white/10 bg-white/[0.02] p-3">
            <p className="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-200"><ImageIcon size={13} /> Upload an image</p>
            <input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" className="hidden" onChange={e => handleFile(e.target.files?.[0], 'image')} />
            <button onClick={() => fileRef.current?.click()} disabled={uploading} className="btn-secondary w-full text-sm">{uploading ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Choose image</button>
          </div>

          {error && <p className="warning-box">{error}</p>}
        </div>
      ) : (
        <div className="space-y-3">
          <div className="flex items-center gap-3 rounded-xl border border-white/10 bg-black/20 p-2.5">
            <div className="h-14 w-14 overflow-hidden rounded-lg border border-white/10 bg-[#0a0e13]">
              <img src={sourceThumb} alt="Source" className="h-full w-full object-contain" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="truncate text-xs font-semibold text-white">Source selected</p>
              <div className="mt-1.5 flex gap-1.5">
                <button onClick={onReplace} className="tool-button !px-2 !py-1"><Replace size={11} /> Replace</button>
                <button onClick={onRemove} className="tool-button !px-2 !py-1"><Trash2 size={11} /> Remove</button>
              </div>
            </div>
          </div>
          <button onClick={onPrepare} className="btn-primary w-full text-sm"><Sparkles size={14} /> Prepare artwork</button>
        </div>
      )}

      {concepts && (
        <div className="space-y-2.5 border-t border-white/10 pt-3">
          <p className="text-[10px] font-semibold uppercase tracking-wider text-slate-500">PromptForge concepts</p>
          {concepts.map((c, i) => (
            <article key={i} className="rounded-xl border border-white/10 bg-black/20 p-2.5">
              <div className="mb-2 aspect-video overflow-hidden rounded-lg border border-white/10 bg-[#0a0e13]"><img src={CONCEPT_PRESETS[i].svg} alt={c.title} className="h-full w-full object-contain" /></div>
              <p className="text-xs font-semibold text-white">{c.title}</p>
              <p className="mt-0.5 text-[10px] leading-4 text-slate-400">{c.description}</p>
              <div className="mt-1.5 flex gap-1">{(c.palette || []).map((hex, j) => <span key={j} className="h-4 w-4 rounded border border-white/20" style={{ background: hex }} title={hex} />)}</div>
              <p className="mt-1.5 text-[10px] text-cyan-200">3D treatment: {c.treatment}</p>
              <span className="mt-1 inline-flex items-center gap-1 rounded border border-violet-400/30 bg-violet-400/10 px-1.5 py-0.5 text-[9px] font-semibold text-violet-200"><Check size={9} /> Original inspired concept</span>
              <button onClick={() => selectConcept(c, i)} className="btn-primary mt-2 w-full text-xs">Use this design</button>
            </article>
          ))}
          {error && <p className="warning-box">{error}</p>}
        </div>
      )}
    </aside>
  );
}

function treatmentToMode(t) {
  const s = (t || '').toLowerCase();
  if (s.includes('raise')) return 'raised_emboss';
  if (s.includes('engrav')) return 'engraving';
  if (s.includes('cut')) return 'stencil';
  if (s.includes('sculpt')) return 'sculpted_relief';
  return 'colour_texture';
}