import { useEffect, useRef, useState } from "preact/hooks";
import type { SearchDetail } from "@/lib/api";
import { MarkdownContent } from "@/components/markdown/markdown-content";
import { cn } from "@/lib/utils";

function formatHost(url: string) {
  try {
    return new URL(url).hostname.replace(/^www\./, "");
  } catch {
    return url;
  }
}

function normalizeHref(href: string) {
  try {
    const parsed = new URL(href);
    parsed.hash = "";
    const normalized = parsed.toString();
    return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
  } catch {
    return href.trim().replace(/\/$/, "");
  }
}

type Props = {
  search: SearchDetail | null;
  isLoading: boolean;
  isRunning: boolean;
  className?: string;
};

export function SearchResultsPanel({ search, isLoading, isRunning, className }: Props) {
  const ANSWER_COLLAPSED_HEIGHT_CLASS = "h-[3rem]";
  const [isAnswerExpanded, setIsAnswerExpanded] = useState(false);
  const [canExpandAnswer, setCanExpandAnswer] = useState(false);
  const answerBodyRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    setIsAnswerExpanded(false);
    setCanExpandAnswer(false);
  }, [search?.id, search?.answerText]);

  useEffect(() => {
    const el = answerBodyRef.current;
    if (!el || !search?.answerText) {
      setCanExpandAnswer(false);
      return;
    }
    if (isAnswerExpanded) {
      setCanExpandAnswer(true);
      return;
    }
    setCanExpandAnswer(el.scrollHeight - el.clientHeight > 1);
  }, [search?.answerText, isAnswerExpanded]);

  const citationEntries = (search?.answerCitations ?? [])
    .map((citation, index) => {
      const href = citation.url || citation.id || "";
      if (!href) return null;
      return {
        href,
        normalizedHref: normalizeHref(href),
        index: index + 1,
        label: citation.title?.trim() || formatHost(href),
      };
    })
    .filter((entry): entry is { href: string; normalizedHref: string; index: number; label: string } => !!entry);

  const resolveCitationIndex = (href: string) => {
    const normalized = normalizeHref(href);
    return citationEntries.find((entry) => entry.normalizedHref === normalized)?.index;
  };

  const hasAnswerText = !!search?.answerText;
  const isAnswerLoading = isRunning && !hasAnswerText;
  const hasCitations = citationEntries.length > 0;
  const isExpandable = hasAnswerText && (canExpandAnswer || hasCitations);

  return (
    <div className={className ?? "mx-auto w-full max-w-4xl"}>
      {search?.query ? (
        <div className="mb-5">
          <p className="text-sm text-muted-foreground">Results for</p>
          <h2 className="mt-1 text-xl font-semibold">{search.query}</h2>
          <p className="mt-1 text-xs text-muted-foreground">
            {search.results.length} result{search.results.length === 1 ? "" : "s"}
            {search.latencyMs ? ` • ${search.latencyMs} ms` : ""}
          </p>
        </div>
      ) : null}

      {(isRunning || !!search?.answerText || !!search?.answerError) && (
        <section className="mb-6 rounded-xl border border-violet-400/35 bg-[hsl(276_31%_15%)] p-4">
          <p className="text-xs font-semibold uppercase tracking-wide text-violet-300/90">Answer</p>
          {(isAnswerLoading || hasAnswerText) ? (
            <div className="mt-2">
              <div className="relative">
                <div
                  ref={answerBodyRef}
                  className={cn(
                    "overflow-hidden",
                    !isAnswerExpanded && ANSWER_COLLAPSED_HEIGHT_CLASS
                  )}
                >
                  {isAnswerLoading ? (
                    <div className="text-sm text-muted-foreground">Generating answer...</div>
                  ) : (
                    <MarkdownContent
                      markdown={search?.answerText ?? ""}
                      mode="citationTokens"
                      resolveCitationIndex={resolveCitationIndex}
                      className="text-sm leading-6 text-violet-50"
                    />
                  )}
                </div>
                {!isAnswerExpanded && (isExpandable || isAnswerLoading) ? (
                  <div className="pointer-events-none absolute inset-x-0 bottom-0 h-7 bg-gradient-to-t from-[hsl(276_31%_15%)] to-transparent" />
                ) : null}
              </div>
              <div className="mt-2 h-5">
                {isExpandable ? (
                  <button
                    type="button"
                    className="inline-flex items-center gap-1 text-xs font-medium text-violet-200 hover:text-violet-100"
                    onClick={() => setIsAnswerExpanded((current) => !current)}
                  >
                    <span className={cn("inline-block text-[11px] transition-transform", isAnswerExpanded && "rotate-180")}>▾</span>
                    {isAnswerExpanded ? "Show less" : "Show more"}
                  </button>
                ) : null}
              </div>
            </div>
          ) : null}
          {search?.answerError ? <p className="mt-2 text-sm text-red-500">{search.answerError}</p> : null}
          {isAnswerExpanded && !!citationEntries.length && (
            <div className="mt-3 flex flex-wrap gap-2">
              {citationEntries.slice(0, 8).map((citation) => {
                return (
                  <a
                    key={`${citation.href}-${citation.index}`}
                    href={citation.href}
                    target="_blank"
                    rel="noreferrer"
                    className="rounded-md border border-violet-400/40 px-2 py-1 text-xs text-violet-200 hover:bg-violet-500/20"
                  >
                    <span className="mr-1 rounded bg-violet-900/70 px-1 py-0.5 text-[10px] text-violet-100">{citation.index}</span>
                    {citation.label}
                  </a>
                );
              })}
            </div>
          )}
        </section>
      )}

      {(isLoading || isRunning) && !search?.results.length ? (
        <p className="text-sm text-muted-foreground">{isRunning ? "Searching Exa..." : "Loading search..."}</p>
      ) : null}

      {!isLoading && !isRunning && !!search?.query && search.results.length === 0 ? (
        <p className="text-sm text-muted-foreground">No results found.</p>
      ) : null}

      <div className="space-y-6">
        {search?.results.map((result) => {
          return (
            <article key={result.id} className="rounded-lg border border-border bg-[hsl(276_30%_13%)] px-4 py-4 shadow-sm">
              <p className="text-xs text-violet-300/85">{formatHost(result.url)}</p>
              <a href={result.url} target="_blank" rel="noreferrer" className="mt-1 block text-lg font-medium text-violet-300 hover:underline">
                {result.title || result.url}
              </a>
              {(result.publishedDate || result.author) && (
                <p className="mt-1 text-xs text-muted-foreground">{[result.publishedDate, result.author].filter(Boolean).join(" • ")}</p>
              )}
              {result.url ? <p className="mt-2 text-sm leading-6 text-violet-100/90">{result.url}</p> : null}
            </article>
          );
        })}
      </div>

      {search?.error ? <p className="mt-4 text-sm text-red-600">{search.error}</p> : null}
    </div>
  );
}
