import React, { useEffect, useState, useMemo, useCallback, memo } from "react";
import { useCertificationManager, useSpecializationManager } from "../../../../../services/Services";
import { SettingsFormView } from "../../../../../components/business/views";
import { UIXThemeProvider, useUIXTheme } from "../../../../../components/UIX";
import { ClipboardDocumentCheckIcon, InformationCircleIcon } from "@heroicons/react/24/outline";
import { CERTIFICATION_STATUS, CERTIFICATION_STATUS_LABELS } from "../../../../../constants/Settings";

// Static configuration outside component
const VALIDATION_RULES = {
  specializationId: {
    required: true,
  },
  name: {
    maxLength: 100,
    minLength: 1,
  },
  description: {
    maxLength: 500,
  },
};

const STATUS_OPTIONS = [
  { value: CERTIFICATION_STATUS.ACTIVE, label: CERTIFICATION_STATUS_LABELS[CERTIFICATION_STATUS.ACTIVE] },
  { value: CERTIFICATION_STATUS.INACTIVE, label: CERTIFICATION_STATUS_LABELS[CERTIFICATION_STATUS.INACTIVE] },
];

function SettingCertificationUpdatePage() {
  return (
    <UIXThemeProvider>
      <SettingCertificationUpdatePageContent />
    </UIXThemeProvider>
  );
}

const SettingCertificationUpdatePageContent = memo(function SettingCertificationUpdatePageContent() {
  const certificationManager = useCertificationManager();
  const specializationManager = useSpecializationManager();
  const { getThemeClasses } = useUIXTheme();
  const [specializationOptions, setSpecializationOptions] = useState([]);

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

  // Memoize form fields
  const formFields = useMemo(() => [
    {
      name: "specializationId",
      label: "Specialization",
      type: "select",
      placeholder: "Select specialization",
      required: true,
      description: "Select the specialization for this certification",
      // Will be populated by useEffect
      options: specializationOptions
    },
    {
      name: "name",
      label: "Certification Name",
      type: "text",
      placeholder: "Enter certification name (e.g., Safety Certification, Technical Certification)",
      required: true,
      maxLength: 100,
    },
    {
      name: "description",
      label: "Description",
      type: "textarea",
      placeholder: "Enter a detailed description of this certification (optional)",
      rows: 4,
      maxLength: 500,
    },
    {
      name: "status",
      label: "Status",
      type: "select",
      required: true,
    }
  ], [specializationOptions]);

  // 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> Certifications are used to track professional qualifications and credentials.
          Changes will be visible immediately after updating.
        </span>
      </p>
    </div>
  ), [themeClasses]);

  // Memoize load specialization options
  const loadSpecializationOptions = useCallback(async () => {
    try {
      if (import.meta.env.DEV) {
        console.log("CertificationUpdate: Loading specialization options...");
      }

      const options = await specializationManager.getSpecializationSelectOptions();

      if (import.meta.env.DEV) {
        console.log("CertificationUpdate: Specialization options received:", options);
      }

      if (options && Array.isArray(options)) {
        setSpecializationOptions(options);
        if (import.meta.env.DEV) {
          console.log("CertificationUpdate: Specialization 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)) {
          setSpecializationOptions(optionsArray);
        } else {
          if (import.meta.env.DEV) {
            console.warn("CertificationUpdate: Options is not an array:", options);
          }
          throw new Error("Invalid options format received");
        }
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("CertificationUpdate: Failed to load specializations:", error);
      }
      // Set empty array on error
      setSpecializationOptions([]);
    }
  }, [specializationManager]);

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

  return (
    <SettingsFormView
      entityType="certification"
      entityTypePlural="Certifications"
      entityIcon={ClipboardDocumentCheckIcon}
      entityManager={certificationManager}
      basePath="/admin/settings/certification"
      listPath="/admin/settings/certification"
      mode="update"
      formFields={formFields}
      validationRules={VALIDATION_RULES}
      statusOptions={STATUS_OPTIONS}
      title="Edit Certification"
      subtitle="Update certification information and details"
      customInfoNote={customInfoNote}
    />
  );
});
SettingCertificationUpdatePageContent.displayName = 'SettingCertificationUpdatePageContent';

export default SettingCertificationUpdatePage;