import React, { useState, useEffect, useMemo, useCallback, memo } from "react";
import { useSkillSetManager, useSkillCategoryManager } from "../../../../../services/Services";
import { SettingsFormView } from "../../../../../components/business/views";
import { UIXThemeProvider, useUIXTheme } from "../../../../../components/UIX";
import { CogIcon, InformationCircleIcon } from "@heroicons/react/24/outline";
import { SKILL_SET_STATUS, SKILL_SET_STATUS_LABELS } from "../../../../../constants/Settings";

// Static configuration outside component
const VALIDATION_RULES = {
  subCategory: {
    maxLength: 127,
    minLength: 1,
  },
  description: {
    maxLength: 500,
  },
};

const STATUS_OPTIONS = [
  { value: SKILL_SET_STATUS.ACTIVE, label: SKILL_SET_STATUS_LABELS[SKILL_SET_STATUS.ACTIVE] },
  { value: SKILL_SET_STATUS.INACTIVE, label: SKILL_SET_STATUS_LABELS[SKILL_SET_STATUS.INACTIVE] },
];

function SettingSkillSetUpdatePage() {
  return (
    <UIXThemeProvider>
      <SettingSkillSetUpdatePageContent />
    </UIXThemeProvider>
  );
}

const SettingSkillSetUpdatePageContent = memo(function SettingSkillSetUpdatePageContent() {
  const skillSetManager = useSkillSetManager();
  const skillCategoryManager = useSkillCategoryManager();
  const { getThemeClasses } = useUIXTheme();
  const [categoryOptions, setCategoryOptions] = useState([]);

  // Memoize theme classes
  const themeClasses = useMemo(
    () => ({
      alertInfoBg: getThemeClasses('alert-info-bg'),
      borderPrimary: getThemeClasses('border-primary'),
      textPrimary: getThemeClasses('text-primary'),
    }),
    [getThemeClasses],
  );

  // Memoize load category options
  const loadCategoryOptions = useCallback(async () => {
    try {
      if (import.meta.env.DEV) {
        console.log("SkillSetUpdate: Loading skill category options...");
      }

      const options = await skillCategoryManager.getSkillCategorySelectOptions();

      if (import.meta.env.DEV) {
        console.log("SkillSetUpdate: Skill category options received:", options);
      }

      if (options && Array.isArray(options)) {
        setCategoryOptions(options);
        if (import.meta.env.DEV) {
          console.log("SkillSetUpdate: Skill category options set successfully");
        }
      } else {
        // Try to extract from response if it's wrapped
        const optionsArray = options?.results || options?.data || options?.options || [];
        if (Array.isArray(optionsArray)) {
          setCategoryOptions(optionsArray);
        } else {
          if (import.meta.env.DEV) {
            console.warn("SkillSetUpdate: Options is not an array:", options);
          }
          throw new Error("Invalid options format received");
        }
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("SkillSetUpdate: Failed to load skill categories:", error);
      }
      // Set empty array on error
      setCategoryOptions([]);
    }
  }, [skillCategoryManager]);

  // Load category options on component mount
  useEffect(() => {
    loadCategoryOptions();
  }, [loadCategoryOptions]);

  // Memoize form fields
  const formFields = useMemo(() => [
    {
      name: "category",
      label: "Category",
      type: "select",
      placeholder: "Select category",
      required: true,
      description: "Select the category for this skill set",
      // Will be populated by useEffect
      options: categoryOptions
    },
    {
      name: "subCategory",
      label: "Sub-Category",
      type: "text",
      placeholder: "Enter sub-category (e.g., Residential Wiring, Commercial Installation)",
      required: true,
      maxLength: 127,
      autoComplete: "off",
    },
    {
      name: "description",
      label: "Description",
      type: "textarea",
      placeholder: "Provide additional context or requirements (optional)",
      rows: 4,
      maxLength: 500,
      description: "Optional description to provide additional context for this skill set",
      autoComplete: "off",
    },
    {
      name: "status",
      label: "Status",
      type: "select",
      required: true,
    }
  ], [categoryOptions]);

  // Memoize custom info note
  const customInfoNote = useMemo(() => (
    <div className={`p-4 ${themeClasses.alertInfoBg} border ${themeClasses.borderPrimary} rounded-lg`}>
      <p className={`text-sm ${themeClasses.textPrimary} flex items-start`}>
        <InformationCircleIcon className="w-5 h-5 mr-2 flex-shrink-0 mt-0.5" />
        <span>
          <strong>Note:</strong> Skill sets are used for facilitator capabilities and job requirements.
          Changes will be visible immediately after updating.
        </span>
      </p>
    </div>
  ), [themeClasses]);

  return (
    <SettingsFormView
      entityType="skillSet"
      entityTypePlural="Skill Sets"
      entityIcon={CogIcon}
      entityManager={skillSetManager}
      basePath="/admin/settings/skill-set"
      listPath="/admin/settings/skill-sets"
      mode="update"
      formFields={formFields}
      validationRules={VALIDATION_RULES}
      statusOptions={STATUS_OPTIONS}
      title="Edit Skill Set"
      subtitle="Update skill set details and configuration"
      customInfoNote={customInfoNote}
    />
  );
});
SettingSkillSetUpdatePageContent.displayName = 'SettingSkillSetUpdatePageContent';

export default SettingSkillSetUpdatePage;