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

function SettingSkillSetCreatePage() {
  return (
    <UIXThemeProvider>
      <SettingSkillSetCreatePageContent />
    </UIXThemeProvider>
  );
}

const SettingSkillSetCreatePageContent = memo(function SettingSkillSetCreatePageContent() {
  const skillSetManager = useSkillSetManager();
  const skillCategoryManager = useSkillCategoryManager();
  const { getThemeClasses } = useUIXTheme();

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

  const [categoryOptions, setCategoryOptions] = useState([]);
  const [isLoadingOptions, setIsLoadingOptions] = useState(true);

  // Load skill category options on component mount
  useEffect(() => {
    const loadCategoryOptions = async () => {
      try {
        const options = await skillCategoryManager.getSkillCategorySelectOptions();
        setCategoryOptions(options || []);
      } catch (error) {
        if (import.meta.env.DEV) {
        console.error("Failed to load skill category options:", error);
        setCategoryOptions([]);
        }
      } finally {
        setIsLoadingOptions(false);
      }
    };

    loadCategoryOptions();
  }, [skillCategoryManager]);

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

  // Define validation rules
  const validationRules = {
    subCategory: {
      maxLength: 127,
      minLength: 1,
    },
    description: {
      maxLength: 500,
    },
  };

  // Define status options
  const statusOptions = [
    { 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] },
  ];

  // Custom info note
  const customInfoNote = (
    <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 creating.
        </span>
      </p>
    </div>
  );

  // Show loading state while category options are being fetched
  if (isLoadingOptions) {
    return (
      <div className={`min-h-screen ${getThemeClasses('bg-primary')} flex items-center justify-center`}>
        <div className="text-center">
          <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${getThemeClasses('loading-spinner')} mx-auto`}></div>
          <p className={`mt-4 ${themeClasses.textMuted}`}>Loading skill categories...</p>
        </div>
      </div>
    );
  }

  return (
    <SettingsFormView
      entityType="skillSet"
      entityTypePlural="Skill Sets"
      entityIcon={AcademicCapIcon}
      entityManager={skillSetManager}
      basePath="/admin/settings/skill-set"
      listPath="/admin/settings/skill-sets"
      mode="create"
      formFields={formFields}
      validationRules={validationRules}
      statusOptions={statusOptions}
      title="Create Skill Set"
      subtitle="Add a new skill set for facilitator capabilities and job requirements"
      customInfoNote={customInfoNote}
    />
  );
});

SettingSkillSetCreatePageContent.displayName = 'SettingSkillSetCreatePageContent';

export default SettingSkillSetCreatePage;
