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";

type Link = {
  id: string;
  code: string;
  track_path: string;
  destination_url: string;
  outcome_id?: string;
  label?: string;
  clicks: number;
  created_at: number;
};

export function UtmLinksPage() {
  const [list, setList] = useState<Link[]>([]);
  const [url, setUrl] = useState("");
  const [label, setLabel] = useState("");
  const [outcomeId, setOutcomeId] = 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, outcome_id: outcomeId || undefined },
      });
      setUrl("");
      setLabel("");
      setOutcomeId("");
      await load();
      setMsg("已建立追蹤連結");
    } catch (e) {
      setMsg(e instanceof Error ? e.message : "fail");
    }
  }

  return (
    <>
      <PageHeader title="UTM 追蹤連結" description="點擊自動計入成果歸因" />
      {msg ? <p className="text-muted">{msg}</p> : null}
      <Card title="新建">
        <div className="hb-stack">
          <Input label="目標 URL" value={url} onChange={(e) => setUrl(e.target.value)} />
          <Input label="標籤" value={label} onChange={(e) => setLabel(e.target.value)} />
          <Input
            label="綁定 Outcome ID（選填）"
            value={outcomeId}
            onChange={(e) => setOutcomeId(e.target.value)}
          />
          <Button type="button" disabled={!url.startsWith("http")} onClick={() => void create()}>
            建立
          </Button>
        </div>
      </Card>
      {list.length === 0 ? (
        <EmptyState title="尚無連結" />
      ) : (
        <ul className="hb-stack">
          {list.map((l) => (
            <Card key={l.id} title={l.label || l.code}>
              <p className="text-muted" style={{ wordBreak: "break-all" }}>
                追蹤：{window.location.origin}
                {l.track_path}
              </p>
              <p>目標：{l.destination_url}</p>
              <p>點擊：{l.clicks}</p>
            </Card>
          ))}
        </ul>
      )}
    </>
  );
}
