import { cn } from "@/lib/utils";
import { useTheme } from "next-themes";
import { useEffect, useState } from "react";
import { Moon, Sun } from "./icons";

const THEMES = [
  {
    name: "light",
    Icon: Sun,
  },
  {
    name: "dark",
    Icon: Moon,
  },
];

type ThemeToggleSwitchProps = {
  className?: string;
};

export function ThemeToggleSwitch({ className }: ThemeToggleSwitchProps) {
  const { setTheme, theme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const isDarkTheme = theme === "dark";
  const tripleTapMaxDelay = 500;

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!isTransitioning) return;

    const transitionTimer = window.setTimeout(() => {
      setIsTransitioning(false);
    }, 650);

    return () => window.clearTimeout(transitionTimer);
  }, [isTransitioning]);

  useEffect(() => {
    if (!mounted) return;

    let tapCount = 0;
    let lastTapAt = 0;

    const isTypingInInput = (target: EventTarget | null) => {
      if (!(target instanceof HTMLElement)) return false;

      const tagName = target.tagName.toLowerCase();
      if (tagName === "input" || tagName === "textarea" || tagName === "select") {
        return true;
      }

      return target.isContentEditable;
    };

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.repeat) return;
      if (event.key.toLowerCase() !== "t") return;
      if (event.ctrlKey || event.metaKey || event.altKey) return;
      if (isTypingInInput(event.target)) return;

      const now = Date.now();
      tapCount = now - lastTapAt <= tripleTapMaxDelay ? tapCount + 1 : 1;
      lastTapAt = now;

      if (tapCount === 3) {
        setIsTransitioning(true);
        setTheme(theme === "dark" ? "light" : "dark");
        tapCount = 0;
        lastTapAt = 0;
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [mounted, setTheme, theme]);

  if (!mounted) {
    return null;
  }

  return (
    <button
      onClick={() => {
        setIsTransitioning(true);
        setTheme(isDarkTheme ? "light" : "dark");
      }}
      className={cn(
        "group relative shrink-0 overflow-hidden rounded-full border border-stroke/70 bg-white/75 p-[5px] text-[#111928] shadow-theme-xs backdrop-blur-md outline-1 outline-primary transition-[color,border-color,background-color,box-shadow] duration-500 ease-out focus-visible:outline dark:border-dark-3 dark:bg-[#020D1A]/75 dark:text-current",
        className,
      )}
      type="button"
    >
      <span className="sr-only">
        Switch to {isDarkTheme ? "light" : "dark"} mode
      </span>

      <span
        aria-hidden
        className={cn(
          "pointer-events-none absolute inset-0 rounded-full bg-[radial-gradient(circle_at_20%_20%,rgba(99,102,241,0.24),transparent_50%),radial-gradient(circle_at_80%_80%,rgba(20,184,166,0.2),transparent_45%)] opacity-0 transition-opacity duration-500",
          isTransitioning && "opacity-100",
          isDarkTheme &&
            "bg-[radial-gradient(circle_at_20%_20%,rgba(59,130,246,0.2),transparent_50%),radial-gradient(circle_at_80%_80%,rgba(129,140,248,0.25),transparent_45%)]",
        )}
      />

      <span aria-hidden className="relative flex gap-2.5">
        {/* Indicator */}
        <span
          className={cn(
            "absolute size-[38px] rounded-full border border-gray-200 bg-white transition-[transform,background-color,border-color,box-shadow] duration-500 ease-[cubic-bezier(0.2,0.8,0.2,1)] motion-reduce:transition-none",
            "shadow-[0_8px_24px_rgba(15,23,42,0.1)] dark:border-dark-3 dark:bg-dark-2 dark:group-hover:bg-dark-3",
            isDarkTheme
              ? "translate-x-[48px] shadow-[0_0_0_1px_rgba(99,102,241,0.25),0_10px_24px_rgba(30,41,59,0.45)]"
              : "translate-x-0",
            isTransitioning && "scale-[1.06]",
          )}
        />

        {THEMES.map(({ name, Icon }) => (
          <span
            key={name}
            className={cn(
              "relative grid size-[38px] place-items-center rounded-full transition-transform duration-500 ease-out motion-reduce:transition-none",
              name === "dark" && "dark:text-white",
              name === "light"
                ? isDarkTheme
                  ? "scale-75 -rotate-45 opacity-60"
                  : "scale-100 rotate-0 opacity-100"
                : isDarkTheme
                  ? "scale-100 rotate-0 opacity-100"
                  : "scale-75 rotate-45 opacity-60",
            )}
          >
            <Icon
              className={cn(
                "transition-all duration-500 ease-out motion-reduce:transition-none",
                name === "light"
                  ? "text-amber-500 drop-shadow-[0_0_10px_rgba(245,158,11,0.35)]"
                  : "text-indigo-300 drop-shadow-[0_0_10px_rgba(129,140,248,0.35)]",
                isTransitioning && "animate-[spin_700ms_cubic-bezier(0.2,0.8,0.2,1)]",
              )}
            />
          </span>
        ))}
      </span>
    </button>
  );
}
