<script lang="ts">
  // 자동 분류 제안 승인 UI (Section 2)
  //
  // 역할: documents.ai_suggestion 에 축적된 제안을 카드 리스트로 노출하고
  //       사용자가 승인/반려 할 수 있게 한다. 자료실 /library 페이지 상단에 렌더.
  //
  // API 계약 (§1 이 제공):
  //   GET    /api/documents?has_suggestion=true&proposed_category=<cat>
  //   POST   /api/documents/{id}/accept-suggestion  body: { expected_source_updated_at }
  //   DELETE /api/documents/{id}/suggestion
  //
  // 409 Conflict: 다른 탭에서 문서가 수정되었거나 제안 payload 가 새 classify 결과로
  // 덮인 경우. 토스트 + 해당 카드 refresh (성공적인 카드는 사라짐).
  import { onMount } from 'svelte';
  import { api } from '$lib/api';
  import { addToast } from '$lib/stores/toast';
  import { Check, X, Loader2, RefreshCcw, FileText } from 'lucide-svelte';
  import Button from '$lib/components/ui/Button.svelte';

  interface Suggestion {
    proposed_category: string;
    proposed_path: string | null;
    proposed_doctype: string | null;
    confidence: number | null;
    source_updated_at: string;
    reason: string | null;
  }

  interface SuggestionDoc {
    id: number;
    title: string | null;
    category: string | null;
    file_format?: string | null;
    ai_suggestion: Suggestion;
    updated_at: string;
  }

  interface Props {
    // 대기 카테고리 (현재는 'library' 만 사용)
    proposedCategory?: string;
    // 부모가 승인/반려 후 갱신하고 싶을 때 호출되는 콜백 (카운트 배지 갱신 용)
    onChange?: () => void;
  }

  let { proposedCategory = 'library', onChange }: Props = $props();

  let docs = $state<SuggestionDoc[]>([]);
  let total = $state(0);
  let loading = $state(true);
  let bulkRunning = $state(false);
  // 행 단위 작업 상태 (id → 'accept' | 'reject')
  let rowBusy = $state<Record<number, 'accept' | 'reject' | null>>({});
  let selected = $state<Set<number>>(new Set());

  async function load() {
    loading = true;
    try {
      const params = new URLSearchParams({
        has_suggestion: 'true',
        proposed_category: proposedCategory,
        page: '1',
        page_size: '50',
      });
      const res = await api<{ items: SuggestionDoc[]; total: number }>(
        `/documents?${params}`,
      );
      docs = res.items ?? [];
      total = res.total ?? docs.length;
      selected = new Set();
    } catch (err) {
      // 엔드포인트 미도착(=§1 미머지) 상태에서도 /library 페이지 자체는 살아 있어야 하므로
      // 실패는 조용히 빈 상태로 전환한다.
      docs = [];
      total = 0;
      // 404/422 외 에러는 사용자에게 알린다.
      const status = (err as { status?: number }).status;
      if (status && status !== 404 && status !== 422) {
        addToast('error', '제안 목록 로딩 실패');
      }
    } finally {
      loading = false;
    }
  }

  async function accept(doc: SuggestionDoc) {
    rowBusy[doc.id] = 'accept';
    try {
      await api(`/documents/${doc.id}/accept-suggestion`, {
        method: 'POST',
        body: JSON.stringify({
          expected_source_updated_at: doc.ai_suggestion.source_updated_at,
        }),
      });
      addToast('success', `${doc.title ?? '제목 없음'} → 자료실 이동`);
      // 해당 카드 제거 (서버가 200 + ai_suggestion=NULL)
      docs = docs.filter((d) => d.id !== doc.id);
      total = Math.max(0, total - 1);
      selected.delete(doc.id);
      selected = new Set(selected);
      onChange?.();
    } catch (err) {
      const status = (err as { status?: number }).status;
      if (status === 409) {
        addToast(
          'warning',
          '문서가 다른 곳에서 수정돼 제안이 만료되었습니다. 목록을 새로고침합니다.',
        );
        await load();
      } else {
        addToast('error', '승인 실패');
      }
    } finally {
      rowBusy[doc.id] = null;
    }
  }

  async function reject(doc: SuggestionDoc) {
    rowBusy[doc.id] = 'reject';
    try {
      await api(`/documents/${doc.id}/suggestion`, { method: 'DELETE' });
      addToast('info', '제안 반려');
      docs = docs.filter((d) => d.id !== doc.id);
      total = Math.max(0, total - 1);
      selected.delete(doc.id);
      selected = new Set(selected);
      onChange?.();
    } catch (err) {
      addToast('error', '반려 실패');
    } finally {
      rowBusy[doc.id] = null;
    }
  }

  async function acceptSelected() {
    if (selected.size === 0 || bulkRunning) return;
    bulkRunning = true;
    const targets = docs.filter((d) => selected.has(d.id));
    let ok = 0;
    let staleOrFail = 0;
    for (const doc of targets) {
      try {
        await api(`/documents/${doc.id}/accept-suggestion`, {
          method: 'POST',
          body: JSON.stringify({
            expected_source_updated_at: doc.ai_suggestion.source_updated_at,
          }),
        });
        ok += 1;
      } catch {
        staleOrFail += 1;
      }
    }
    bulkRunning = false;
    if (ok > 0) {
      addToast('success', `${ok}건 자료실로 이동`);
    }
    if (staleOrFail > 0) {
      addToast('warning', `${staleOrFail}건은 실패/만료 — 목록 새로고침`);
    }
    onChange?.();
    await load();
  }

  function toggleSelect(id: number) {
    const next = new Set(selected);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    selected = next;
  }

  function toggleAll() {
    if (selected.size === docs.length) {
      selected = new Set();
    } else {
      selected = new Set(docs.map((d) => d.id));
    }
  }

  function formatConfidence(c: number | null | undefined): string {
    if (c === null || c === undefined) return '—';
    return `${Math.round(c * 100)}%`;
  }

  function proposedPathLabel(doc: SuggestionDoc): string {
    const s = doc.ai_suggestion;
    if (s.proposed_path) return s.proposed_path;
    if (s.proposed_doctype) return `@${s.proposed_category}/${s.proposed_doctype}`;
    return `@${s.proposed_category}`;
  }

  onMount(() => {
    load();
  });
