/**
 * Account Settings Modal
 * Professional settings interface with tabbed navigation
 * Tabs: Profile, Security (all users)
 * Owner-only tabs: Billing, Preferences, Help, Advanced
 */

"use client";

import { Fragment, useState, useEffect, useMemo } from "react";
import { Dialog, Transition, Tab } from "@headlessui/react";
import type { Lang } from "@/lib/config";

// Import tab components (will create these next)
import ProfileTab from "./settings/ProfileTab";
import SecurityTab from "./settings/SecurityTab";
import BillingTab from "./settings/BillingTab";
import PreferencesTab from "./settings/PreferencesTab";

interface AccountSettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
  lang: Lang;
  initialTab?: number;
}

export default function AccountSettingsModal({
  isOpen,
  onClose,
  lang,
  initialTab = 0,
}: AccountSettingsModalProps) {
  const isAr = lang === "ar";
  const [selectedIndex, setSelectedIndex] = useState(initialTab);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [isTeamMember, setIsTeamMember] = useState(false);
  const [loadingRole, setLoadingRole] = useState(true);

  // Fetch user's organization role to determine which tabs to show
  useEffect(() => {
    const fetchUserRole = async () => {
      try {
        const response = await fetch("/api/user/profile");
        const data = await response.json();
        if (data.success && data.organization) {
          setIsTeamMember(data.organization.isTeamMember);
        }
      } catch (err) {
        console.error("Failed to fetch user role:", err);
      } finally {
        setLoadingRole(false);
      }
    };

    if (isOpen) {
      fetchUserRole();
    }
  }, [isOpen]);

  // Reset selected tab when modal opens
  useEffect(() => {
    if (isOpen) {
      setSelectedIndex(initialTab);
    }
  }, [isOpen, initialTab]);

  // Handle modal close with unsaved changes warning
  const handleClose = () => {
    if (hasUnsavedChanges) {
      const confirmClose = window.confirm(
        isAr
          ? "لديك تغييرات غير محفوظة. هل تريد المتابعة؟"
          : "You have unsaved changes. Continue anyway?",
      );
      if (!confirmClose) return;
    }
    setHasUnsavedChanges(false);
    onClose();
  };

  // Tab configuration - filter based on user role
  const allTabs = [
    {
      id: "profile",
      name: isAr ? "الملف الشخصي" : "Profile",
      icon: "👤",
      component: ProfileTab,
      ownerOnly: false,
    },
    {
      id: "security",
      name: isAr ? "الأمان" : "Security",
      icon: "🔒",
      component: SecurityTab,
      ownerOnly: false,
    },
    {
      id: "billing",
      name: isAr ? "الفوترة" : "Billing",
      icon: "💳",
      component: BillingTab,
      ownerOnly: true,
    },
    {
      id: "preferences",
      name: isAr ? "التفضيلات" : "Preferences",
      icon: "⚙️",
      component: PreferencesTab,
      ownerOnly: true,
    },
  ];

  // Filter tabs: team members only see Profile and Security
  // While loading, show only common tabs to avoid flash of owner-only tabs
  const tabs = useMemo(() => {
    if (loadingRole || isTeamMember) {
      return allTabs.filter((tab) => !tab.ownerOnly);
    }
    return allTabs;
  }, [isTeamMember, isAr, loadingRole]);

  return (
    <Transition appear show={isOpen} as={Fragment}>
      <Dialog as="div" className="relative z-50" onClose={handleClose}>
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-5xl transform overflow-hidden rounded-2xl bg-white shadow-2xl transition-all">
                {/* Header */}
                <div className="flex items-center justify-between border-b border-slate-200 px-6 py-4">
                  <Dialog.Title className="text-xl font-bold text-slate-900">
                    {isAr ? "إعدادات الحساب" : "Account Settings"}
                  </Dialog.Title>
                  <button
                    onClick={handleClose}
                    className="rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors"
                  >
                    <svg
                      className="h-5 w-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M6 18L18 6M6 6l12 12"
                      />
                    </svg>
                  </button>
                </div>

                {/* Tab Navigation + Content */}
                <Tab.Group
                  selectedIndex={selectedIndex}
                  onChange={setSelectedIndex}
                >
                  {/* ALWAYS: Menu on LEFT, Content on RIGHT (regardless of language) */}
                  <div className="flex flex-col md:flex-row" dir="ltr">
                    {/* Sidebar Navigation - ALWAYS ON LEFT */}
                    <Tab.List className="flex flex-row md:flex-col md:w-64 border-b md:border-b-0 md:border-r border-slate-200 bg-slate-50 overflow-x-auto md:overflow-x-visible shrink-0">
                      {tabs.map((tab) => (
                        <Tab key={tab.id} as={Fragment}>
                          {({ selected }) => (
                            <button
                              className={`flex items-center gap-3 px-5 py-4 text-sm font-medium transition-all whitespace-nowrap justify-start w-full ${
                                selected
                                  ? "bg-white text-brand-green border-r-4 border-brand-green shadow-sm"
                                  : "text-slate-600 hover:bg-white/50 hover:text-slate-900"
                              }`}
                            >
                              <span className="text-lg">{tab.icon}</span>
                              <span className="font-semibold">{tab.name}</span>
                            </button>
                          )}
                        </Tab>
                      ))}
                    </Tab.List>

                    {/* Tab Panels - ALWAYS ON RIGHT */}
                    <Tab.Panels className="flex-1 p-8 max-h-[calc(100vh-200px)] overflow-y-auto bg-white">
                      {tabs.map((tab) => (
                        <Tab.Panel
                          key={tab.id}
                          className="focus:outline-none"
                          dir={isAr ? "rtl" : "ltr"}
                        >
                          <tab.component
                            lang={lang}
                            onUnsavedChanges={setHasUnsavedChanges}
                            onClose={onClose}
                          />
                        </Tab.Panel>
                      ))}
                    </Tab.Panels>
                  </div>
                </Tab.Group>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  );
}
