"use client";

import { useEffect, useId, useState } from "react";
import { Download, Share2, Star, X } from "lucide-react";

import { openChatInExternalBrowser } from "@/lib/chat/chat_external_browser";
import {
  hasPersistedFavoriteEntryIntent,
  resolveFavoriteEntryMode,
  type FavoriteEntryMode,
} from "@/lib/navigation/favorite_entry";
import { BrowserDetector } from "@/utils/browser-detect";
import { PlatformDetector } from "@/utils/platform-detect";
import { pwaUtil } from "@/utils/pwa";

import styles from "./favorite-entry-button.module.css";

export interface FavoriteEntryButtonProps {
  characterSlug: string;
  tone?: "dark" | "light";
}

export function FavoriteEntryButton({
  characterSlug,
  tone = "dark",
}: FavoriteEntryButtonProps) {
  const [mode, setMode] = useState<FavoriteEntryMode>("favorite");
  const [installGuide, setInstallGuide] = useState<
    "ios" | "browser" | null
  >(null);
  const installGuideTitleId = useId();

  useEffect(() => {
    const updateMode = () => {
      setMode(
        resolveFavoriteEntryMode({
          hasFavoriteIntent: hasPersistedFavoriteEntryIntent(),
          isAndroid: PlatformDetector.isAndroid(),
          isIOS: PlatformDetector.isIOS(),
          isInAppBrowser: BrowserDetector.isInAppBrowser(),
          isInstalled: pwaUtil.isInstalled(),
        }),
      );
    };

    pwaUtil.prepareInstallPrompt();
    updateMode();
    const unsubscribe = pwaUtil.subscribe(updateMode);
    return unsubscribe;
  }, []);

  useEffect(() => {
    if (!installGuide) return;
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setInstallGuide(null);
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [installGuide]);

  const handleClick = async (): Promise<void> => {
    if (mode === "favorite") {
      await openChatInExternalBrowser({ characterSlug });
      return;
    }

    if (mode === "download") {
      if (PlatformDetector.isIOS()) {
        setInstallGuide("ios");
        return;
      }
      pwaUtil.prepareInstallPrompt();
      const result = await pwaUtil.install();
      if (result === "accepted" || pwaUtil.isInstalled()) {
        setMode("saved");
        setInstallGuide(null);
        return;
      }
      if (result === "unavailable") setInstallGuide("browser");
    }
  };

  const label = getFavoriteEntryLabel(mode);

  return (
    <div className={styles.wrap}>
      <button
        type="button"
        data-analytics-key={`favorite.${mode}`}
        data-analytics-label={label}
        className={[styles.button, styles[tone], styles[mode]]
          .filter(Boolean)
          .join(" ")}
        aria-label={label}
        aria-pressed={mode === "saved"}
        onClick={() => void handleClick()}
      >
        {mode === "download" ? (
          <Download size={16} strokeWidth={2.4} aria-hidden="true" />
        ) : (
          <Star
            size={21}
            strokeWidth={2.3}
            fill={mode === "saved" ? "currentColor" : "none"}
            aria-hidden="true"
          />
        )}
        {mode === "favorite" ? null : <span>{label}</span>}
      </button>
      {installGuide ? (
        <div
          className={styles.guideBackdrop}
          onClick={() => setInstallGuide(null)}
          role="presentation"
        >
          <section
            className={styles.guideDialog}
            role="dialog"
            aria-modal="true"
            aria-labelledby={installGuideTitleId}
            onClick={(event) => event.stopPropagation()}
          >
            <button
              type="button"
              className={styles.guideClose}
              onClick={() => setInstallGuide(null)}
              aria-label="Close install instructions"
            >
              <X size={18} aria-hidden="true" />
            </button>
            <span className={styles.guideIcon} aria-hidden="true">
              {installGuide === "ios" ? (
                <Share2 size={28} strokeWidth={2.2} />
              ) : (
                <Download size={28} strokeWidth={2.2} />
              )}
            </span>
            <h2 id={installGuideTitleId}>Add CozSweet to Home Screen</h2>
            <p>
              {installGuide === "ios"
                ? "In Safari, tap the Share button, then choose “Add to Home Screen”."
                : "Open your browser menu, then choose “Add to Home screen”."}
            </p>
            <button
              type="button"
              className={styles.guideConfirm}
              onClick={() => setInstallGuide(null)}
            >
              Got it
            </button>
          </section>
        </div>
      ) : null}
    </div>
  );
}

function getFavoriteEntryLabel(mode: FavoriteEntryMode): string {
  if (mode === "download") return "Download";
  if (mode === "saved") return "Saved";
  return "Save CozSweet";
}
