'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useRef, useState } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import { ChevronUp, LifeBuoy, LogOut, Send, Settings, Shield } from 'lucide-react';
import { getRuntimeClientConfig } from '@/lib/runtime-client-config';

type ProfileAccountMenuProps = {
  displayName: string;
  avatarInitials: string;
  isAdmin: boolean;
  onOpenSettings: () => void;
  onLogout: () => void;
};

export default function ProfileAccountMenu({
  displayName,
  avatarInitials,
  isAdmin,
  onOpenSettings,
  onLogout,
}: ProfileAccountMenuProps) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement | null>(null);
  // Контакт поддержки: приоритет Telegram → email → вообще скрыть кнопку.
  const { supportEmail, supportTelegramUsername } = useMemo(() => {
    const cfg = getRuntimeClientConfig();
    return {
      supportEmail: (cfg.supportEmail || '').trim(),
      supportTelegramUsername: (cfg.supportTelegramUsername || '').trim().replace(/^@+/, ''),
    };
  }, []);

  useEffect(() => {
    if (!open) return;

    const handlePointerDown = (event: PointerEvent) => {
      if (!containerRef.current) return;
      if (containerRef.current.contains(event.target as Node)) return;
      setOpen(false);
    };

    window.addEventListener('pointerdown', handlePointerDown);
    return () => window.removeEventListener('pointerdown', handlePointerDown);
  }, [open]);

  useEffect(() => {
    if (!isAdmin) return;
    void router.prefetch('/admin');
  }, [isAdmin, router]);

  return (
    <div ref={containerRef} className="relative">
      <button
        type="button"
        onClick={() => setOpen((prev) => !prev)}
        className="group inline-flex w-full items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] p-3 text-left backdrop-blur-md transition-all duration-300 hover:border-white/20 hover:bg-white/[0.06]"
      >
        <span className="inline-flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-violet-500 to-fuchsia-500 text-sm font-semibold text-white shadow-[0_0_20px_rgba(139,92,246,0.22)]">
          {avatarInitials}
        </span>

        <span className="min-w-0 flex-1">
          <span className="block truncate text-sm font-semibold text-white">{displayName}</span>
          <span className="block truncate text-xs text-gray-500">Личный кабинет</span>
        </span>

        <ChevronUp className={`h-4 w-4 text-gray-500 transition-transform duration-300 ${open ? 'rotate-0' : 'rotate-180'}`} />
      </button>

      <AnimatePresence>
        {open ? (
          <motion.div
            initial={{ opacity: 0, y: 6, scale: 0.98 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 6, scale: 0.98 }}
            transition={{ duration: 0.18, ease: 'easeOut' }}
            className="absolute bottom-[calc(100%+10px)] left-0 z-30 w-full overflow-hidden rounded-2xl border border-white/10 bg-[#0A0A0A]/95 p-2 backdrop-blur-xl shadow-[0_20px_50px_rgba(0,0,0,0.55)]"
          >
            <div className="space-y-1">
              {isAdmin ? (
                <Link
                  href="/admin"
                  onClick={() => setOpen(false)}
                  className="inline-flex w-full items-center gap-2 rounded-lg border border-transparent px-2.5 py-2 text-xs text-gray-300 transition-all hover:border-white/10 hover:bg-white/[0.05] hover:text-white"
                >
                  <Shield className="h-3.5 w-3.5 text-gray-500" />
                  Админ-панель
                </Link>
              ) : null}

              <button
                type="button"
                onClick={() => {
                  setOpen(false);
                  onOpenSettings();
                }}
                className="inline-flex w-full items-center gap-2 rounded-lg border border-transparent px-2.5 py-2 text-xs text-gray-300 transition-all hover:border-white/10 hover:bg-white/[0.05] hover:text-white"
              >
                <Settings className="h-3.5 w-3.5 text-gray-500" />
                Настройки
              </button>

              {supportTelegramUsername ? (
                <a
                  href={`https://t.me/${supportTelegramUsername}`}
                  target="_blank"
                  rel="noreferrer"
                  onClick={() => setOpen(false)}
                  className="inline-flex w-full items-center gap-2 rounded-lg border border-transparent px-2.5 py-2 text-xs text-gray-300 transition-all hover:border-[#2AABEE]/25 hover:bg-[#2AABEE]/5 hover:text-white"
                >
                  <Send className="h-3.5 w-3.5 text-[#2AABEE]" />
                  Поддержка
                </a>
              ) : supportEmail ? (
                <a
                  href={`mailto:${supportEmail}`}
                  onClick={() => setOpen(false)}
                  className="inline-flex w-full items-center gap-2 rounded-lg border border-transparent px-2.5 py-2 text-xs text-gray-300 transition-all hover:border-violet-500/20 hover:bg-violet-500/5 hover:text-white"
                >
                  <LifeBuoy className="h-3.5 w-3.5 text-violet-300" />
                  Поддержка
                </a>
              ) : null}

              <div className="my-1 h-px bg-white/5" />

              <button
                type="button"
                onClick={() => {
                  setOpen(false);
                  onLogout();
                }}
                className="inline-flex w-full items-center gap-2 rounded-lg border border-red-500/20 bg-red-500/10 px-2.5 py-2 text-xs text-red-200 transition-all hover:bg-red-500/20"
              >
                <LogOut className="h-3.5 w-3.5" />
                Выйти
              </button>
            </div>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </div>
  );
}
