import { useEffect, useState } from "react";
import {
  ExternalLink,
  Loader2,
  BookOpen,
  Clock,
} from "lucide-react";
import { api } from "@/client";
import RepoDrawer from "./repo-drawer";
import type { RepoLinkMatch } from "./repo-link-parser";

type RepoInfo = {
  name: string;
  description: string | null;
  default_branch: string;
  language: string | null;
  updated_at: string;
};

function languageColor(lang: string): string {
  const map: Record<string, string> = {
    Rust: "#DEA584",
    TypeScript: "#3178C6",
    JavaScript: "#F7DF1E",
    Python: "#3572A5",
    Go: "#00ADD8",
    Java: "#B07219",
    Kotlin: "#A97BFF",
    Swift: "#F05138",
    C: "#555555",
    "C++": "#F34B7D",
    "C#": "#178600",
    Ruby: "#701516",
    Zig: "#EC915C",
    Elixir: "#6E4A7E",
    Haskell: "#5E5086",
    CSS: "#563D7C",
    HTML: "#E34C26",
    Shell: "#89E051",
  };
  return map[lang] ?? "#6B7280";
}

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  const days = Math.floor(diff / 86400000);
  if (days < 1) return "today";
  if (days === 1) return "yesterday";
  if (days < 30) return `${days}d ago`;
  const months = Math.floor(days / 30);
  if (months < 12) return `${months}mo ago`;
  return `${Math.floor(months / 12)}y ago`;
}

export default function RepoEmbedCard({ link }: { link: RepoLinkMatch }) {
  const [info, setInfo] = useState<RepoInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    let cancelled = false;
    // eslint-disable-next-line react-hooks/set-state-in-effect -- fetch on mount
    setLoading(true);

    const repoPath = `/api/v1/workspace/${link.workspace}/repos/${link.repo}`;

    api
      .get<Record<string, unknown>>(repoPath)
      .then(async (repoRes) => {
        if (cancelled) return;
        const d = repoRes.data as Record<string, unknown>;
        // Fetch top language
        let topLang: string | null = null;
        try {
          const langRes = await api.get<
            { language: string; percent: number }[]
          >(`${repoPath}/git/languages`);
          if (!cancelled && langRes.data.length > 0) {
            topLang = langRes.data[0].language;
          }
        } catch {
          // language fetch is best-effort
        }

        if (cancelled) return;
        setInfo({
          name: (d.name as string) ?? link.repo,
          description: (d.description as string) ?? null,
          default_branch: (d.default_branch as string) ?? "main",
          language: topLang,
          updated_at: (d.updated_at as string) ?? "",
        });
      })
      .catch(() => {
        if (!cancelled) setError(true);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [link.workspace, link.repo]);

  return (
    <RepoDrawer repo={link.repo} workspace={link.workspace}>
      <div className="mt-2 block max-w-[420px] rounded-xl border border-border/30 bg-muted/[0.03] p-4 transition-[background-color,border-color,color,opacity,box-shadow,transform] duration-200 hover:border-primary/20 hover:bg-muted/[0.08] hover:shadow-sm">
      {loading ? (
        <div className="flex items-center gap-2 py-2 text-[13px] text-muted-foreground/50">
          <Loader2 className="size-4 animate-spin" />
          Loading repo info…
        </div>
      ) : error || !info ? (
        <div className="flex items-center gap-2 py-2">
          <BookOpen className="size-4 shrink-0 text-muted-foreground/30" />
          <div className="min-w-0 flex-1">
            <p className="text-[13px] font-semibold text-foreground/70">
              {link.workspace}/{link.repo}
            </p>
            <p className="text-[11px] text-muted-foreground/40">
              Click to open repository
            </p>
          </div>
          <ExternalLink className="size-3.5 shrink-0 text-muted-foreground/25" />
        </div>
      ) : (
        <>
          <div className="flex items-start gap-3">
            <div className="grid size-8 shrink-0 place-items-center rounded-lg bg-muted/40">
              <BookOpen className="size-4 text-muted-foreground/50" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="text-[13px] font-semibold text-foreground">
                {link.workspace}/
                <span className="text-primary/80">{link.repo}</span>
              </p>
              {info.description && (
                <p className="mt-0.5 line-clamp-2 text-[12px] leading-relaxed text-muted-foreground/60">
                  {info.description}
                </p>
              )}
            </div>
            <ExternalLink className="mt-0.5 size-3.5 shrink-0 text-muted-foreground/20" />
          </div>

          <div className="mt-3 flex flex-wrap items-center gap-3 text-[11px] text-muted-foreground/50">
            {info.language && (
              <span className="inline-flex items-center gap-1.5">
                <span
                  className="inline-block size-2.5 rounded-full"
                  style={{ backgroundColor: languageColor(info.language) }}
                />
                {info.language}
              </span>
            )}
            <span className="inline-flex items-center gap-1">
              <Clock className="size-3" />
              {info.updated_at ? timeAgo(info.updated_at) : ""}
            </span>
          </div>
        </>
      )}
      </div>
    </RepoDrawer>
  );
}
