import React, { useMemo, useCallback, memo, useState, useEffect } from "react";
import { Link } from "react-router";
import { useSkillSetManager, useSkillCategoryManager } from "../../../../../services/Services";
import { SettingsListView } from "../../../../../components/business/views";
import { ViewButton, UIXThemeProvider, useUIXTheme } from "../../../../../components/UIX";
import { AcademicCapIcon } from "@heroicons/react/24/outline";
import { SKILL_SET_STATUS, SKILL_SET_STATUS_LABELS } from "../../../../../constants/Settings";
import { formatDateForDisplay } from "../../../../../services/Helpers/DateFormatter";

function SettingSkillSetListPage() {
  return (
    <UIXThemeProvider>
      <SettingSkillSetListPageContent />
    </UIXThemeProvider>
  );
}

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

  // State for category options
  const [categoryOptions, setCategoryOptions] = useState([]);

  // Load skill category options for ID-to-label mapping
  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([]);
        }
      }
    };

    loadCategoryOptions();
  }, [skillCategoryManager]);

  // Helper function to get category label by ID
  const getCategoryLabel = useCallback((categoryId) => {
    if (!categoryId || !categoryOptions.length) return categoryId;
    const category = categoryOptions.find(option => option.value === categoryId);
    return category ? category.label : categoryId;
  }, [categoryOptions]);

  // Memoize theme classes
  const themeClasses = useMemo(
    () => ({
      linkText: getThemeClasses('text-primary'),
      linkHover: getThemeClasses('text-primary-hover'),
      textMuted: getThemeClasses('text-muted'),
      badgeActiveBg: getThemeClasses('badge-active-bg'),
      badgeActiveText: getThemeClasses('badge-active-text'),
      badgeInactiveBg: getThemeClasses('badge-inactive-bg'),
      badgeInactiveText: getThemeClasses('badge-inactive-text'),
    }),
    [getThemeClasses],
  );

  // Memoize row click handler
  const handleRowClick = useCallback((item) => {
    return `${window.location.pathname}/${item.id}/detail`;
  }, []);

  // Memoize table columns with theme-aware styling
  const columns = useMemo(() => [
    {
      key: 'category',
      label: 'Category',
      render: (value, skillSet) => (
        <Link
          to={`/admin/settings/skill-set/${skillSet.id}/detail`}
          className={`${themeClasses.linkText} ${themeClasses.linkHover} font-medium`}
        >
          {getCategoryLabel(skillSet.category)}
        </Link>
      )
    },
    {
      key: 'subCategory',
      label: 'Sub-Category',
      render: (value, skillSet) => (
        <div className="max-w-xs truncate">
          {skillSet.subCategory || (
            <span className={`${themeClasses.textMuted} italic`}>—</span>
          )}
        </div>
      )
    },
    {
      key: 'status',
      label: 'Status',
      render: (value, skillSet) => {
        const isActive = skillSet.status === SKILL_SET_STATUS.ACTIVE;
        return (
          <span
            className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
              isActive ? `${themeClasses.badgeActiveBg} ${themeClasses.badgeActiveText}` : `${themeClasses.badgeInactiveBg} ${themeClasses.badgeInactiveText}`
            }`}
          >
            {SKILL_SET_STATUS_LABELS[skillSet.status] || "Unknown"}
          </span>
        );
      }
    },
    {
      key: 'createdAt',
      label: 'Created At',
      render: (value, skillSet) => formatDateForDisplay(skillSet.createdAt) || "—"
    },
    {
      key: 'actions',
      label: 'Actions',
      align: 'right',
      render: (value, skillSet) => (
        <ViewButton basePath="/admin/settings/skill-set" itemId={skillSet.id} />
      )
    }
  ], [themeClasses, getCategoryLabel]);

  // Define status options
  const statusOptions = [
    { value: "", label: "All Statuses" },
    { value: SKILL_SET_STATUS.ACTIVE.toString(), label: SKILL_SET_STATUS_LABELS[SKILL_SET_STATUS.ACTIVE] },
    { value: SKILL_SET_STATUS.INACTIVE.toString(), label: SKILL_SET_STATUS_LABELS[SKILL_SET_STATUS.INACTIVE] },
  ];

  // Define sort options
  const sortOptions = [
    { value: "category,ASC", label: "Category (A-Z)" },
    { value: "category,DESC", label: "Category (Z-A)" },
    { value: "sub_category,ASC", label: "Sub-Category (A-Z)" },
    { value: "sub_category,DESC", label: "Sub-Category (Z-A)" },
    { value: "created_at,DESC", label: "Created Date (Newest)" },
    { value: "created_at,ASC", label: "Created Date (Oldest)" },
  ];

  return (
    <SettingsListView
      entityType="skillSet"
      entityTypePlural="Skill Sets"
      entityIcon={AcademicCapIcon}
      entityManager={skillSetManager}
      basePath="/admin/settings/skill-set"
      createPath="/admin/settings/skill-set/create"
      title="Skill Sets"
      subtitle="Manage professional skills and competency categories"
      columns={columns}
      searchPlaceholder="Search by category or sub-category..."
      statusOptions={statusOptions}
      sortOptions={sortOptions}
      onRowClick={handleRowClick}
    />
  );
});

SettingSkillSetListPageContent.displayName = 'SettingSkillSetListPageContent';

export default SettingSkillSetListPage;