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

const MODES = {
  colour_texture: 'Colour', raised_emboss: 'Emboss', engraving: 'Engrave',
  sculpted_relief: 'Relief', stencil: 'Stencil'
};

// Collapsible PromptForge concept panel embedded in the 3D Studio.
// Does not remove the dedicated PromptForge page — "Open Full PromptForge" links to it.
export default function PromptForgePanel({ projectId, onApplyConcept, onOpenFull, defaultOpen = false }) {
  const [open, setOpen] = useState(defaultOpen);
  const [prompt, setPrompt] = useState('');
  const [concepts, setConcepts] = useState([]);
  const [generating, setGenerating] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!projectId) return;
    base44.entities.PromptConcept.filter({ projectId }).then(x => setConcepts(Array.isArray(x) ? x : [])).catch(() => setConcepts([]));
  }, [projectId]);

  const safeConcepts = Array.isArray(concepts) ? concepts : [];

  const generate = async () => {
    if (!projectId || !prompt.trim()) return;
    setGenerating(true); setError(null);
    try {
      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. User prompt: "${prompt}".`,
        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(', ')}. High detail decorative surface design, 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: 'generated'
        }))
      );
      setConcepts(Array.isArray(saved) ? saved : []);
    } catch (e) {
      setError(e.message || 'Concept generation failed. Please retry.');
    } finally {
      setGenerating(false);
    }
  };

  const apply = async (c) => {
    try { await onApplyConcept?.(c); }
    catch (e) { setError(e.message || 'Could not apply concept to cover.'); }
  };

  return (
    <div className="border-b border-white/[0.06] last:border-0">
      <button onClick={() => setOpen(o => !o)} className="flex w-full items-center gap-2 py-2.5 text-left">
        <ChevronDown size={13} className={`collapse-chevron text-slate-500 ${open ? 'open' : ''}`} />
        <Wand2 size={13} className="text-violet-300/80" />
        <span className="text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-300">PromptForge concepts</span>
        <span className="ml-auto mono text-[10px] text-slate-500">{safeConcepts.length}</span>
      </button>
      {open && (
        <div className="space-y-3 pb-3 fade-in">
          <textarea className="field min-h-16 resize-none text-xs" value={prompt} onChange={e => setPrompt(e.target.value)} placeholder="Describe a theme (e.g. heroic arachnid cover)…" />
          <div className="flex gap-1.5">
            <button disabled={!prompt.trim() || generating} onClick={generate} className="btn-violet flex-1 text-xs">
              {generating ? <><Loader2 size={14} className="animate-spin" />Generating…</> : <><Sparkles size={14} />Generate concepts</>}
            </button>
            {safeConcepts.length > 0 && <button disabled={generating} onClick={generate} className="btn-secondary text-xs" title="Generate more"><RefreshCw size={14} /></button>}
          </div>
          {error && <div className="warning-box flex items-center justify-between">{error}<button onClick={generate} className="ml-2 underline">Retry</button></div>}

          {safeConcepts.length === 0 && !generating && <p className="text-center text-[11px] text-slate-500">No concepts yet. Enter a prompt and generate.</p>}
          {generating && <div className="text-center text-[11px] text-violet-200"><Loader2 size={14} className="mx-auto mb-1 animate-spin" />Generating original concept directions…</div>}

          <div className="space-y-2">
            {safeConcepts.map(c => (
              <div key={c.id} className="rounded-lg border border-white/[0.06] bg-black/20 p-2 fade-in">
                <div className="flex gap-2">
                  <div className="h-14 w-14 shrink-0 overflow-hidden rounded border border-violet-400/20 bg-[#0e0b16]">
                    {c.previewImageUrl ? <ContentImage src={c.previewImageUrl} fittingType="fill" className="h-full w-full" /> : <div className="grid h-full place-items-center"><Sparkles size={16} className="text-violet-400/40" /></div>}
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-[12px] font-semibold text-slate-100">{c.title}</p>
                    <p className="line-clamp-2 text-[10px] leading-4 text-slate-400">{c.summary}</p>
                    <div className="mt-1 flex items-center gap-1">
                      <span className="sim-badge !px-1 !py-0 !text-[8px]">Original</span>
                      <span className="rounded border border-cyan-400/25 bg-cyan-400/10 px-1 text-[9px] text-cyan-200">{MODES[c.applicationModeSuggestion] || c.applicationModeSuggestion}</span>
                    </div>
                  </div>
                </div>
                <div className="mt-1.5 flex items-center gap-1">
                  {(c.colourPalette || []).map(col => <span key={col} className="h-3.5 w-3.5 rounded border border-white/20" style={{ background: col }} title={col} />)}
                </div>
                <button onClick={() => apply(c)} className="btn-violet mt-2 w-full text-[11px]">Apply to Cover<ArrowRight size={13} /></button>
              </div>
            ))}
          </div>

          <button onClick={onOpenFull} className="flex w-full items-center justify-center gap-1.5 rounded-lg border border-white/10 py-2 text-[11px] text-slate-300 hover:border-violet-400/40 hover:text-violet-200">
            <ExternalLink size={12} />Open Full PromptForge
          </button>
          <p className="flex items-center gap-1 text-[10px] text-slate-500"><ShieldCheck size={11} className="text-violet-300/70" />Original-inspired · copyright-safe</p>
        </div>
      )}
    </div>
  );
}