/**
 * Account Dropdown Component
 * Professional account menu in dashboard header
 * Inspired by Stripe, GitHub, Vercel
 */

"use client";

import { useState, Fragment } from "react";
import { Menu, Transition } from "@headlessui/react";
import { useClerk } from "@clerk/nextjs";
import type { Session } from "next-auth";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";

interface AccountDropdownProps {
  session: Session;
  lang: Lang;
  onOpenSettings?: () => void;
  onOpenBilling?: () => void;
  /** Organization role - if 'STAFF', hides billing and premium badge */
  organizationRole?: "OWNER" | "ADMIN" | "STAFF" | null;
}

export default function AccountDropdown({
  session,
  lang,
  onOpenSettings,
  onOpenBilling,
  organizationRole,
}: AccountDropdownProps) {
  const { signOut } = useClerk();
  const isAr = lang === "ar";
  const [isLoggingOut, setIsLoggingOut] = useState(false);

  // Staff members don't see billing or premium plan badge
  const isStaffMember = organizationRole === "STAFF";
  const canAccessBilling = !isStaffMember;

  const handleLogout = async () => {
    setIsLoggingOut(true);
    try {
      // Clear custom auth cookies (OTP / NextAuth users) — must use fetchWithCSRF
      await fetchWithCSRF("/api/auth/logout", { method: "POST" }).catch(
        () => {},
      );
      // Sign out of Clerk (clears Clerk cookies) and redirect to login
      await signOut({ redirectUrl: `/${lang}/clerk-login` });
    } catch (error) {
      console.error("Logout error:", error);
      // Force-navigate even if signOut fails
      window.location.href = `/${lang}/clerk-login`;
    } finally {
      setIsLoggingOut(false);
    }
  };

  // Get user initials for avatar
  const getUserInitials = (name?: string | null, email?: string | null) => {
    if (name) {
      const parts = name.split(" ");
      if (parts.length >= 2) {
        return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
      }
      return name.slice(0, 2).toUpperCase();
    }
    if (email) {
      return email.slice(0, 2).toUpperCase();
    }
    return "??";
  };

  // Get avatar color based on name
  const getAvatarColor = (name?: string | null, email?: string | null) => {
    const str = name || email || "";
    const colors = [
      "bg-emerald-500",
      "bg-blue-500",
      "bg-violet-500",
      "bg-pink-500",
      "bg-orange-500",
      "bg-cyan-500",
    ];
    const index = str.charCodeAt(0) % colors.length;
    return colors[index];
  };

  const initials = getUserInitials(session.user?.name, session.user?.email);
  const avatarColor = getAvatarColor(session.user?.name, session.user?.email);

  return (
    <Menu as="div" className="relative inline-block text-left">
      <Menu.Button className="flex items-center gap-2 rounded-lg hover:bg-slate-50 transition-colors p-1">
        {/* Avatar */}
        <div
          className={`flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full ${avatarColor} text-sm font-bold text-white shadow-md`}
        >
          {initials}
        </div>

        {/* User Info (desktop only) */}
        <div className="hidden sm:flex flex-col items-start min-w-0">
          <span className="text-sm font-medium text-slate-900 truncate max-w-[150px]">
            {session.user?.name || (isAr ? "مستخدم" : "User")}
          </span>
          <span className="text-xs text-slate-500 truncate max-w-[150px]">
            {session.user?.email}
          </span>
        </div>

        {/* Dropdown Icon */}
        <svg
          className="h-4 w-4 text-slate-400"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M19 9l-7 7-7-7"
          />
        </svg>
      </Menu.Button>

      <Transition
        as={Fragment}
        enter="transition ease-out duration-100"
        enterFrom="transform opacity-0 scale-95"
        enterTo="transform opacity-100 scale-100"
        leave="transition ease-in duration-75"
        leaveFrom="transform opacity-100 scale-100"
        leaveTo="transform opacity-0 scale-95"
      >
        <Menu.Items
          className={`absolute ${isAr ? "left-0" : "right-0"} mt-2 w-64 origin-top-right rounded-xl bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none z-50`}
        >
          <div className="p-3">
            {/* User Info Header */}
            <div className="mb-3 border-b border-slate-100 pb-3">
              <p className="text-sm font-semibold text-slate-900 truncate">
                {session.user?.name}
              </p>
              <p className="text-xs text-slate-500 truncate">
                {session.user?.email}
              </p>
              {/* Plan Badge - Hidden for staff members */}
              {!isStaffMember && (
                <div className="mt-2">
                  <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2.5 py-0.5 text-xs font-semibold text-emerald-700">
                    <span>🏆</span>
                    <span>{isAr ? "خطة مميزة" : "Premium Plan"}</span>
                  </span>
                </div>
              )}
              {/* Staff role badge */}
              {isStaffMember && (
                <div className="mt-2">
                  <span className="inline-flex items-center gap-1 rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-semibold text-slate-600">
                    <span>👤</span>
                    <span>{isAr ? "موظف" : "Staff Member"}</span>
                  </span>
                </div>
              )}
            </div>

            {/* Menu Items */}
            <div className="space-y-1">
              <Menu.Item>
                {({ active }) => (
                  <button
                    onClick={onOpenSettings}
                    className={`${
                      active ? "bg-slate-50" : ""
                    } group flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-slate-700 transition-colors`}
                  >
                    <span className="text-lg">⚙️</span>
                    <span className="font-medium">
                      {isAr ? "حسابي" : "My Account"}
                    </span>
                  </button>
                )}
              </Menu.Item>

              {/* Billing - Hidden for staff members */}
              {canAccessBilling && (
                <Menu.Item>
                  {({ active }) => (
                    <button
                      onClick={onOpenBilling}
                      className={`${
                        active ? "bg-slate-50" : ""
                      } group flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-slate-700 transition-colors`}
                    >
                      <span className="text-lg">💳</span>
                      <span className="font-medium">
                        {isAr ? "الفوترة" : "Billing"}
                      </span>
                    </button>
                  )}
                </Menu.Item>
              )}

              {/* Divider */}
              <div className="my-2 border-t border-slate-100"></div>

              <Menu.Item>
                {({ active }) => (
                  <button
                    onClick={handleLogout}
                    disabled={isLoggingOut}
                    className={`${
                      active ? "bg-red-50" : ""
                    } group flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-red-600 transition-colors disabled:opacity-50`}
                  >
                    <span className="text-lg">🚪</span>
                    <span className="font-medium">
                      {isLoggingOut
                        ? isAr
                          ? "جاري تسجيل الخروج..."
                          : "Logging out..."
                        : isAr
                          ? "تسجيل الخروج"
                          : "Logout"}
                    </span>
                  </button>
                )}
              </Menu.Item>
            </div>
          </div>
        </Menu.Items>
      </Transition>
    </Menu>
  );
}
