import type { ReactElement } from "react";
import { useEffect, useState } from "react";

import { shortToken } from "../../utils";

interface DraftsListProps {
  onPick(draft: string): void;
  id?: string;
}

interface DraftEntry {
  text: string;
  ts: string;
}

const DRAFTS_KEY = "hwlab.workbench.recentDrafts.v1";
const DRAFTS_LIMIT = 8;

export function DraftsList({ onPick, id }: DraftsListProps): ReactElement | null {
  const [drafts, setDrafts] = useState<DraftEntry[]>([]);

  useEffect(() => {
    try {
      const raw = window.localStorage.getItem(DRAFTS_KEY);
      if (!raw) {
        setDrafts([]);
        return;
      }
      const parsed: unknown = JSON.parse(raw);
      if (Array.isArray(parsed)) {
        const next = parsed.filter((item): item is DraftEntry => {
          return Boolean(item) && typeof item === "object" && typeof (item as { text?: unknown }).text === "string" && typeof (item as { ts?: unknown }).ts === "string";
        }).slice(0, DRAFTS_LIMIT);
        setDrafts(next);
      }
    } catch {
      setDrafts([]);
    }
  }, []);

  if (drafts.length === 0) return null;
  return (
    <section className="drafts-list" id={id} data-drafts-list aria-label="最近发送过的草稿">
      <header className="drafts-list-head">
        <p className="eyebrow">最近输入</p>
        <button type="button" className="command-button secondary" onClick={() => { try { window.localStorage.removeItem(DRAFTS_KEY); } catch { /* ignore */ } setDrafts([]); }}>清空</button>
      </header>
      <ul className="drafts-list-items" role="list">
        {drafts.map((draft, index) => (
          <li key={`${draft.ts}-${index}`} role="listitem">
            <button type="button" className="draft-chip mono" title={`${draft.ts.slice(0, 19)} · ${shortToken(draft.text, 80)}`} onClick={() => onPick(draft.text)}>
              {shortToken(draft.text, 32)}
            </button>
          </li>
        ))}
      </ul>
    </section>
  );
}

export function recordDraft(text: string): void {
  if (typeof window === "undefined") return;
  const trimmed = text.trim();
  if (!trimmed) return;
  try {
    const raw = window.localStorage.getItem(DRAFTS_KEY);
    const parsed: unknown = raw ? JSON.parse(raw) : [];
    const existing: DraftEntry[] = Array.isArray(parsed) ? parsed.filter((item): item is DraftEntry => Boolean(item) && typeof (item as { text?: unknown }).text === "string") : [];
    const next = [{ text: trimmed, ts: new Date().toISOString() }, ...existing.filter((item) => item.text !== trimmed)].slice(0, DRAFTS_LIMIT);
    window.localStorage.setItem(DRAFTS_KEY, JSON.stringify(next));
  } catch { /* ignore */ }
}
