import React, { useMemo, useCallback, memo } from "react";
import { Link } from "react-router";
import { useInsuranceRequirementManager } from "../../../../../services/Services";
import { SettingsListView } from "../../../../../components/business/views";
import { ViewButton, UIXThemeProvider, useUIXTheme } from "../../../../../components/UIX";
import { ShieldCheckIcon } from "@heroicons/react/24/outline";
import { INSURANCE_REQUIREMENT_STATUS, INSURANCE_REQUIREMENT_STATUS_LABELS } from "../../../../../constants/Settings";
import { formatDateForDisplay } from "../../../../../services/Helpers/DateFormatter";

// Move static configuration outside component to prevent recreation
const STATUS_OPTIONS = [{ value: "", label: "All Statuses" },
        { value: INSURANCE_REQUIREMENT_STATUS.ACTIVE.toString(), label: INSURANCE_REQUIREMENT_STATUS_LABELS[INSURANCE_REQUIREMENT_STATUS.ACTIVE] },
        { value: INSURANCE_REQUIREMENT_STATUS.INACTIVE.toString(), label: INSURANCE_REQUIREMENT_STATUS_LABELS[INSURANCE_REQUIREMENT_STATUS.INACTIVE] },];

const SORT_OPTIONS = [{ value: "name,ASC", label: "Name (A-Z)" },
        { value: "name,DESC", label: "Name (Z-A)" },
        { value: "created_at,DESC", label: "Created Date (Newest)" },
        { value: "created_at,ASC", label: "Created Date (Oldest)" },];

function SettingInsuranceRequirementListPage() {
  return (
    <UIXThemeProvider>
      <SettingInsuranceRequirementListPageContent />
    </UIXThemeProvider>
  );
}

const SettingInsuranceRequirementListPageContent = memo(function SettingInsuranceRequirementListPageContent() {
  const insuranceRequirementManager = useInsuranceRequirementManager();
  const { getThemeClasses } = useUIXTheme();

  // Memoize theme classes
  const themeClasses = useMemo(
    () => ({
      linkText: getThemeClasses('text-primary'),
      linkHover: getThemeClasses('text-primary-hover'),
      badgeActiveBg: getThemeClasses('badge-active-bg'),
      badgeActiveText: getThemeClasses('badge-active-text'),
      badgeInactiveBg: getThemeClasses('badge-inactive-bg'),
      badgeInactiveText: getThemeClasses('badge-inactive-text'),
      textMuted: getThemeClasses('text-muted'),
    }),
    [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: 'name',
      label: 'Name',
      render: (value, insuranceRequirement) => (
        <Link
          to={`/admin/settings/insurance-requirement/${insuranceRequirement.id}/detail`}
          className={`${themeClasses.linkText} ${themeClasses.linkHover} font-medium`}
        >
          {insuranceRequirement.name}
        </Link>
      )
    },
    {
      key: 'description',
      label: 'Description',
      render: (value, insuranceRequirement) => (
        <div className="max-w-xs truncate">
          {insuranceRequirement.description || (
            <span className={`${themeClasses.textMuted} italic`}>—</span>
          )}
        </div>
      )
    },
    {
      key: 'status',
      label: 'Status',
      render: (value, insuranceRequirement) => {
        const isActive = insuranceRequirement.status === INSURANCE_REQUIREMENT_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}`
            }`}
          >
            {INSURANCE_REQUIREMENT_STATUS_LABELS[insuranceRequirement.status] || "Unknown"}
          </span>
        );
      }
    },
    {
      key: 'createdAt',
      label: 'Created At',
      render: (value, insuranceRequirement) => formatDateForDisplay(insuranceRequirement.createdAt) || "—"
    },
    {
      key: 'actions',
      label: 'Actions',
      align: 'right',
      render: (value, insuranceRequirement) => (
        <ViewButton basePath="/admin/settings/insurance-requirement" itemId={insuranceRequirement.id} />
      )
    }
  ], [themeClasses]);

  return (
    <SettingsListView
      entityType="insuranceRequirement"
      entityTypePlural="Insurance Requirements"
      entityIcon={ShieldCheckIcon}
      entityManager={insuranceRequirementManager}
      basePath="/admin/settings/insurance-requirement"
      createPath="/admin/settings/insurance-requirement/create"
      title="Insurance Requirements"
      subtitle="Manage insurance requirements and coverage standards"
      columns={columns}
      searchPlaceholder="Search by name or description..."
      statusOptions={STATUS_OPTIONS}
      sortOptions={SORT_OPTIONS}
      onRowClick={handleRowClick}
    />
  );
});

SettingInsuranceRequirementListPageContent.displayName = 'SettingInsuranceRequirementListPageContent';

export default SettingInsuranceRequirementListPage;