import { useCallback, useEffect, useState } from "react";
import { PageHeader } from "../components/layout/PageHeader";
import { Button, Card, EmptyState, Input } from "../components/ui";
import { apiRequest } from "../data/live/http";
import { useI18n } from "../i18n/I18nContext";

type Link = {
  id: string;
  code: string;
  track_path: string;
  /** 後端算好的絕對網址；舊版後端沒有這欄，退回 track_path。 */
  track_url?: string;
  destination_url: string;
  outcome_id?: string;
  label?: string;
  clicks: number;
  created_at: number;
};

function trackUrlOf(l: Link): string {
  return l.track_url || `${window.location.origin}${l.track_path}`;
}

export function UtmLinksPage() {
  const { t } = useI18n();
  const [list, setList] = useState<Link[]>([]);
  const [url, setUrl] = useState("");
  const [label, setLabel] = useState("");
  const [msg, setMsg] = useState("");

  const load = useCallback(async () => {
    const data = await apiRequest<{ list?: Link[] }>("/api/v1/utm/links");
    setList(data.list ?? []);
  }, []);

  useEffect(() => {
    void load().catch((e) => setMsg(String(e)));
  }, [load]);

  async function create() {
    try {
      await apiRequest("/api/v1/utm/links", {
        method: "POST",
        body: { destination_url: url, label },
      });
      setUrl("");
      setLabel("");
      await load();
      setMsg(t("utm.created"));
    } catch (e) {
      setMsg(e instanceof Error ? e.message : "fail");
    }
  }

  async function copy(l: Link) {
    try {
      await navigator.clipboard.writeText(trackUrlOf(l));
      setMsg(t("utm.copied"));
    } catch {
      setMsg(t("utm.copyFail"));
    }
  }

  return (
    <>
      <PageHeader title={t("utm.title")} />
      {msg ? <p className="text-muted">{msg}</p> : null}
      <Card title={t("utm.new")}>
        <div className="hb-stack">
          <Input label={t("utm.dest")} value={url} onChange={(e) => setUrl(e.target.value)} />
          <Input label={t("utm.label")} value={label} onChange={(e) => setLabel(e.target.value)} />
          <Button type="button" disabled={!url.startsWith("http")} onClick={() => void create()}>
            {t("utm.create")}
          </Button>
        </div>
      </Card>
      {list.length === 0 ? (
        <EmptyState title={t("utm.empty")} />
      ) : (
        <ul className="hb-stack">
          {list.map((l) => (
            <Card key={l.id} title={l.label || l.code}>
              <p className="text-muted" style={{ wordBreak: "break-all" }}>
                {t("utm.track", { url: trackUrlOf(l) })}
              </p>
              <p>{t("utm.destLine", { url: l.destination_url })}</p>
              <p>{t("utm.clicks", { n: l.clicks })}</p>
              <Button type="button" onClick={() => void copy(l)}>
                {t("utm.copy")}
              </Button>
            </Card>
          ))}
        </ul>
      )}
    </>
  );
}
