"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { UI_SKINS, type UiSkinId, getUiSkin, setCachedPreferredUi } from "@/lib/uiSkins";
import { useProfile } from "@/lib/profile/context";
import { addAnalyticsEvent, putAccount, putProfile } from "@/lib/profile/db";
import { pushAccountToCloud } from "@/lib/oauth/cloudAccount";

export function UiSkinPicker({
  initial,
  afterSaveHref = "/",
  title = "Choose your cabinet",
  subtitle = "Full-screen home UIs. Pick one — change it anytime.",
}: {
  initial?: string;
  afterSaveHref?: string;
  title?: string;
  subtitle?: string;
}) {
  const { account, profile, refresh } = useProfile();
  const [selected, setSelected] = useState<UiSkinId>(
    (initial as UiSkinId) || "classic",
  );
  const [saving, setSaving] = useState(false);
  const router = useRouter();
  const skin = getUiSkin(selected);
  const index = UI_SKINS.findIndex((s) => s.id === selected);

  useEffect(() => {
    document.documentElement.classList.add("ui-picker-mode");
    return () => document.documentElement.classList.remove("ui-picker-mode");
  }, []);

  function step(delta: number) {
    const next = (index + delta + UI_SKINS.length) % UI_SKINS.length;
    setSelected(UI_SKINS[next].id);
  }

  async function save() {
    setSaving(true);
    try {
      if (account) {
        const next = {
          ...account,
          preferredUi: selected,
          needsUiSetup: false,
          updatedAt: Date.now(),
        };
        await putAccount(next);
        await pushAccountToCloud(next);
      } else if (profile) {
        await putProfile({
          ...profile,
          settings: { ...profile.settings, preferredUi: selected },
        });
      }
      await refresh();
      setCachedPreferredUi(selected);
      await addAnalyticsEvent({
        type: "ui_skin_set",
        accountId: account?.id,
        profileId: profile?.id,
        label: selected,
        at: Date.now(),
      });
      router.push(afterSaveHref);
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="ui-picker-full fixed inset-0 z-40 flex flex-col bg-background">
      <div
        className="ui-picker-stage relative min-h-0 flex-1"
        style={{ background: skin.preview.bg }}
      >
        <div className="absolute inset-0 opacity-30" aria-hidden>
          <div
            className="absolute inset-0"
            style={{
              background:
                "repeating-linear-gradient(0deg,transparent,transparent 2px,rgba(0,0,0,.15) 2px,rgba(0,0,0,.15) 3px)",
            }}
          />
        </div>

        <div className="relative z-10 flex h-full flex-col justify-between p-6 sm:p-10 lg:p-14">
          <div className="flex items-start justify-between gap-4">
            <div>
              <p className="font-display text-[0.55rem] tracking-[0.3em] text-white/50 uppercase">
                {title}
              </p>
              <p className="mt-2 max-w-md text-sm text-white/70">{subtitle}</p>
            </div>
            <div className="flex flex-wrap gap-2">
              <Link href="/profiles" className="btn-ghost border-white/20 text-white/80">
                Profiles
              </Link>
              <Link href="/settings" className="btn-ghost border-white/20 text-white/80">
                Settings
              </Link>
              <Link href="/" className="btn-ghost border-white/20 text-white/80">
                Cancel
              </Link>
            </div>
          </div>

          <div className="flex flex-1 flex-col items-center justify-center py-10 text-center">
            <p
              className="font-display text-6xl tracking-[0.12em] sm:text-8xl md:text-9xl"
              style={{ color: skin.preview.accent }}
            >
              {skin.preview.label}
            </p>
            <h1 className="mt-6 font-display text-3xl tracking-wide text-white sm:text-4xl">
              {skin.name}
            </h1>
            <p className="mt-3 max-w-lg text-base text-white/70">{skin.blurb}</p>
            <p className="mt-6 font-display text-[0.55rem] tracking-[0.2em] text-white/40 uppercase">
              {skin.mode === "console" ? "Fullscreen console shell" : "Fullscreen library"}
              {" · "}
              {index + 1} / {UI_SKINS.length}
            </p>
          </div>

          <div className="flex flex-wrap items-center justify-center gap-2">
            {UI_SKINS.map((s) => (
              <button
                key={s.id}
                type="button"
                aria-label={s.name}
                onClick={() => setSelected(s.id)}
                className={`h-2.5 w-2.5 rounded-full transition ${
                  s.id === selected
                    ? "scale-125 bg-white"
                    : "bg-white/35 hover:bg-white/60"
                }`}
              />
            ))}
          </div>
        </div>

        <button
          type="button"
          className="absolute left-3 top-1/2 z-20 -translate-y-1/2 btn-ghost border-white/25 bg-black/40 text-white sm:left-6"
          onClick={() => step(-1)}
          aria-label="Previous UI"
        >
          ←
        </button>
        <button
          type="button"
          className="absolute right-3 top-1/2 z-20 -translate-y-1/2 btn-ghost border-white/25 bg-black/40 text-white sm:right-6"
          onClick={() => step(1)}
          aria-label="Next UI"
        >
          →
        </button>
      </div>

      <div className="relative z-10 flex flex-wrap items-center justify-between gap-4 border-t border-line bg-background/95 px-4 py-5 backdrop-blur sm:px-8">
        <div className="min-w-0">
          <p className="font-display text-sm tracking-wide">{skin.name}</p>
          <p className="truncate text-xs text-muted">{skin.blurb}</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <button
            type="button"
            className="btn-ghost"
            onClick={() => step(-1)}
          >
            Prev
          </button>
          <button type="button" className="btn-ghost" onClick={() => step(1)}>
            Next
          </button>
          <button
            type="button"
            className="btn-primary"
            disabled={saving}
            onClick={() => void save()}
          >
            {saving ? "Saving…" : "Use this UI"}
          </button>
        </div>
      </div>
    </div>
  );
}
