// File Path: monorepo/web/frontend/src/pages/Admin/Setting/Page.jsx

import React, { useState, useEffect, useCallback, useMemo, memo } from "react";
import { Link, useNavigate } from "react-router";
import {
  useAccountManager,
  useTenantManager,
} from "../../../services/Services";
import {
  Breadcrumb,
  PageHeader,
  Alert,
  UIXThemeProvider,
  ThemeSelector,
  UIX_THEMES,
  useUIXTheme,
} from "../../../components/UIX";
import { EXECUTIVE_ROLE_ID } from "../../../constants/Roles";
import {
  HomeIcon,
  Cog6ToothIcon,
  NewspaperIcon,
  AcademicCapIcon,
  TagIcon,
  MegaphoneIcon,
  ScaleIcon,
  CreditCardIcon,
  UserMinusIcon,
  TruckIcon,
  PhoneIcon,
  BanknotesIcon,
  BuildingOfficeIcon,
  BuildingOffice2Icon,
  StarIcon,
  ClipboardDocumentCheckIcon,
  CalendarDaysIcon,
  ArrowRightIcon,
  ChevronRightIcon,
  XMarkIcon,
  CheckIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";

// Move static theme configuration objects outside component to prevent recreation
const THEME_GRADIENTS = {
  blue: "linear-gradient(135deg, #172554 0%, #1e3a8a 100%)",
  red: "linear-gradient(135deg, #7f1d1d 0%, #dc2626 100%)",
  purple: "linear-gradient(135deg, #581c87 0%, #7c3aed 100%)",
  green: "linear-gradient(135deg, #14532d 0%, #16a34a 100%)",
  charcoal: "linear-gradient(135deg, #0f172a 0%, #475569 100%)",
};

const THEME_HOVER_COLORS = {
  blue: "group-hover:text-blue-600",
  red: "group-hover:text-red-600",
  purple: "group-hover:text-purple-600",
  green: "group-hover:text-green-600",
  charcoal: "group-hover:text-slate-600",
};

const THEME_BUTTON_GRADIENTS = {
  blue: "bg-gradient-to-r from-gray-50 to-blue-50 hover:from-blue-50 hover:to-blue-100",
  red: "bg-gradient-to-r from-gray-50 to-red-50 hover:from-red-50 hover:to-red-100",
  purple:
    "bg-gradient-to-r from-gray-50 to-purple-50 hover:from-purple-50 hover:to-purple-100",
  green:
    "bg-gradient-to-r from-gray-50 to-green-50 hover:from-green-50 hover:to-green-100",
  charcoal:
    "bg-gradient-to-r from-gray-50 to-slate-50 hover:from-slate-50 hover:to-slate-100",
};

const THEME_BUTTON_TEXT_COLORS = {
  blue: "text-gray-700 hover:text-blue-950",
  red: "text-gray-700 hover:text-red-950",
  purple: "text-gray-700 hover:text-purple-950",
  green: "text-gray-700 hover:text-green-950",
  charcoal: "text-gray-700 hover:text-slate-950",
};

// Move static settings items outside component
const SETTINGS_ITEMS = [
  {
    title: "Office News",
    description: "Modify office news items.",
    icon: NewspaperIcon,
    path: "/admin/settings/bulletins",
  },
  {
    title: "Skill Sets",
    description: "Modify the skill sets.",
    icon: AcademicCapIcon,
    path: "/admin/settings/skill-sets",
  },
  {
    title: "Tags",
    description: "Manage system tags and labels.",
    icon: TagIcon,
    path: "/admin/settings/tags",
  },
  {
    title: "Facilitator Away Logs",
    description: "Modify facilitator away logs.",
    icon: MegaphoneIcon,
    path: "/admin/settings/facilitator-away-logs",
  },
  {
    title: "Speaker Away Logs",
    description: "Modify speaker away logs.",
    icon: MegaphoneIcon,
    path: "/admin/settings/speaker-away-logs",
  },
  {
    title: "How did you hear?",
    description: "List how users discovered us and referral sources.",
    icon: PhoneIcon,
    path: "/admin/settings/how-hear-about-us-items",
  },
  {
    title: "Specializations",
    description: "Manage facilitator specializations and expertise areas.",
    icon: StarIcon,
    path: "/admin/settings/specializations",
  },
  {
    title: "Certifications",
    description: "Manage required certifications and qualifications.",
    icon: ClipboardDocumentCheckIcon,
    path: "/admin/settings/certification",
  },
  {
    title: "Event Categories",
    description: "Manage event categories and classification types.",
    icon: CalendarDaysIcon,
    path: "/admin/settings/event-categories",
  },
  {
    title: "Skill Categories",
    description: "Manage skill categories and classification types.",
    icon: AcademicCapIcon,
    path: "/admin/settings/skill-categories",
  },
  {
    title: "Insurance Requirements",
    description: "Modify insurance settings.",
    icon: ScaleIcon,
    path: "/admin/settings/insurance-requirements",
    requiredRoles: [EXECUTIVE_ROLE_ID], // Root only
  },
  {
    title: "Service Fees",
    description: "Modify service fee settings.",
    icon: CreditCardIcon,
    path: "/admin/settings/service-fees",
    requiredRoles: [EXECUTIVE_ROLE_ID], // Root only
  },
  {
    title: "Deactivated Clients",
    description: "Modify inactive customers.",
    icon: UserMinusIcon,
    path: "/admin/settings/inactive-clients",
    requiredRoles: [EXECUTIVE_ROLE_ID], // Root only
  },
  {
    title: "Vehicle Types",
    description: "Modify vehicle types for facilitators.",
    icon: TruckIcon,
    path: "/admin/settings/vehicle-types",
    requiredRoles: [EXECUTIVE_ROLE_ID], // Root only
  },
  {
    title: "National Occupational Classification",
    description: "Search NOC's in the system.",
    icon: BuildingOfficeIcon,
    path: "/admin/settings/noc/search",
    requiredRoles: [EXECUTIVE_ROLE_ID], // Root only
  },
  {
    title: "North America Industry Classification System",
    description: "Search NAICS's in the system.",
    icon: BuildingOffice2Icon,
    path: "/admin/settings/naics/search",
    requiredRoles: [EXECUTIVE_ROLE_ID], // Root only
  },
  {
    title: "Tax Settings",
    description: "Change how tax gets applied system wide.",
    icon: BanknotesIcon,
    path: "/admin/settings/tax",
    requiredRoles: [EXECUTIVE_ROLE_ID], // Root only
  },
];

const BREADCRUMB_ITEMS = [
  {
    label: "Dashboard",
    to: "/admin/dashboard",
    icon: HomeIcon,
  },
  {
    label: "Settings",
    icon: Cog6ToothIcon,
    isActive: true,
  },
];

function SettingDashboardPage() {
  return (
    <UIXThemeProvider>
      <SettingDashboardPageContent />
    </UIXThemeProvider>
  );
}

const SettingDashboardPageContent = memo(
  function SettingDashboardPageContent() {
    const accountManager = useAccountManager();
    const tenantManager = useTenantManager();
    const navigate = useNavigate();
    const { getThemeClasses, currentTheme } = useUIXTheme();

    const [errors, setErrors] = useState({});
    const [isLoading, setIsLoading] = useState(false);
    const [currentUser, setCurrentUser] = useState(null);
    const [tenant, setTenant] = useState(null);
    const [showTaxSettingModal, setShowTaxSettingModal] = useState(false);

    // Memoize theme classes to prevent multiple calls on each render
    const themeClasses = useMemo(
      () => ({
        bgGradientPrimary: getThemeClasses("bg-gradient-primary"),
        loadingSpinner: getThemeClasses("loading-spinner"),
      }),
      [getThemeClasses],
    );

    // Memoize handlers
    const onUnauthorized = useCallback(() => {
      navigate("/login?unauthorized=true");
    }, [navigate]);

    const fetchCurrentUser = useCallback(async () => {
      try {
        const userData = await accountManager.getAccountDetail(onUnauthorized);
        if (import.meta.env.DEV) {
          console.log("Settings: Current user data:", userData);
          console.log(
            "Settings: User role:",
            userData.role,
            "Type:",
            typeof userData.role,
          );
        }
        setCurrentUser(userData);
        return userData;
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Settings: Failed to fetch current user:", error);
        }
        setErrors({ user: error.message || "Failed to load user details" });
        throw error;
      }
    }, [accountManager, onUnauthorized]);

    const fetchTenantDetail = useCallback(
      async (tenantId) => {
        try {
          const tenantData = await tenantManager.getTenantDetail(
            tenantId,
            onUnauthorized,
          );
          setTenant(tenantData);
          if (import.meta.env.DEV) {
            console.log("Settings: Tenant detail fetched successfully:", {
              id: tenantData.id,
              name: tenantData.name,
            });
          }
        } catch (error) {
          if (import.meta.env.DEV) {
            console.error("Settings: Failed to fetch tenant:", error);
          }
          setErrors({
            tenant: error.message || "Failed to load tenant details",
          });
        }
      },
      [tenantManager, onUnauthorized],
    );

    // Memoize error handlers
    const handleCloseUserError = useCallback(() => {
      setErrors((prev) => ({ ...prev, user: null }));
    }, []);

    const handleCloseTenantError = useCallback(() => {
      setErrors((prev) => ({ ...prev, tenant: null }));
    }, []);

    const handleCloseThemeError = useCallback(() => {
      setErrors((prev) => ({ ...prev, theme: null }));
    }, []);

    const handleTaxSettingSuccess = useCallback(() => {
      if (import.meta.env.DEV) {
        console.log("Tax settings updated successfully");
      }
      // Optionally refresh tenant data
      if (currentUser && currentUser.tenantId) {
        fetchTenantDetail(currentUser.tenantId);
      }
    }, [currentUser, fetchTenantDetail]);

    const handleThemeChange = useCallback(async (newTheme) => {
      try {
        if (import.meta.env.DEV) {
          console.log("Settings: Saving theme preference to backend:", newTheme);
        }
        await accountManager.updateThemePreference(newTheme, onUnauthorized);
        if (import.meta.env.DEV) {
          console.log("Settings: Theme preference saved successfully");
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Settings: Failed to save theme preference:", error);
        }
        // Show error to user but don't block theme change in UI
        setErrors((prev) => ({
          ...prev,
          theme: "Theme changed locally but failed to save to your profile. Please try again later.",
        }));
      }
    }, [accountManager, onUnauthorized]);

    useEffect(() => {
      let mounted = true;

      const initializeData = async () => {
        if (!mounted) return;

        setIsLoading(true);
        setErrors({});

        try {
          // First get current user
          const userData = await fetchCurrentUser();

          if (!mounted) return;

          // Then get tenant details using user's tenant ID
          if (userData && userData.tenantId) {
            await fetchTenantDetail(userData.tenantId);
          } else {
            setErrors({ tenant: "User does not have a valid tenant ID" });
          }
        } catch (error) {
          if (import.meta.env.DEV) {
            console.error("Settings: Failed to initialize data:", error);
          }
        } finally {
          if (mounted) {
            setIsLoading(false);
          }
        }
      };

      window.scrollTo(0, 0);
      initializeData();

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

    // Memoize settings cards rendering with role-based filtering
    const settingsCards = useMemo(() => {
      if (import.meta.env.DEV) {
        console.log("Settings: Filtering cards. Current user:", currentUser);
        console.log("Settings: Current user role:", currentUser?.role);
        console.log("Settings: EXECUTIVE_ROLE_ID:", EXECUTIVE_ROLE_ID);
      }

      // Filter items based on user's role
      const filteredItems = SETTINGS_ITEMS.filter((item) => {
        // If no role restriction specified, show to everyone
        if (!item.requiredRoles || item.requiredRoles.length === 0) {
          return true;
        }
        // Check if current user's role is in the required roles
        const hasAccess =
          currentUser && item.requiredRoles.includes(currentUser.role);
        if (import.meta.env.DEV) {
          console.log(
            `Settings: Item "${item.title}" - Required roles:`,
            item.requiredRoles,
            "User role:",
            currentUser?.role,
            "Has access:",
            hasAccess,
          );
        }
        return hasAccess;
      });

      if (import.meta.env.DEV) {
        console.log(
          "Settings: Filtered items count:",
          filteredItems.length,
          "out of",
          SETTINGS_ITEMS.length,
        );
      }

      return filteredItems.map((item, index) => {
        const IconComponent = item.icon;
        return (
          <div
            key={index}
            className="group bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden hover:shadow-xl hover:-translate-y-1 transition-all duration-300 flex flex-col"
          >
            {/* Icon Header with theme-aware gradient */}
            <div
              className="p-6 text-white flex justify-center relative overflow-hidden"
              style={{ background: THEME_GRADIENTS[currentTheme] }}
            >
              <div className="absolute inset-0 bg-white opacity-10 transform -skew-y-6 translate-y-12"></div>
              <IconComponent className="w-12 h-12 relative z-10 group-hover:scale-110 transition-transform duration-300" />
            </div>

            {/* Content */}
            <div className="p-5 flex-grow flex flex-col">
              <h3
                className={`text-lg font-bold text-gray-900 mb-2 transition-colors duration-200 ${THEME_HOVER_COLORS[currentTheme]}`}
              >
                {item.title}
              </h3>
              <p className="text-sm text-gray-600 line-clamp-3 mb-4 flex-grow">
                {item.description}
              </p>
            </div>

            {/* Footer Button */}
            <div className="border-t border-gray-100">
              {item.path ? (
                <Link
                  to={item.path}
                  className={`w-full p-4 ${THEME_BUTTON_GRADIENTS[currentTheme]} flex items-center justify-between ${THEME_BUTTON_TEXT_COLORS[currentTheme]} transition-all duration-200 font-medium`}
                >
                  <span>Manage Settings</span>
                  <ChevronRightIcon className="w-5 h-5 group-hover:translate-x-1 transition-transform duration-200" />
                </Link>
              ) : (
                <button
                  onClick={item.action}
                  className={`w-full p-4 ${THEME_BUTTON_GRADIENTS[currentTheme]} flex items-center justify-between ${THEME_BUTTON_TEXT_COLORS[currentTheme]} transition-all duration-200 font-medium`}
                >
                  <span>Manage Settings</span>
                  <ChevronRightIcon className="w-5 h-5 group-hover:translate-x-1 transition-transform duration-200" />
                </button>
              )}
            </div>
          </div>
        );
      });
    }, [currentTheme, currentUser]);

    if (isLoading) {
      return (
        <div
          className={`min-h-screen bg-gradient-to-br from-gray-50 via-white ${themeClasses.bgGradientPrimary} flex items-center justify-center px-4`}
        >
          <div className="text-center">
            <div
              className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.loadingSpinner} mx-auto`}
            ></div>
            <p className="mt-4 text-gray-600 text-sm sm:text-base">
              Loading Settings...
            </p>
          </div>
        </div>
      );
    }

    return (
      <div
        className={`min-h-screen bg-gradient-to-br from-gray-50 via-white ${themeClasses.bgGradientPrimary}`}
      >
        {/* Decorative background elements */}
        <div className="fixed inset-0 overflow-hidden pointer-events-none">
          <div className="absolute -top-40 -right-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob"></div>
          <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-yellow-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000"></div>
          <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000"></div>
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
          {/* Breadcrumb */}
          <Breadcrumb items={BREADCRUMB_ITEMS} />

          <PageHeader
            icon={Cog6ToothIcon}
            title="System Settings"
            subtitle="Configure and manage your system settings. Click on any option below to modify specific settings."
          />

          {/* Theme Selector */}
          <div className="mb-8 bg-white shadow-lg rounded-xl p-6 border border-gray-100">
            <ThemeSelector onThemeChange={handleThemeChange} />
          </div>

          {/* Error Alerts */}
          {errors.user && (
            <Alert
              type="error"
              message={errors.user}
              onClose={handleCloseUserError}
              className="mb-6"
            />
          )}
          {errors.tenant && (
            <Alert
              type="error"
              message={errors.tenant}
              onClose={handleCloseTenantError}
              className="mb-6"
            />
          )}
          {errors.theme && (
            <Alert
              type="warning"
              message={errors.theme}
              onClose={handleCloseThemeError}
              className="mb-6"
            />
          )}

          {/* Settings Grid Container */}
          <div className="bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100 hover:shadow-2xl transition-shadow duration-300">
            <div className="p-6 sm:p-8">
              {/* Settings Grid - Optimized for all screen sizes */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                {settingsCards}
              </div>
            </div>
          </div>
        </div>

        {/* Tax Settings Modal */}
        {tenant && (
          <TaxSettingModal
            currentUser={currentUser}
            tenant={tenant}
            showModal={showTaxSettingModal}
            setShowModal={setShowTaxSettingModal}
            onSuccess={handleTaxSettingSuccess}
          />
        )}
      </div>
    );
  },
);

// Set display name for React DevTools
SettingDashboardPageContent.displayName = "SettingDashboardPageContent";

// Tax Setting Modal Component - Performance Optimized
const TaxSettingModal = memo(function TaxSettingModal({
  currentUser,
  tenant,
  showModal,
  setShowModal,
  onSuccess,
}) {
  const tenantManager = useTenantManager();
  const { getThemeClasses } = useUIXTheme();
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [taxRate, setTaxRate] = useState(tenant?.taxRate || 0);

  // Memoize theme classes
  const themeClasses = useMemo(
    () => ({
      focusRing: getThemeClasses("focus-ring"),
      focusBorder: getThemeClasses("focus-border"),
    }),
    [getThemeClasses],
  );

  // Memoize handlers
  const onUnauthorized = useCallback(() => {
    window.location.href = "/login?unauthorized=true";
  }, []);

  const handleSave = useCallback(async () => {
    setIsLoading(true);
    setErrors({});

    try {
      const taxRateData = {
        tenantId: currentUser.tenantId,
        taxRate: parseFloat(taxRate),
      };

      await tenantManager.updateTaxRate(taxRateData, onUnauthorized);

      onSuccess();
      setShowModal(false);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Failed to update tax rate:", error);
      }
      setErrors({ submit: error.message || "Failed to update tax rate" });
    } finally {
      setIsLoading(false);
    }
  }, [
    currentUser,
    taxRate,
    tenantManager,
    onUnauthorized,
    onSuccess,
    setShowModal,
  ]);

  const handleClose = useCallback(() => {
    setErrors({});
    setTaxRate(tenant?.taxRate || 0);
    setShowModal(false);
  }, [tenant, setShowModal]);

  const handleTaxRateChange = useCallback((e) => {
    setTaxRate(e.target.value);
  }, []);

  useEffect(() => {
    if (showModal && tenant) {
      setTaxRate(tenant.taxRate || 0);
    }
  }, [showModal, tenant]);

  if (!showModal) return null;

  return (
    <>
      {/* Modal Backdrop */}
      <div
        className="fixed inset-0 bg-black bg-opacity-50 z-40 transition-opacity"
        onClick={handleClose}
      />

      {/* Modal Content - Responsive sizing */}
      <div className="fixed inset-0 z-50 overflow-y-auto">
        <div className="flex min-h-full items-center justify-center p-4">
          <div className="relative bg-white rounded-lg shadow-xl w-full max-w-[90vw] sm:max-w-md">
            {/* Modal Header */}
            <div className="flex items-center justify-between p-4 sm:p-5 border-b border-gray-200">
              <div className="flex items-center">
                <BanknotesIcon className="w-5 h-5 sm:w-6 sm:h-6 text-gray-700 mr-2" />
                <h3 className="text-base sm:text-lg font-semibold text-gray-900">
                  Tax Settings
                </h3>
              </div>
              <button
                onClick={handleClose}
                className={`text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 ${themeClasses.focusRing} rounded-lg p-1`}
              >
                <XMarkIcon className="w-4 h-4 sm:w-5 sm:h-5" />
              </button>
            </div>

            {/* Modal Body */}
            <div className="p-4 sm:p-6">
              {errors.submit && (
                <div className="mb-3 sm:mb-4 p-3 sm:p-4 bg-red-50 border border-red-200 rounded-lg flex items-start">
                  <ExclamationTriangleIcon className="w-4 h-4 sm:w-5 sm:h-5 text-red-600 mr-2 flex-shrink-0 mt-0.5" />
                  <span className="text-red-800 text-xs sm:text-sm">
                    {errors.submit}
                  </span>
                </div>
              )}

              <div>
                <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2">
                  Tax Rate
                </label>
                <input
                  type="number"
                  step="0.01"
                  min="0"
                  max="100"
                  value={taxRate}
                  onChange={handleTaxRateChange}
                  placeholder="Enter tax rate"
                  disabled={isLoading}
                  className={`w-full px-2.5 sm:px-3 py-1.5 sm:py-2 border border-gray-300 rounded-lg focus:ring-2 ${themeClasses.focusRing} ${themeClasses.focusBorder} disabled:bg-gray-100 disabled:cursor-not-allowed text-xs sm:text-sm`}
                />
                <p className="mt-1 text-[10px] sm:text-xs text-gray-500">
                  Tax rate applied to every order if the user has a tax account
                </p>
              </div>
            </div>

            {/* Modal Footer */}
            <div className="flex justify-end gap-2 sm:gap-3 px-4 sm:px-6 py-3 sm:py-4 border-t border-gray-200">
              <button
                onClick={handleClose}
                disabled={isLoading}
                className={`px-3 sm:px-4 py-1.5 sm:py-2 text-xs sm:text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 ${themeClasses.focusRing} disabled:opacity-50 disabled:cursor-not-allowed`}
              >
                Cancel
              </button>
              <button
                onClick={handleSave}
                disabled={isLoading}
                className={`px-3 sm:px-4 py-1.5 sm:py-2 text-xs sm:text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed flex items-center`}
              >
                {isLoading ? (
                  <>
                    <div className="animate-spin rounded-full h-3 w-3 sm:h-4 sm:w-4 border-b-2 border-white mr-1.5 sm:mr-2"></div>
                    Saving...
                  </>
                ) : (
                  <>
                    <CheckIcon className="w-3 h-3 sm:w-4 sm:h-4 mr-1" />
                    Save
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
});

// Set display name for React DevTools
TaxSettingModal.displayName = "TaxSettingModal";

export default SettingDashboardPage;
