'use client';

import type { GenImage, GenSession, PackKind } from '@/lib/types';
import { PACK_LABELS, PACK_ORDER, VIDEO_TEMPLATES } from '@/lib/templates';

const PACK_DESCRIPTIONS: Record<PackKind, string> = {
  patent: '六面视图、45 度立体图和局部放大，用于外观专利素材整理。',
  production: '尺寸、材料、颜色、拆件和包装结构，用于工厂报价与打样沟通。',
  marketing: '白底商品图、场景图、细节图和社媒图，用于新品宣发。',
};

function manifestUrl(sessionId: string, kind: PackKind, version: string) {
  return `/api/export/${sessionId}_${kind}_${version}_manifest.json`;
}

export default function PackPanel({
  session,
  loadingKind,
  allLoading,
  characterLoading,
  videoLoading,
  onGenerate,
  onGenerateAll,
  onLockCharacter,
  onGenerateVideo,
}: {
  session: GenSession;
  loadingKind: PackKind | null;
  allLoading: boolean;
  characterLoading: boolean;
  videoLoading: boolean;
  onGenerate: (image: GenImage, kind: PackKind) => void;
  onGenerateAll: (image: GenImage) => void;
  onLockCharacter: (image: GenImage) => void;
  onGenerateVideo: (image: GenImage, prompt: string) => void;
}) {
  const selectedImages = session.images.filter(image => image.status === 'selected');
  const primaryImage = selectedImages[0] ?? null;
  const packs = session.packs ?? [];

  if (!primaryImage) {
    return (
      <section className="card p-5">
        <h2 className="text-sm font-semibold text-zinc-900">下一步素材包</h2>
        <p className="mt-1 text-xs text-zinc-500">
          先在上方九宫格选中一个主方案，再生成专利、生产和宣发模板包。
        </p>
      </section>
    );
  }

  return (
    <section className="card p-5 space-y-5">
      <div className="flex items-start justify-between gap-4">
        <div>
          <h2 className="text-sm font-semibold text-zinc-900">角色锁定与素材包</h2>
          <p className="mt-1 text-xs text-zinc-500">
            当前以第一个选中图作为主方案，可先锁定角色，再全量生成三类素材包。
          </p>
        </div>
        <div className="w-16 h-16 rounded-xl overflow-hidden ring-1 ring-zinc-200 bg-zinc-100 shrink-0">
          <img src={primaryImage.url} alt="selected source" className="w-full h-full object-cover" />
        </div>
      </div>

      <div className="flex flex-wrap gap-2">
        <button
          onClick={() => onLockCharacter(primaryImage)}
          disabled={characterLoading || !!loadingKind || allLoading}
          className="btn btn-outline text-xs"
        >
          {characterLoading ? '锁定中' : session.characterSpec ? '刷新角色设定' : '锁定角色设定'}
        </button>
        <button
          onClick={() => onGenerateAll(primaryImage)}
          disabled={allLoading || !!loadingKind || characterLoading}
          className="btn btn-primary text-xs"
        >
          {allLoading ? '全量生成中' : '一键生成完整三包'}
        </button>
      </div>

      {session.characterSpec && (
        <div className="rounded-2xl bg-zinc-50 border border-zinc-200/70 p-4">
          <div className="flex items-center justify-between gap-3">
            <div>
              <div className="text-xs font-semibold text-zinc-900">{session.characterSpec.name}</div>
              <div className="text-xs text-zinc-500 mt-1 line-clamp-2">{session.characterSpec.oneLiner}</div>
            </div>
            <span className="chip bg-white text-zinc-600 border border-zinc-200">CharacterSpec</span>
          </div>
          <div className="mt-3 grid grid-cols-2 gap-2 text-[11px] text-zinc-600">
            <div>形态：{session.characterSpec.speciesShape}</div>
            <div>比例：{session.characterSpec.bodyRatio}</div>
            <div>配色：{session.characterSpec.colorPalette.join('、')}</div>
            <div>材料：{session.characterSpec.materials.join('、')}</div>
          </div>
        </div>
      )}

      <div className="grid grid-cols-3 gap-3">
        {PACK_ORDER.map(kind => {
          const pack = packs.find(item => item.kind === kind && item.sourceImageId === primaryImage.id);
          const isLoading = loadingKind === kind;
          return (
            <div key={kind} className="rounded-2xl border border-zinc-200 p-4 bg-white space-y-3">
              <div>
                <div className="text-sm font-semibold text-zinc-900">{PACK_LABELS[kind]}</div>
                <p className="text-[11px] text-zinc-500 mt-1 leading-relaxed">{PACK_DESCRIPTIONS[kind]}</p>
              </div>
              <button
                onClick={() => onGenerate(primaryImage, kind)}
                disabled={!!loadingKind}
                className={pack ? 'btn btn-outline w-full text-xs' : 'btn btn-primary w-full text-xs'}
              >
                {isLoading ? '生成中' : pack ? '重新生成' : `生成${PACK_LABELS[kind]}`}
              </button>
              {pack && (
                <div className="space-y-2">
                  <div className="text-[11px] text-zinc-500">
                    已生成 <span className="font-semibold text-zinc-900">{pack.assets.length}</span> 张 · {pack.version}
                  </div>
                  <a
                    href={manifestUrl(session.id, kind, pack.version)}
                    className="text-[11px] font-medium text-zinc-900 underline underline-offset-2"
                  >
                    下载 manifest JSON
                  </a>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {packs.length > 0 && (
        <div className="space-y-4">
          {packs.map(pack => (
            <div key={pack.id} className="space-y-2">
              <div className="flex items-center justify-between">
                <h3 className="text-xs font-semibold text-zinc-900">{PACK_LABELS[pack.kind]} · {pack.assets.length} 张</h3>
                <code className="text-[10px] text-zinc-400">{pack.id}</code>
              </div>
              <div className="grid grid-cols-5 gap-2">
                {pack.assets.map(asset => (
                  <div key={asset.id} className="rounded-xl overflow-hidden border border-zinc-200 bg-zinc-50">
                    <div className="aspect-square bg-zinc-100">
                      <img src={asset.url} alt={asset.title} className="w-full h-full object-cover" />
                    </div>
                    <div className="p-2">
                      <div className="text-[11px] font-medium text-zinc-800 truncate">{asset.title}</div>
                      <div className="text-[10px] text-zinc-400 truncate">{asset.view}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="rounded-2xl border border-zinc-200 p-4 bg-white space-y-3">
        <div>
          <div className="text-sm font-semibold text-zinc-900">Seedance 视频</div>
          <p className="text-[11px] text-zinc-500 mt-1">
            视频固定走 Seedance。这里先用当前主方案生成标准宣发/展示短片任务。
          </p>
        </div>
        <div className="grid grid-cols-4 gap-2">
          {VIDEO_TEMPLATES.map(template => (
            <button
              key={template.id}
              onClick={() => onGenerateVideo(primaryImage, template.promptTemplate)}
              disabled={videoLoading}
              className="btn btn-outline text-[11px] px-2 py-2"
              title={template.description}
            >
              {videoLoading ? '提交中' : template.title}
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}
