'use client';

import { useCallback, useEffect, useState } from 'react';
import PromptPanel from '@/components/PromptPanel';
import ResultGrid from '@/components/ResultGrid';
import Sidebar from '@/components/Sidebar';
import PackPanel from '@/components/PackPanel';
import type { GenImage, GenSession, GeneratePackResponse, GenerateResponse, PackKind } from '@/lib/types';

export default function Home() {
  const [sessions, setSessions] = useState<GenSession[]>([]);
  const [current, setCurrent] = useState<GenSession | null>(null);
  const [loading, setLoading] = useState(false);
  const [loadingKind, setLoadingKind] = useState<PackKind | null>(null);
  const [provider, setProvider] = useState<string>('?');
  const [sidebarOpen, setSidebarOpen] = useState(true);

  const refreshSessions = useCallback(async () => {
    const r = await fetch('/api/sessions');
    const d = await r.json();
    setSessions(d.sessions);
    return d.sessions as GenSession[];
  }, []);

  useEffect(() => { refreshSessions(); }, [refreshSessions]);

  async function handleGenerate(opts: { prompt: string; refImages: string[]; count: number; style?: string }) {
    setLoading(true);
    try {
      const r = await fetch('/api/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(opts),
      });
      if (!r.ok) {
        alert('生成失败：' + (await r.text()));
        return;
      }
      const d: GenerateResponse = await r.json();
      setProvider(d.provider);
      const all = await refreshSessions();
      const s = all.find(x => x.id === d.sessionId) ?? null;
      setCurrent(s);
    } finally {
      setLoading(false);
    }
  }

  async function handleAction(imageId: string, action: 'select' | 'reject' | 'reset') {
    if (!current) return;
    const r = await fetch('/api/select', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ sessionId: current.id, imageId, action }),
    });
    if (!r.ok) return;
    const d: { image: GenImage } = await r.json();
    setCurrent(prev => prev ? {
      ...prev,
      images: prev.images.map(i => i.id === imageId ? d.image : i),
    } : prev);
    refreshSessions();
  }

  async function handleGeneratePack(image: GenImage, kind: PackKind) {
    if (!current || loadingKind) return;
    setLoadingKind(kind);
    try {
      const r = await fetch('/api/packs/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sessionId: current.id, imageId: image.id, kind }),
      });
      if (!r.ok) {
        alert('素材包生成失败：' + (await r.text()));
        return;
      }
      const d: GeneratePackResponse = await r.json();
      setProvider(d.provider);
      const all = await refreshSessions();
      const updated = all.find(x => x.id === current.id) ?? null;
      setCurrent(updated);
    } finally {
      setLoadingKind(null);
    }
  }

  return (
    <div className="flex h-screen bg-[#FAFAFA]">
      <Sidebar
        open={sidebarOpen}
        onToggle={() => setSidebarOpen(v => !v)}
        sessions={sessions}
        currentId={current?.id ?? null}
        onPick={id => setCurrent(sessions.find(s => s.id === id) ?? null)}
        onNew={() => setCurrent(null)}
      />
      <main className="flex-1 overflow-y-auto">
        <div className="mx-auto max-w-[1180px] px-10 py-10">
          <header className="flex items-start justify-between mb-10">
            <div>
              <h1 className="text-[26px] font-semibold tracking-tight text-zinc-900 leading-tight">
                AI 玩具专利生成工作流
              </h1>
              <p className="text-sm text-zinc-500 mt-1.5">
                批量出意向 → 快筛 → 多角度尺寸 → 喂专利
              </p>
            </div>
            <div className="flex items-center gap-2 pt-1">
              <span className={provider === 'poe' ? 'chip chip-live' : 'chip chip-mock'}>
                <span className={`w-1.5 h-1.5 rounded-full ${provider === 'poe' ? 'bg-emerald-500' : 'bg-amber-500'}`} />
                {provider === 'poe' ? 'Poe · 实时生图' : provider === 'mock' ? 'Mock · 占位图' : provider}
              </span>
            </div>
          </header>

          <div className="space-y-8">
            <PromptPanel onGenerate={handleGenerate} loading={loading} />
            {current && (
              <section className="space-y-4">
                <div className="flex items-end justify-between">
                  <div>
                    <h2 className="text-sm font-medium text-zinc-900">本次生成</h2>
                    <p className="text-xs text-zinc-500 mt-0.5">
                      {new Date(current.createdAt).toLocaleString('zh-CN')}
                    </p>
                  </div>
                  <code className="text-[11px] text-zinc-400 font-mono">{current.id}</code>
                </div>
                <ResultGrid images={current.images} onAction={handleAction} />
                <PackPanel session={current} loadingKind={loadingKind} onGenerate={handleGeneratePack} />
              </section>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}