</script>

<section
  class="border border-default rounded-lg bg-surface-muted/30 overflow-hidden"
  aria-label="자동 분류 제안 승인"
>
  <header class="flex items-center justify-between gap-3 px-4 py-3 border-b border-default bg-surface">
    <div class="flex items-center gap-2">
      <FileText size={16} class="text-dim" />
      <h2 class="text-sm font-semibold text-text">자동 분류 제안</h2>
      {#if !loading}
        <span
          class="text-xs text-dim bg-surface-muted px-1.5 py-0.5 rounded"
          data-testid="suggestion-total"
        >
          {total}건
        </span>
      {/if}
    </div>
    <div class="flex items-center gap-2">
      {#if docs.length > 1}
        <button
          type="button"
          onclick={toggleAll}
          class="text-xs text-dim hover:text-text"
        >
          {selected.size === docs.length ? '전체 해제' : '전체 선택'}
        </button>
      {/if}
      {#if selected.size > 0}
        <Button
          size="sm"
          variant="primary"
          loading={bulkRunning}
          onclick={acceptSelected}
          icon={Check}
        >
          선택 {selected.size}건 승인
        </Button>
      {/if}
      <button
        type="button"
        class="p-1.5 text-dim hover:text-text rounded hover:bg-surface-hover"
        onclick={load}
        aria-label="새로고침"
        disabled={loading}
      >
        <RefreshCcw size={14} class={loading ? 'animate-spin' : ''} />
      </button>
    </div>
  </header>

  {#if loading}
    <div class="px-4 py-6 flex items-center gap-2 text-dim text-sm">
      <Loader2 size={14} class="animate-spin" />
      제안 불러오는 중…
    </div>
  {:else if docs.length === 0}
    <div class="px-4 py-5 text-sm text-dim">
      대기 중인 제안이 없습니다. 발주서·세금계산서 등이 분류되면 여기 쌓입니다.
    </div>
  {:else}
    <ul class="divide-y divide-default/40">
      {#each docs as doc (doc.id)}
        {@const busy = rowBusy[doc.id]}
        {@const isSel = selected.has(doc.id)}
        <li class="flex items-start gap-3 px-4 py-3 hover:bg-surface/60">
          <label class="mt-0.5 flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={isSel}
              onchange={() => toggleSelect(doc.id)}
              class="h-4 w-4 rounded border-default"
              aria-label="선택"
            />
          </label>
          <a
            href={`/documents/${doc.id}`}
            class="flex-1 min-w-0 space-y-1"
          >
            <div class="flex items-baseline gap-2">
              <span class="text-sm font-medium text-text truncate">
                {doc.title ?? `문서 ${doc.id}`}
              </span>
              {#if doc.category}
                <span class="text-[10px] uppercase tracking-wide text-dim">
                  현재: {doc.category}
                </span>
              {/if}
            </div>
            <div class="flex items-center gap-2 text-xs text-dim">
              <span class="font-mono text-accent">{proposedPathLabel(doc)}</span>
              {#if doc.ai_suggestion.proposed_doctype}
                <span class="px-1.5 py-0.5 rounded bg-surface-muted">
                  {doc.ai_suggestion.proposed_doctype}
                </span>
              {/if}
              <span>신뢰도 {formatConfidence(doc.ai_suggestion.confidence)}</span>
              {#if doc.ai_suggestion.reason}
                <span class="truncate">· {doc.ai_suggestion.reason}</span>
              {/if}
            </div>
          </a>
          <div class="flex items-center gap-1.5 shrink-0">
            <Button
              size="sm"
              variant="secondary"
              icon={X}
              loading={busy === 'reject'}
              disabled={busy === 'accept'}
              onclick={() => reject(doc)}
            >
              반려
            </Button>
            <Button
              size="sm"
              variant="primary"
              icon={Check}
              loading={busy === 'accept'}
              disabled={busy === 'reject'}
              onclick={() => accept(doc)}
            >
              승인
            </Button>
          </div>
        </li>
      {/each}
    </ul>
  {/if}
</section>
