import { useEffect, useState, useCallback } from "react";
import { useParams } from "react-router-dom";
import { fetchPublicShort, type PublicShortResponse } from "../api/shorts";
import { copyToClipboard } from "../utils/clipboard";
import styles from "./ShortPlayer.module.css";

function buildEmbedSnippet(
  token: string,
  width: number,
  height: number,
): string {
  const src = `${window.location.origin}/shorts/${token}`;
  return `<iframe src="${src}" width="${width}" height="${height}" frameborder="0" allowfullscreen></iframe>`;
}

export default function ShortPlayer() {
  const { token } = useParams<{ token: string }>();
  const [data, setData] = useState<PublicShortResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState<"share" | "embed" | null>(null);

  useEffect(() => {
    if (!token) {
      setError("No share token provided");
      setLoading(false);
      return;
    }

    let cancelled = false;
    setLoading(true);
    setError(null);

    fetchPublicShort(token)
      .then((res) => {
        if (!cancelled) setData(res);
      })
      .catch((err) => {
        if (!cancelled) {
          setError(
            err?.detail ?? err?.message ?? "Short not found",
          );
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [token]);

  const showCopiedFlash = useCallback((which: "share" | "embed") => {
    setCopied(which);
    setTimeout(() => setCopied(null), 2000);
  }, []);

  const handleCopyShare = useCallback(async () => {
    const url = `${window.location.origin}/shorts/${token}`;
    const ok = await copyToClipboard(url);
    if (ok) showCopiedFlash("share");
  }, [token, showCopiedFlash]);

  const handleCopyEmbed = useCallback(async () => {
    if (!data || !token) return;
    const snippet = buildEmbedSnippet(token, data.width, data.height);
    const ok = await copyToClipboard(snippet);
    if (ok) showCopiedFlash("embed");
  }, [data, token, showCopiedFlash]);

  if (loading) {
    return (
      <div className={styles.loadingState}>Loading…</div>
    );
  }

  if (error || !data) {
    return (
      <div className={styles.errorState}>
        <p className={styles.errorMessage}>{error ?? "Short not found"}</p>
        <p>This short may have been removed or the link is invalid.</p>
      </div>
    );
  }

  return (
    <div className={styles.page}>
      <div className={styles.wrapper}>
        <video
          className={styles.video}
          src={data.download_url}
          controls
          autoPlay
          playsInline
          width={data.width}
          height={data.height}
        />

        <div className={styles.meta}>
          <h1 className={styles.title}>{data.highlight_title}</h1>
          <p className={styles.creator}>by {data.creator_name}</p>
        </div>

        <div className={styles.actions}>
          <button
            className={`${styles.copyBtn} ${copied === "share" ? styles.copied : ""}`}
            onClick={handleCopyShare}
          >
            {copied === "share" ? "Copied!" : "Copy Share Link"}
          </button>
          <button
            className={`${styles.copyBtn} ${copied === "embed" ? styles.copied : ""}`}
            onClick={handleCopyEmbed}
          >
            {copied === "embed" ? "Copied!" : "Copy Embed Code"}
          </button>
        </div>

        <p className={styles.branding}>
          Powered by <a href="/">Chrysopedia</a>
        </p>
      </div>
    </div>
  );
}
