import { useEffect, useMemo, useRef, useState } from "react";
import { api } from "../api/haixun";
import {
  extractMentionUsernames,
  parsePlaygroundProfileData,
  profileDisplayEntries,
  type ProfileLookupProfile
} from "../lib/mentionLookup";
import { Badge } from "./ui";

type LookupState = {
  status: "loading" | "ok" | "error";
  profile?: ProfileLookupProfile;
  message?: string;
};

type Props = {
  accountId: string;
  text: string;
  label?: string;
};

export function MentionProfileLookup({ accountId, text, label = "@ 提及查詢" }: Props) {
  const mentions = useMemo(() => extractMentionUsernames(text), [text]);
  const mentionsKey = mentions.join("|");
  const [lookupByUser, setLookupByUser] = useState<Record<string, LookupState>>({});
  const cacheRef = useRef<Record<string, LookupState>>({});
  const requestGenRef = useRef(0);

  useEffect(() => {
    cacheRef.current = lookupByUser;
  }, [lookupByUser]);

  useEffect(() => {
    if (!accountId || !mentionsKey) {
      setLookupByUser({});
      cacheRef.current = {};
      return;
    }

    const timer = window.setTimeout(() => {
      const gen = ++requestGenRef.current;
      const targets = mentionsKey.split("|");

      setLookupByUser((current) => {
        const next: Record<string, LookupState> = {};
        for (const username of targets) {
          const cached = current[username];
          next[username] =
            cached?.status === "ok" ? cached : { status: "loading" };
        }
        cacheRef.current = next;
        return next;
      });

      void (async () => {
        for (const username of targets) {
          if (cacheRef.current[username]?.status === "ok") continue;

          try {
            const result = await api.threadsPlayground(accountId, {
              action: "profile_lookup",
              username
            });
            if (gen !== requestGenRef.current) return;

            if (!result.ok) {
              setLookupByUser((current) => {
                const next = {
                  ...current,
                  [username]: { status: "error" as const, message: result.message || "查詢失敗" }
                };
                cacheRef.current = next;
                return next;
              });
              continue;
            }

            const profile = parsePlaygroundProfileData(result.data);
            if (!profile?.username) {
              setLookupByUser((current) => {
                const next = {
                  ...current,
                  [username]: { status: "error" as const, message: "API 回傳格式無法解析" }
                };
                cacheRef.current = next;
                return next;
              });
              continue;
            }

            setLookupByUser((current) => {
              const next = {
                ...current,
                [username]: { status: "ok" as const, profile }
              };
              cacheRef.current = next;
              return next;
            });
          } catch (err) {
            if (gen !== requestGenRef.current) return;
            setLookupByUser((current) => {
              const next = {
                ...current,
                [username]: {
                  status: "error" as const,
                  message: err instanceof Error ? err.message : "查詢失敗"
                }
              };
              cacheRef.current = next;
              return next;
            });
          }
        }
      })();
    }, 650);

    return () => window.clearTimeout(timer);
  }, [accountId, mentionsKey]);

  if (!mentions.length) return null;

  return (
    <div className="hx-mention-lookup" role="region" aria-label={label}>
      <div className="hx-mention-lookup__head">
        <strong>{label}</strong>
        <span className="muted hx-text-xs">profile_lookup · 輸入完整 @帳號後自動查詢</span>
      </div>
      <div className="hx-mention-lookup__list">
        {mentions.map((username) => (
          <MentionProfileCard
            key={username}
            username={username}
            state={lookupByUser[username] || { status: "loading" }}
          />
        ))}
      </div>
    </div>
  );
}

function MentionProfileCard({ username, state }: { username: string; state: LookupState }) {
  if (state.status === "loading") {
    return (
      <div className="hx-mention-card hx-mention-card--loading" role="status">
        <span className="hx-formula-status__spinner" aria-hidden="true" />
        <span>正在查 @{username}…</span>
      </div>
    );
  }

  if (state.status === "error") {
    return (
      <div className="hx-mention-card hx-mention-card--error" role="alert">
        <strong>@{username}</strong>
        <span>{state.message || "找不到此帳號"}</span>
      </div>
    );
  }

  const profile = state.profile!;
  const entries = profileDisplayEntries(profile);
  const avatar = typeof profile.profile_picture_url === "string" ? profile.profile_picture_url : "";

  return (
    <div className="hx-mention-card hx-mention-card--ok" role="status">
      <div className="hx-mention-card__main">
        {avatar ? <img className="hx-mention-card__avatar" src={avatar} alt="" /> : null}
        <div className="hx-mention-card__identity">
          <div className="button-row" style={{ flexWrap: "wrap" }}>
            <strong>@{profile.username || username}</strong>
            {profile.is_verified ? <Badge variant="brand">已認證</Badge> : null}
          </div>
          {profile.name ? <span className="hx-mention-card__name">{profile.name}</span> : null}
        </div>
      </div>
      {entries.length ? (
        <dl className="hx-mention-card__meta">
          {entries.map((entry) => (
            <div key={entry.key} className="hx-mention-card__meta-row">
              <dt>{entry.label}</dt>
              <dd>{entry.value}</dd>
            </div>
          ))}
        </dl>
      ) : null}
    </div>
  );
}