import { IconX } from "@tabler/icons-react";
import { useState } from "react";

import {
  useUpdateStatus,
  installAndRestart,
  retryUpdateCheck,
} from "../lib/updater";
import { DownloadIcon, SpinnerIcon } from "./Icons";

/**
 * Compact banner that slots into the top of the popover whenever an update
 * is in flight or ready. Kept tight so it doesn't push the recording
 * controls off-screen. Hidden in idle / checking / not-available states.
 */
export function UpdateBanner() {
  const status = useUpdateStatus();
  const [dismissedVersion, setDismissedVersion] = useState<string | null>(null);
  // Dismissal is scoped to the specific error message so a new,
  // different failure still surfaces. Users shouldn't have to see the
  // same message twice, but they should hear about a new kind of
  // failure.
  const [dismissedErrorMessage, setDismissedErrorMessage] = useState<
    string | null
  >(null);

  if (status.state === "idle") return null;
  if (status.state === "checking") return null;
  if (status.state === "not-available") return null;

  if (status.state === "error") {
    if (status.message === dismissedErrorMessage) return null;
    return (
      <div className="update-banner update-banner--error">
        <span className="update-banner-text">
          Update check failed: {status.message}
        </span>
        <div className="update-banner-actions">
          <button
            type="button"
            className="update-banner-btn update-banner-btn--ghost"
            onClick={() => setDismissedErrorMessage(status.message)}
          >
            Dismiss
          </button>
          <button
            type="button"
            className="update-banner-btn update-banner-btn--primary"
            onClick={() => {
              retryUpdateCheck().catch((err) => {
                console.error("[clips-updater] retry failed:", err);
              });
            }}
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  // User dismissed for this version — don't keep nagging.
  if (
    (status.state === "available" ||
      status.state === "downloading" ||
      status.state === "downloaded") &&
    status.version === dismissedVersion
  ) {
    return null;
  }

  if (status.state === "available") {
    return (
      <div className="update-banner update-banner--pending">
        <DownloadIcon />
        <span className="update-banner-text">
          Update available — downloading…
        </span>
      </div>
    );
  }

  if (status.state === "downloading") {
    return (
      <div className="update-banner update-banner--pending">
        <SpinnerIcon />
        <span className="update-banner-text">
          Downloading update… {status.percent}%
        </span>
      </div>
    );
  }

  // downloaded → actionable restart
  return (
    <div className="update-banner update-banner--ready">
      <span className="update-banner-text">
        Update ready — restart to install
      </span>
      <div className="update-banner-actions">
        <button
          type="button"
          className="update-banner-btn update-banner-btn--dismiss"
          onClick={() => setDismissedVersion(status.version)}
          aria-label="Dismiss update"
          title="Dismiss update"
        >
          <IconX size={15} strokeWidth={1.8} aria-hidden />
        </button>
        <button
          type="button"
          className="update-banner-btn update-banner-btn--primary"
          onClick={() => {
            installAndRestart().catch((err) => {
              console.error("[clips-updater] relaunch failed:", err);
            });
          }}
        >
          Restart
        </button>
      </div>
    </div>
  );
}
