import { useEffect, useRef, useState } from "react";

import { addChannel } from "../api";
import { BTN, BTN_PRIMARY, Dialog, HELP, INPUT, Spinner } from "./ui";

interface Props {
  onClose: () => void;
  onAdded: (title: string) => void;
}

/**
 * Adds one channel from a link, for the ones a Takeout export does not have —
 * something found after the last import, or a channel followed nowhere but
 * here. Any YouTube link belonging to the channel works, including a video of
 * theirs, since the channel is what gets read off the page.
 */
export default function AddChannel({ onClose, onAdded }: Props) {
  const [url, setUrl] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const field = useRef<HTMLInputElement>(null);

  useEffect(() => field.current?.focus(), []);

  const submit = () => {
    if (busy || !url.trim()) return;
    setBusy(true);
    setError(null);
    addChannel(url.trim())
      .then(onAdded)
      .catch((e) => setError(String(e)))
      .finally(() => setBusy(false));
  };

  const footer = (
    <div className="flex justify-end gap-2">
      <button onClick={onClose} className={`${BTN} cursor-pointer`}>
        Cancel
      </button>
      <button
        onClick={submit}
        disabled={busy || !url.trim()}
        className={`${BTN_PRIMARY} cursor-pointer disabled:cursor-not-allowed disabled:opacity-40`}
      >
        {busy ? <Spinner /> : "Add channel"}
      </button>
    </div>
  );

  return (
    <Dialog title="Add a channel" onCancel={onClose} footer={footer}>
      <p className={HELP}>
        Paste any link belonging to the channel — its own page, its @handle, or
        one of its videos. FlightTube reads the channel from the page and starts
        following it here. Nothing changes on YouTube.
      </p>

      <input
        ref={field}
        value={url}
        onChange={(e) => setUrl(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === "Enter") submit();
        }}
        placeholder="https://www.youtube.com/@channel"
        spellCheck={false}
        className={`${INPUT} mt-3 w-full`}
      />

      {error && (
        <p className="mt-2 text-[12px] leading-snug text-red-600 dark:text-red-400">{error}</p>
      )}

    </Dialog>
  );
}
