'use client';

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

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

const PACK_ORDER: PackKind[] = ['patent', 'production', 'marketing'];

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

export default function PackPanel({
  session,
  loadingKind,
  onGenerate,
}: {
  session: GenSession;
  loadingKind: PackKind | null;
  onGenerate: (image: GenImage, kind: PackKind) => 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">
            当前以第一个选中图作为主方案，生成结果会写回会话并生成 manifest。
          </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>

      {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>
      )}
    </section>
  );
}
