"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  ExternalLink,
  Copy,
  Check,
  HelpCircle,
  User,
  Sparkles,
  Home,
  Compass,
} from "lucide-react";
import ThemeToggle from "@/components/ThemeToggle";
import {
  SITE_NAME,
  DISCORD_INVITE_URL,
  isReservedProfileHandle,
} from "@/lib/constants";
import { createClient } from "@/lib/supabase/client";

interface LoggedInProfile {
  id: string;
  username: string;
  avatar_url?: string | null;
  display_name?: string | null;
}

export default function UnclaimedUsernameScreen({
  initialHandle,
}: {
  initialHandle?: string;
}) {
  const pathname = usePathname() || "";
  const [currentUser, setCurrentUser] = useState<LoggedInProfile | null>(null);
  const [authLoading, setAuthLoading] = useState(true);
  const [copied, setCopied] = useState(false);

  // Derive handle from prop or pathname (/username -> username)
  const segments = pathname.replace(/^\/+/, "").split("/").filter(Boolean);
  const rawFirstSegment = initialHandle || (segments.length > 0 ? segments[0] : "");
  const cleanHandle = rawFirstSegment
    ? decodeURIComponent(rawFirstSegment).replace(/^@/, "").trim().toLowerCase()
    : "";

  const isHandle =
    Boolean(cleanHandle) &&
    segments.length <= 1 &&
    !isReservedProfileHandle(cleanHandle);

  useEffect(() => {
    let mounted = true;
    try {
      const supabase = createClient();
      supabase.auth
        .getUser()
        .then(async ({ data: { user } }) => {
          if (!mounted) return;
          if (!user) {
            setAuthLoading(false);
            return;
          }

          const { data: profile } = await supabase
            .from("profiles")
            .select("id, username, avatar_url, display_name")
            .eq("id", user.id)
            .maybeSingle();

          if (mounted) {
            if (profile?.username) {
              setCurrentUser(profile);
            }
            setAuthLoading(false);
          }
        })
        .catch(() => {
          if (mounted) setAuthLoading(false);
        });
    } catch {
      if (mounted) setAuthLoading(false);
    }

    return () => {
      mounted = false;
    };
  }, []);

  const handleCopy = async () => {
    try {
      const url =
        typeof window !== "undefined"
          ? window.location.href
          : `https://${SITE_NAME}/${cleanHandle || ""}`;
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // Fallback
    }
  };

  const claimUrl = isHandle
    ? currentUser
      ? `/claim?handle=${encodeURIComponent(cleanHandle)}`
      : `/signup?username=${encodeURIComponent(cleanHandle)}`
    : currentUser
      ? "/dashboard"
      : "/signup";

  return (
    <main
      className="min-h-screen w-full flex flex-col items-center justify-center p-4 sm:p-6 text-white relative selection:bg-red-500/30 overflow-x-hidden"
      style={{
        background:
          "radial-gradient(1100px 580px at 50% 28%, rgba(216, 120, 120, 0.16), transparent 75%), #060911",
      }}
    >
      {/* Top right theme toggle */}
      <div className="fixed top-4 right-4 z-50">
        <ThemeToggle />
      </div>

      <div className="w-full max-w-md flex flex-col items-center">
        {/* Brand Badge */}
        <Link
          href="/"
          className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-white/[0.04] hover:bg-white/[0.08] border border-white/[0.08] text-xs font-semibold tracking-wide text-neutral-300 hover:text-white transition-all duration-150 mb-5 shadow-sm"
        >
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src="/addons/logo.svg" alt="" width={15} height={15} />
          <span>sinss.lol</span>
        </Link>

        {/* Main Card */}
        <section
          aria-labelledby="unclaimed-heading"
          className="w-full rounded-2xl border border-white/[0.08] bg-[#0c1220]/90 backdrop-blur-xl p-6 sm:p-8 shadow-2xl shadow-black/60 text-center flex flex-col items-center transition-all"
        >
          {/* Status Indicator Pill */}
          {isHandle ? (
            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-medium mb-4">
              <span className="w-2 h-2 rounded-full bg-red-400" />
              <span>Available Handle</span>
            </div>
          ) : (
            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-medium mb-4">
              <Compass size={12} />
              <span>Page Not Found</span>
            </div>
          )}

          {/* Handle Spotlight */}
          {isHandle ? (
            <div className="w-full py-3.5 px-4 rounded-xl bg-black/40 border border-white/[0.06] mb-4 text-center overflow-hidden">
              <span
                className="font-extrabold tracking-tight text-white block truncate"
                style={{ fontSize: "clamp(1.25rem, 5vw, 1.875rem)" }}
                title={`@${cleanHandle}`}
              >
                @{cleanHandle}
              </span>
            </div>
          ) : null}

          <h1
            id="unclaimed-heading"
            className="text-lg sm:text-xl font-bold text-white mb-2 tracking-tight"
          >
            {isHandle ? "This handle is up for grabs" : "Looking for something?"}
          </h1>

          <p className="text-xs sm:text-sm text-neutral-400 mb-6 leading-relaxed max-w-sm">
            {isHandle ? (
              <>
                Reserve <strong className="text-neutral-200">@{cleanHandle}</strong> on sinss.lol to
                create your personal bio link, music showcase, and social profile.
              </>
            ) : (
              "The page or username you requested does not exist or has been moved."
            )}
          </p>

          {/* Primary Action Button */}
          <Link
            href={claimUrl}
            className="w-full h-11 px-5 rounded-xl bg-[#d67a7a] hover:bg-[#c76b6b] active:bg-[#c37777] transition-colors duration-150 text-white font-semibold text-sm flex items-center justify-center gap-2 border border-[#ecb1b1]/60 mb-3"
          >
            <Sparkles size={16} className="text-red-200 shrink-0" />
            <span className="truncate">
              {isHandle ? `Claim @${cleanHandle}` : "Claim a Handle"}
            </span>
          </Link>

          {/* Secondary Actions Grid */}
          <div className="w-full grid grid-cols-2 gap-2.5">
            <Link
              href="/"
              className="h-10 px-3 rounded-xl bg-white/[0.04] hover:bg-white/[0.08] border border-white/[0.08] hover:border-white/[0.15] text-neutral-300 hover:text-white text-xs font-semibold flex items-center justify-center gap-2 transition-all duration-150"
            >
              <Home size={14} className="shrink-0 text-neutral-400" />
              <span>Return Home</span>
            </Link>

            <button
              type="button"
              onClick={handleCopy}
              className={`h-10 px-3 rounded-xl border text-xs font-semibold flex items-center justify-center gap-2 transition-all duration-150 ${
                copied
                  ? "bg-red-500/10 border-red-500/30 text-red-400"
                  : "bg-white/[0.04] hover:bg-white/[0.08] border-white/[0.08] hover:border-white/[0.15] text-neutral-300 hover:text-white"
              }`}
            >
              {copied ? (
                <>
                  <Check size={14} className="shrink-0 text-red-400" />
                  <span>Copied!</span>
                </>
              ) : (
                <>
                  <Copy size={14} className="shrink-0 text-neutral-400" />
                  <span>Copy Link</span>
                </>
              )}
            </button>
          </div>
        </section>

        {/* Account / Session Companion Dock */}
        <section
          aria-label="Account status"
          className="w-full mt-3 rounded-xl border border-white/[0.08] bg-[#0c1220]/70 backdrop-blur-xl p-3 shadow-lg shadow-black/40 flex items-center justify-between gap-3"
        >
          {authLoading ? (
            <div className="w-full flex items-center justify-center py-1">
              <span className="w-28 h-3 rounded-full bg-white/10 animate-pulse" />
            </div>
          ) : currentUser ? (
            <>
              <div className="flex items-center gap-2.5 min-w-0">
                {currentUser.avatar_url ? (
                  <img
                    src={currentUser.avatar_url}
                    alt=""
                    className="w-7 h-7 rounded-full object-cover border border-white/10 shrink-0"
                  />
                ) : (
                  <div className="w-7 h-7 rounded-full bg-white/10 flex items-center justify-center shrink-0">
                    <User size={13} className="text-neutral-400" />
                  </div>
                )}
                <div className="min-w-0 text-left">
                  <p className="text-[10px] text-neutral-400 leading-none">Signed in as</p>
                  <p className="text-xs font-bold text-white truncate leading-snug">
                    @{currentUser.username}
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-1.5 shrink-0">
                <Link
                  href={`/${currentUser.username}`}
                  className="h-7 px-2.5 rounded-lg bg-white/[0.04] hover:bg-white/[0.08] border border-white/[0.08] text-neutral-300 hover:text-white text-xs font-medium inline-flex items-center gap-1 transition-all"
                  title="View your profile"
                >
                  <span>My Page</span>
                  <ExternalLink size={11} className="text-neutral-400" />
                </Link>
                <Link
                  href="/dashboard"
                  className="h-7 px-2.5 rounded-lg bg-red-600/20 hover:bg-red-600/30 border border-red-500/30 text-red-300 hover:text-red-100 text-xs font-medium inline-flex items-center transition-all"
                >
                  Dashboard
                </Link>
              </div>
            </>
          ) : (
            <>
              <div className="flex items-center gap-2 text-xs text-neutral-400">
                <User size={14} className="text-neutral-500 shrink-0" />
                <span>Already have a profile?</span>
              </div>
              <Link
                href="/login"
                className="h-7 px-3 rounded-lg bg-white/[0.06] hover:bg-white/[0.1] border border-white/[0.1] text-white text-xs font-semibold inline-flex items-center transition-all"
              >
                Log In
              </Link>
            </>
          )}
        </section>

        {/* Footer Support */}
        <footer className="mt-5 flex items-center justify-center gap-4 text-xs text-neutral-500">
          <a
            href={DISCORD_INVITE_URL}
            target="_blank"
            rel="noreferrer"
            className="hover:text-neutral-300 transition-colors inline-flex items-center gap-1.5"
          >
            <HelpCircle size={13} />
            <span>Community & Support</span>
          </a>
        </footer>
      </div>
    </main>
  );
}
