'use client';

import { useRef, useState } from 'react';
import type { GenSession, ProjectInputMode, UploadedImage } from '@/lib/types';

const STYLE_OPTIONS = [
  { id: 'none', label: '无', value: '', preview: '/style-previews/none.png' },
  { id: 'plush', label: '毛绒玩偶', value: '毛绒玩偶', preview: '/style-previews/plush.png' },
  { id: 'mecha', label: '机甲风', value: '机甲风', preview: '/style-previews/mecha.png' },
  { id: 'kawaii', label: '可爱萌系', value: '可爱萌系', preview: '/style-previews/kawaii.png' },
  { id: 'blueprint', label: '专利蓝图', value: '专利蓝图', preview: '/style-previews/blueprint.png' },
  { id: 'cyber', label: '赛博朋克', value: '赛博朋克', preview: '/style-previews/cyber.png' },
  { id: 'minimal', label: '极简', value: '极简', preview: '/style-previews/minimal.png' },
];

type UploadProjectFile = {
  file: File;
  role: 'reference' | 'subject';
};

export type PromptPanelProps = {
  session: GenSession | null;
  onGenerate: (opts: { prompt: string; refImages: string[]; count: number; style?: string }) => void;
  onUploadProject: (opts: {
    mode: 'remix' | 'replicate';
    files: UploadProjectFile[];
    prompt?: string;
    styleId?: string;
    count?: number;
  }) => void;
  loading: boolean;
  uploadLoading: boolean;
};

type Tab = 'idea' | 'remix' | 'replicate';

function filePreview(file: File | null) {
  return file ? URL.createObjectURL(file) : '';
}

function tabFromMode(mode?: ProjectInputMode): Tab {
  if (mode === 'remix') return 'remix';
  if (mode === 'replicate' || mode === 'extend') return 'replicate';
  return 'idea';
}

function modeLabel(mode?: ProjectInputMode) {
  if (mode === 'remix') return '二创';
  if (mode === 'replicate') return '复刻';
  if (mode === 'extend') return '复制';
  return '想法';
}

function imageSourcesForSession(session: GenSession) {
  const uploaded = session.uploadedImages?.map(image => image.url) ?? [];
  return uploaded.length ? uploaded : session.refImages;
}

function uploadedLabel(image: UploadedImage) {
  if (image.role === 'subject') return '主体图';
  if (image.role === 'reference') return '参考图';
  return image.accessoryName || image.role;
}

