import React, { useMemo, memo } from "react";
import { useServiceFeeManager } from "../../../../../services/Services";
import { SettingsFormView } from "../../../../../components/business/views";
import { UIXThemeProvider, useUIXTheme } from "../../../../../components/UIX";
import { CreditCardIcon, InformationCircleIcon, PercentBadgeIcon } from "@heroicons/react/24/outline";
import { SERVICE_FEE_STATUS, SERVICE_FEE_STATUS_LABELS } from "../../../../../constants/Settings";

// Move static config outside component
const FORM_FIELDS = [
  {
    name: "name",
    label: "Service Fee Name",
    type: "text",
    placeholder: "Enter service fee name",
    required: true,
    maxLength: 127,
    defaultValue: "",
    autoComplete: "off",
  },
  {
    name: "description",
    label: "Description",
    type: "textarea",
    placeholder: "Enter optional description",
    rows: 4,
    maxLength: 500,
    defaultValue: "",
    autoComplete: "off",
  },
  {
    name: "percentage",
    label: "Percentage Rate (%)",
    type: "number",
    placeholder: "Enter percentage (e.g., 2.5)",
    required: true,
    min: 0,
    max: 100,
    step: 0.01,
    description: "Enter a value between 0 and 100. Example: 2.5 for 2.5%",
    icon: PercentBadgeIcon,
    defaultValue: "",
    autoComplete: "off",
  },
  {
    name: "status",
    label: "Status",
    type: "select",
    required: true,
    defaultValue: SERVICE_FEE_STATUS.ACTIVE,
  }
];

const VALIDATION_RULES = {
  name: {
    maxLength: 127,
    minLength: 1,
  },
  description: {
    maxLength: 500,
  },
  percentage: {
    custom: (value) => {
      const num = parseFloat(value);
      if (isNaN(num)) return "Percentage must be a valid number";
      if (num < 0) return "Percentage cannot be negative";
      if (num > 100) return "Percentage cannot exceed 100";
      return null;
    }
  },
};

const STATUS_OPTIONS = [
  { value: SERVICE_FEE_STATUS.ACTIVE, label: SERVICE_FEE_STATUS_LABELS[SERVICE_FEE_STATUS.ACTIVE] },
  { value: SERVICE_FEE_STATUS.INACTIVE, label: SERVICE_FEE_STATUS_LABELS[SERVICE_FEE_STATUS.INACTIVE] },
];

function SettingServiceFeeCreatePage() {
  return (
    <UIXThemeProvider>
      <SettingServiceFeeCreatePageContent />
    </UIXThemeProvider>
  );
}

const SettingServiceFeeCreatePageContent = memo(
  function SettingServiceFeeCreatePageContent() {
    const serviceFeeManager = useServiceFeeManager();
    const { getThemeClasses } = useUIXTheme();

    // Memoize theme classes
    const themeClasses = useMemo(
      () => ({
        alertInfoBg: getThemeClasses("alert-info-bg"),
        borderPrimary: getThemeClasses("border-primary"),
        textPrimary: getThemeClasses("text-primary"),
        textSecondary: getThemeClasses("text-secondary"),
        bgCard: getThemeClasses("bg-card"),
        cardBorder: getThemeClasses("card-border"),
        bgGradientPrimary: getThemeClasses("bg-gradient-primary"),
      }),
      [getThemeClasses],
    );

    // Memoize custom preview component
    const customPreview = useMemo(
      () => (formData) => {
        if (!formData.name || !formData.percentage) return null;

        return (
          <div className={`p-4 ${themeClasses.alertInfoBg} border ${themeClasses.borderPrimary} rounded-lg`}>
            <h3 className={`text-sm font-medium ${themeClasses.textPrimary} mb-3 flex items-center`}>
              <InformationCircleIcon className="w-4 h-4 mr-2" />
              Preview
            </h3>
            <div className={`${themeClasses.bgCard} p-3 rounded border ${themeClasses.cardBorder}`}>
              <p className={`text-xs ${themeClasses.textSecondary} mb-2`}>
                How this will appear in transactions:
              </p>
              <div className={`text-sm ${themeClasses.textPrimary} p-2 ${themeClasses.bgGradientPrimary} rounded border ${themeClasses.cardBorder}`}>
                <span className="font-medium">{formData.name}</span>
                {formData.description && (
                  <p className={`text-xs ${themeClasses.textSecondary} mt-1`}>{formData.description}</p>
                )}
                <p className={`text-xs ${themeClasses.textSecondary} mt-1`}>Fee: {formData.percentage}%</p>
              </div>
            </div>
            <div className={`mt-2 text-xs ${themeClasses.textPrimary}`}>
              Example: On a $100 transaction, the fee would be $
              {((100 * parseFloat(formData.percentage || 0)) / 100).toFixed(2)}
            </div>
          </div>
        );
      },
      [themeClasses],
    );

    // 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> Service fees are applied to transactions based on the percentage rate.
              Changes will be visible immediately after creating.
            </span>
          </p>
        </div>
      ),
      [themeClasses],
    );

    return (
      <SettingsFormView
        entityType="serviceFee"
        entityTypePlural="Service Fees"
        entityIcon={CreditCardIcon}
        entityManager={serviceFeeManager}
        basePath="/admin/settings/service-fee"
        listPath="/admin/settings/service-fees"
        mode="create"
        formFields={FORM_FIELDS}
        validationRules={VALIDATION_RULES}
        statusOptions={STATUS_OPTIONS}
        title="Create Service Fee"
        subtitle="Add a new service fee to the system"
        customPreview={customPreview}
        customInfoNote={customInfoNote}
      />
    );
  },
);

SettingServiceFeeCreatePageContent.displayName = "SettingServiceFeeCreatePageContent";

export default SettingServiceFeeCreatePage;