function LockedSessionInput({ session }: { session: GenSession }) {
  const images = imageSourcesForSession(session);
  return (
    <div className="rounded-[8px] border border-[#e6f578]/18 bg-[#e6f578]/[0.035] p-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <div className="text-[10px] uppercase tracking-[0.18em] text-[#e6f578]/65">Locked session input</div>
          <div className="mt-1 text-sm font-semibold text-white">本会话入口已锁定 · {modeLabel(session.inputMode)}</div>
        </div>
        <div className="rounded-full border border-white/10 bg-black/35 px-3 py-1 text-[11px] text-white/45">
          要换内容，请从左侧新建会话
        </div>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-[minmax(0,1fr)_220px]">
        <div className="rounded-[8px] border border-white/10 bg-black/28 p-3">
          <div className="mb-1.5 text-[10px] uppercase tracking-[0.14em] text-white/38">Prompt</div>
          <p className="text-[13px] leading-relaxed text-white/76">{session.prompt || '未填写'}</p>
        </div>
        <div className="grid grid-cols-2 gap-2 text-[11px] text-white/54">
          <div className="rounded-[8px] border border-white/10 bg-black/24 p-3">
            <div className="text-white/32">数量</div>
            <div className="mt-1 font-semibold text-white">{session.count} 张</div>
          </div>
          <div className="rounded-[8px] border border-white/10 bg-black/24 p-3">
            <div className="text-white/32">创建时间</div>
            <div className="mt-1 font-semibold text-white">
              {new Date(session.createdAt).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })}
            </div>
          </div>
        </div>
      </div>

      <div className="mt-3">
        <div className="mb-2 text-[10px] uppercase tracking-[0.14em] text-white/38">Reference</div>
        {images.length ? (
          <div className="flex flex-wrap gap-2.5">
            {images.slice(0, 6).map((url, index) => {
              const uploaded = session.uploadedImages?.find(image => image.url === url);
              return (
                <div key={`${url}-${index}`} className="relative h-20 w-20 overflow-hidden rounded-[8px] ring-1 ring-white/[0.1]">
                  <img src={url} alt={uploaded ? uploadedLabel(uploaded) : `参考图 ${index + 1}`} className="h-full w-full object-cover" />
                  <div className="absolute bottom-1 left-1 rounded bg-black/70 px-1.5 py-0.5 text-[9px] text-white/70">
                    {uploaded ? uploadedLabel(uploaded) : `参考 ${index + 1}`}
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="rounded-[8px] border border-dashed border-white/10 bg-black/18 px-3 py-4 text-xs text-white/34">
            本会话没有参考图。
          </div>
        )}
      </div>
    </div>
  );
}

export default function PromptPanel({ session, onGenerate, onUploadProject, loading, uploadLoading }: PromptPanelProps) {
  const [tab, setTab] = useState<Tab>('idea');
  const [prompt, setPrompt] = useState('AI 毛绒陪伴玩具，机甲头盔，胸前挂 M logo，橙白配色，圆胖体型');
  const [refs, setRefs] = useState<string[]>([]);
  const [count, setCount] = useState(8);
  const [style, setStyle] = useState<string>('');
  const [remixFiles, setRemixFiles] = useState<File[]>([]);
  const [remixPrompt, setRemixPrompt] = useState('保留原角色轮廓和五官，改成原创毛绒玩具设计');
  const [replicateFile, setReplicateFile] = useState<File | null>(null);
  const [replicateHint, setReplicateHint] = useState('');
  const fileInput = useRef<HTMLInputElement>(null);
  const remixInput = useRef<HTMLInputElement>(null);
  const replicateInput = useRef<HTMLInputElement>(null);

  function handleFiles(files: FileList | null) {
    if (!files) return;
    Array.from(files).slice(0, 4 - refs.length).forEach(f => {
      const r = new FileReader();
      r.onload = () => setRefs(prev => [...prev, r.result as string]);
      r.readAsDataURL(f);
    });
  }

  function submitIdea() {
    if (!prompt.trim() || loading) return;
    onGenerate({ prompt: prompt.trim(), refImages: refs, count, style: style || undefined });
  }

  function submitRemix() {
    if (!remixFiles.length || uploadLoading) return;
    onUploadProject({
      mode: 'remix',
      files: remixFiles.map(file => ({ file, role: 'reference' })),
      prompt: remixPrompt.trim(),
      styleId: style || undefined,
      count,
    });
  }

  function submitReplicate() {
    if (!replicateFile || uploadLoading) return;
    onUploadProject({
      mode: 'replicate',
      files: [{ file: replicateFile, role: 'subject' }],
      prompt: replicateHint.trim(),
      count: 1,
    });
  }

  const busy = loading || uploadLoading;
  const replicatePreview = filePreview(replicateFile);
  const locked = Boolean(session);
  const activeTab = session ? tabFromMode(session.inputMode) : tab;
  const canChooseStyle = !session && (activeTab === 'idea' || activeTab === 'remix');

  return (
    <section className="card overflow-hidden">
      <div className="grid lg:grid-cols-[268px_minmax(0,1fr)]">
        <aside className="border-b border-[#8cb478]/12 bg-black/16 p-5 lg:border-b-0 lg:border-r">
          <div className="space-y-1.5">
            <span className="section-eyebrow">Step · 01 · Input</span>
            <div className="text-[10px] text-white/34">入口、风格和数量都在这里选</div>
          </div>

          <div className="mt-5 space-y-2">
            <div className="text-[10px] uppercase tracking-[0.14em] text-white/38">模式</div>
            <div className="grid gap-2">
              {[
                ['idea', '想法', 'Prompt 批量出意向'],
                ['remix', '二创', '上传图做风格变体'],
                ['replicate', '复刻', '上传主体直接锁定'],
              ].map(([id, label, desc]) => (
                <button
                  key={id}
                  onClick={() => { if (!locked) setTab(id as Tab); }}
                  disabled={locked}
                  title={locked ? '本会话入口已锁定；从左侧新建会话后可重新选择' : undefined}
                  className={`rounded-[8px] border p-3 text-left transition-all ${
                    activeTab === id
                      ? 'border-[#e6f578]/55 bg-[#e6f578]/14 text-white shadow-[0_12px_38px_-22px_rgba(230,245,120,0.65)]'
                      : 'border-[#8cb478]/14 bg-black/20 text-white/58 hover:border-[#e6f578]/28 hover:text-white/82'
                  } ${locked ? 'cursor-not-allowed opacity-70' : ''}`}
                >
                  <span className="block text-sm font-semibold">{label}</span>
                  <span className="mt-1 block text-[10px] leading-relaxed text-white/38">{desc}</span>
                </button>
              ))}
            </div>
          </div>

          {canChooseStyle && (
            <div className="mt-6 space-y-2">
              <div className="flex items-center justify-between">
                <div className="text-[10px] uppercase tracking-[0.14em] text-white/38">风格示意</div>
                <div className="text-[10px] text-[#e6f578]/55">GPT 预览</div>
              </div>
              <div className="grid grid-cols-2 gap-2">
                {STYLE_OPTIONS.map(option => {
                  const active = style === option.value;
                  return (
                    <button
                      key={option.id}
                      onClick={() => setStyle(option.value)}
                      className={`group overflow-hidden rounded-[8px] border text-left transition-all ${
                        active
                          ? 'border-[#e6f578]/70 bg-[#e6f578]/14 shadow-[0_14px_34px_-22px_rgba(230,245,120,0.9)]'
                          : 'border-[#8cb478]/16 bg-black/24 hover:border-[#e6f578]/38'
                      }`}
                    >
                      <img src={option.preview} alt={option.label} className="h-16 w-full bg-[#101a0d] object-cover transition-transform duration-300 group-hover:scale-[1.04]" />
                      <span className={`block px-2 py-1.5 text-[11px] font-medium ${active ? 'text-[#f2f6a8]' : 'text-white/72'}`}>
                        {option.label}
                      </span>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {canChooseStyle && (
            <div className="mt-6 space-y-2">
              <div className="text-[10px] uppercase tracking-[0.14em] text-white/38">数量</div>
              <div className="grid grid-cols-3 gap-2">
                {[4, 8, 12].map(n => (
                  <button
                    key={n}
                    onClick={() => setCount(n)}
                    className={`rounded-[8px] border px-2 py-2 text-xs transition-all ${
                      count === n
                        ? 'border-[#e6f578]/70 bg-[#e6f578] text-[#081006]'
                        : 'border-[#8cb478]/16 bg-black/24 text-white/55 hover:border-[#e6f578]/38 hover:text-white'
                    }`}
                  >{n} 张</button>
                ))}
              </div>
            </div>
          )}
        </aside>

        <div className="space-y-6 p-7">
          {session ? (
            <LockedSessionInput session={session} />
          ) : activeTab === 'idea' && (
            <>
          <div>
            <label className="block text-[11px] font-medium text-white/55 uppercase tracking-[0.14em] mb-2.5">
              Prompt
            </label>
            <textarea
              value={prompt}
              onChange={e => setPrompt(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) submitIdea(); }}
              rows={3}
              placeholder="描述要生成的玩具意向…"
              className="field text-[15px] leading-relaxed"
            />
            <p className="mt-2 text-[11px] text-white/35 flex items-center gap-1.5">
              按 <kbd className="kbd">⌘</kbd><kbd className="kbd">↵</kbd> 提交
            </p>
          </div>

          <div>
            <label className="block text-[11px] font-medium text-white/55 uppercase tracking-[0.14em] mb-2.5">
              参考图 <span className="text-white/35 normal-case tracking-normal">· 可选，最多 4 张</span>
            </label>
            <div className="flex flex-wrap gap-2.5">
              {refs.map((r, i) => (
                <div key={i} className="relative w-20 h-20 rounded-[8px] overflow-hidden ring-1 ring-white/[0.1] group">
                  <img src={r} alt="ref" className="w-full h-full object-cover" />
                  <button
                    onClick={() => setRefs(prev => prev.filter((_, j) => j !== i))}
                    className="absolute top-1 right-1 w-5 h-5 rounded-full bg-black/80 text-white text-[10px] opacity-0 group-hover:opacity-100 transition-opacity shadow-md"
                  >x</button>
                </div>
              ))}
              {refs.length < 4 && (
                <button
                  onClick={() => fileInput.current?.click()}
                  className="w-20 h-20 rounded-[8px] border-2 border-dashed border-[#8cb478]/25 hover:border-[#e6f578]/55 hover:bg-[#e6f578]/[0.04] text-white/30 hover:text-[#e6f578] text-2xl transition-all flex items-center justify-center"
                >+</button>
              )}
              <input
                ref={fileInput}
                type="file"
                accept="image/*"
                multiple
                hidden
                onChange={e => handleFiles(e.target.files)}
              />
            </div>
          </div>
            </>
          )}

          {!session && activeTab === 'remix' && (
            <div className="space-y-5">
          <div>
            <label className="block text-[11px] font-medium text-white/55 uppercase tracking-[0.14em] mb-2.5">
              参考图 <span className="text-white/35 normal-case tracking-normal">· 1-4 张</span>
            </label>
            <div className="flex flex-wrap gap-2.5">
              {remixFiles.map((file, i) => (
                <div key={`${file.name}-${i}`} className="relative w-20 h-20 rounded-[8px] overflow-hidden ring-1 ring-white/[0.1] group">
                  <img src={URL.createObjectURL(file)} alt={file.name} className="w-full h-full object-cover" />
                  <button
                    onClick={() => setRemixFiles(prev => prev.filter((_, j) => j !== i))}
                    className="absolute top-1 right-1 w-5 h-5 rounded-full bg-black/80 text-white text-[10px] opacity-0 group-hover:opacity-100 transition-opacity shadow-md"
                  >x</button>
                </div>
              ))}
              {remixFiles.length < 4 && (
                <button
                  onClick={() => remixInput.current?.click()}
                  className="w-20 h-20 rounded-[8px] border-2 border-dashed border-[#8cb478]/25 hover:border-[#e6f578]/55 hover:bg-[#e6f578]/[0.04] text-white/30 hover:text-[#e6f578] text-2xl transition-all flex items-center justify-center"
                >+</button>
              )}
              <input
                ref={remixInput}
                type="file"
                accept="image/*"
                multiple
                hidden
                onChange={e => {
                  const files = Array.from(e.target.files ?? []).slice(0, 4 - remixFiles.length);
                  setRemixFiles(prev => [...prev, ...files]);
                }}
              />
            </div>
          </div>
          <div>
            <label className="block text-[11px] font-medium text-white/55 uppercase tracking-[0.14em] mb-2.5">
              变化方向
            </label>
            <textarea
              value={remixPrompt}
              onChange={e => setRemixPrompt(e.target.value)}
              rows={3}
              className="field text-[15px] leading-relaxed"
            />
          </div>
            </div>
          )}

          {!session && activeTab === 'replicate' && (
            <div className="grid md:grid-cols-[220px_1fr] gap-5 items-start">
          <div>
            <label className="block text-[11px] font-medium text-white/55 uppercase tracking-[0.14em] mb-2.5">
              主体图
            </label>
            <button
              onClick={() => replicateInput.current?.click()}
              className="relative w-full aspect-square rounded-[8px] border-2 border-dashed border-[#8cb478]/25 hover:border-[#e6f578]/55 bg-[#e6f578]/[0.025] overflow-hidden transition-all flex items-center justify-center text-white/35"
            >
              {replicateFile ? (
                <img src={replicatePreview} alt={replicateFile.name} className="w-full h-full object-cover" />
              ) : (
                <span className="text-sm">上传</span>
              )}
            </button>
            <input
              ref={replicateInput}
              type="file"
              accept="image/*"
              hidden
              onChange={e => setReplicateFile(e.target.files?.[0] ?? null)}
            />
          </div>
          <div className="space-y-4">
            <div>
              <label className="block text-[11px] font-medium text-white/55 uppercase tracking-[0.14em] mb-2.5">
                名称 / 提示
              </label>
              <textarea
                value={replicateHint}
                onChange={e => setReplicateHint(e.target.value)}
                rows={3}
                placeholder="可选：IP 名称、材质、用途或你想保留的重点"
                className="field text-[15px] leading-relaxed"
              />
            </div>
            <div className="rounded-[8px] bg-amber-500/10 ring-1 ring-amber-400/20 px-3 py-2 text-[11px] leading-relaxed text-amber-100/75">
              上传图必须为你拥有或有合法授权使用的素材。请勿上传迪士尼、三丽鸥、泡泡玛特等已注册 IP 图像；用于专利申请前需自行确认不与他人在先权利冲突。
            </div>
          </div>
            </div>
          )}

          {!session && (
            <div className="flex justify-end gap-4 pt-2">
              <button
                onClick={activeTab === 'idea' ? submitIdea : activeTab === 'remix' ? submitRemix : submitReplicate}
                disabled={
                  busy
                  || (activeTab === 'idea' && !prompt.trim())
                  || (activeTab === 'remix' && remixFiles.length === 0)
                  || (activeTab === 'replicate' && !replicateFile)
                }
                className="btn btn-primary px-5 py-2.5 disabled:opacity-40 disabled:cursor-not-allowed"
              >
                {busy ? (
                  <>
                    <svg width="14" height="14" viewBox="0 0 24 24" className="animate-spin" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M12 2a10 10 0 0 1 10 10" strokeLinecap="round" />
                    </svg>
                    处理中
                  </>
                ) : (
                  <>
                    {activeTab === 'idea' ? '批量生成' : activeTab === 'remix' ? '生成变体' : '复刻并锁定'}
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                      <path d="M5 12h14M13 5l7 7-7 7" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </>
                )}
              </button>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
