import React, { useMemo, useCallback, memo } from "react";
import { Link } from "react-router";
import { useCustomerManager } from "../../../../../services/Services";
import { SettingsListView } from "../../../../../components/business/views";
import { ViewButton, UIXThemeProvider, useUIXTheme } from "../../../../../components/UIX";
import { ArchiveBoxIcon, EnvelopeIcon, PhoneIcon, AcademicCapIcon, BuildingOffice2Icon, HeartIcon, BuildingOfficeIcon, UserGroupIcon } from "@heroicons/react/24/outline";
import { INACTIVE_CLIENT_STATUS, INACTIVE_CLIENT_STATUS_LABELS } from "../../../../../constants/Settings";
import { CUSTOMER_TYPE_VALUES, CUSTOMER_TYPE_LABELS, CUSTOMER_STATUS, CUSTOMER_DEACTIVATION_REASONS, CUSTOMER_DEACTIVATION_REASON_LABELS } from "../../../../../constants/Customer";
import { formatDateForDisplay } from "../../../../../services/Helpers/DateFormatter";

// Move static configuration outside component to prevent recreation
const STATUS_OPTIONS = [];

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

function SettingInactiveClientListPage() {
  return (
    <UIXThemeProvider>
      <SettingInactiveClientListPageContent />
    </UIXThemeProvider>
  );
}

const SettingInactiveClientListPageContent = memo(function SettingInactiveClientListPageContent() {
  const customerManager = useCustomerManager();
  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'),
      badgePurpleBg: getThemeClasses('badge-purple-bg'),
      badgePurpleText: getThemeClasses('badge-purple-text'),
      badgeWarningBg: getThemeClasses('badge-warning-bg'),
      badgeWarningText: getThemeClasses('badge-warning-text'),
      textMuted: getThemeClasses('text-muted'),
      alertInfoBg: getThemeClasses('alert-info-bg'),
    }),
    [getThemeClasses],
  );

  // Get customer type icon
  const getCustomerTypeIcon = (type) => {
    switch (type) {
      case CUSTOMER_TYPE_VALUES.EDUCATIONAL:
        return <AcademicCapIcon className="w-4 h-4 mr-2" />;
      case CUSTOMER_TYPE_VALUES.CORPORATE:
        return <BuildingOffice2Icon className="w-4 h-4 mr-2" />;
      case CUSTOMER_TYPE_VALUES.NON_PROFIT:
        return <HeartIcon className="w-4 h-4 mr-2" />;
      case CUSTOMER_TYPE_VALUES.GOVERNMENT:
        return <BuildingOfficeIcon className="w-4 h-4 mr-2" />;
      default:
        return <UserGroupIcon className="w-4 h-4 mr-2" />;
    }
  };

  // Get type badge color - memoized
  const getTypeBadgeColor = useCallback((customerType) => {
    switch (customerType) {
      case CUSTOMER_TYPE_VALUES.EDUCATIONAL:
        return `${themeClasses.alertInfoBg} ${themeClasses.linkText}`;
      case CUSTOMER_TYPE_VALUES.CORPORATE:
        return `${themeClasses.badgeActiveBg} ${themeClasses.badgeActiveText}`;
      case CUSTOMER_TYPE_VALUES.NON_PROFIT:
        return `${themeClasses.badgePurpleBg} ${themeClasses.badgePurpleText}`;
      case CUSTOMER_TYPE_VALUES.GOVERNMENT:
        return `${themeClasses.badgeWarningBg} ${themeClasses.badgeWarningText}`;
      default:
        return `${themeClasses.badgeInactiveBg} ${themeClasses.badgeInactiveText}`;
    }
  }, [themeClasses]);

  // Get deactivation reason text
  const getDeactivationReasonText = (reason, reasonOther) => {
    if (reason === CUSTOMER_DEACTIVATION_REASONS.OTHER && reasonOther) {
      return reasonOther;
    }
    return CUSTOMER_DEACTIVATION_REASON_LABELS[reason] || "Not specified";
  };

  // Wrap handlers with useCallback
  const handleRowClick = useCallback((client) => {
    // Navigation is handled by ViewButton
  }, []);

  // Custom entity manager wrapper for inactive clients
  const inactiveClientManager = useMemo(() => ({
    getInactiveClients: (params, onUnauthorized, forceRefresh) => {
      // Force status filter for inactive clients (override any existing status filter)
      const enhancedParams = {
        ...params,
        status: CUSTOMER_STATUS.INACTIVE
      };
      // Remove any empty status values that might interfere
      if (enhancedParams.status === "" || enhancedParams.status === null || enhancedParams.status === undefined) {
        delete enhancedParams.status;
      }
      // Always set our specific status (use ARCHIVED which maps to inactive clients)
      enhancedParams.status = CUSTOMER_STATUS.ARCHIVED;

      if (import.meta.env.DEV) {
        console.log('InactiveClient filter params:', enhancedParams);
        console.log('CUSTOMER_STATUS.ARCHIVED value:', CUSTOMER_STATUS.ARCHIVED);
        console.log('Generated URL should be: /api/v1/customers?status=2&page=1&limit=25...');
      }

      // Always force refresh for inactive clients to bypass cache since we're filtering
      const result = customerManager.getCustomers(enhancedParams, onUnauthorized, true);

      // Debug: Log the actual response to see what customers are returned
      result.then(response => {
        if (import.meta.env.DEV) {
          console.log('InactiveClient API response:', response);
          console.log('Customers returned:', response.results?.map(c => ({
            id: c.id,
            name: c.name,
            status: c.status,
            deactivationReason: c.deactivationReason
          })));
        }

        // Filter out any active customers on the frontend as a temporary workaround
        if (response.results) {
          const beforeCount = response.results.length;
          response.results = response.results.filter(customer => customer.status === CUSTOMER_STATUS.ARCHIVED);
          const afterCount = response.results.length;

          if (import.meta.env.DEV) {
            console.log(`FRONTEND FILTER: Removed ${beforeCount - afterCount} active customers, showing ${afterCount} inactive customers`);
          }

          // Update the count to reflect filtered results
          response.count = afterCount;
        }
      }).catch(err => {
        if (import.meta.env.DEV) {
          console.error('InactiveClient API error:', err);
        }
      });

      return result;
    }
  }), [customerManager]);

  // Define table columns - memoized
  const columns = useMemo(() => [
    {
      key: 'name',
      label: 'Name',
      render: (value, client) => (
        <Link
          to={`/admin/customer/${client.id}/detail`}
          className={`${themeClasses.linkText} ${themeClasses.linkHover} font-medium flex items-center`}
        >
          {getCustomerTypeIcon(client.type)}
          <div className="max-w-md truncate">
            {client.name}
          </div>
        </Link>
      )
    },
    {
      key: 'contact',
      label: 'Contact',
      render: (value, client) => (
        <div className="space-y-1">
          {client.email && (
            <div className="flex items-center text-sm">
              <EnvelopeIcon className={`w-4 h-4 mr-2 ${themeClasses.textMuted}`} />
              <span className="truncate">{client.email}</span>
            </div>
          )}
          {client.phone && (
            <div className="flex items-center text-sm">
              <PhoneIcon className={`w-4 h-4 mr-2 ${themeClasses.textMuted}`} />
              {client.phone}
            </div>
          )}
        </div>
      )
    },
    {
      key: 'type',
      label: 'Type',
      render: (value, client) => (
        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getTypeBadgeColor(client.type)}`}>
          {CUSTOMER_TYPE_LABELS[client.type] || client.type}
        </span>
      )
    },
    {
      key: 'deactivationReason',
      label: 'Deactivation Reason',
      render: (value, client) => (
        <div className="max-w-xs truncate">
          {getDeactivationReasonText(client.deactivationReason, client.deactivationReasonOther)}
        </div>
      )
    },
    {
      key: 'updatedAt',
      label: 'Modified Date',
      render: (value, client) => formatDateForDisplay(client.updatedAt) || "—"
    },
    {
      key: 'actions',
      label: 'Actions',
      align: 'right',
      render: (value, client) => (
        <ViewButton basePath="/admin/customer" itemId={client.id} />
      )
    }
  ], [themeClasses, getCustomerTypeIcon, getTypeBadgeColor, getDeactivationReasonText]);

  // Custom empty state without create button - memoized
  const customEmptyState = useMemo(() => (
    <div className="text-center py-12">
      <ArchiveBoxIcon className={`w-12 h-12 mx-auto ${themeClasses.textMuted} mb-4`} />
      <h3 className={`text-lg font-medium ${themeClasses.linkText} mb-2`}>
        No Inactive Clients
      </h3>
      <p className={`${themeClasses.textMuted} max-w-sm mx-auto`}>
        There are currently no archived/inactive clients to display.
      </p>
    </div>
  ), [themeClasses]);

  return (
    <SettingsListView
      entityType="inactiveClient"
      entityTypePlural="Inactive Clients"
      entityIcon={ArchiveBoxIcon}
      entityManager={inactiveClientManager}
      basePath="/admin/settings/inactive-clients"
      createPath={undefined} // Disable create button for this read-only view
      title="Inactive Clients"
      subtitle="View and manage archived client records"
      columns={columns}
      searchPlaceholder="Search by name, email, or phone..."
      statusOptions={STATUS_OPTIONS}
      sortOptions={SORT_OPTIONS}
      onRowClick={handleRowClick}
      customEmptyState={customEmptyState}
      hideSearch={true}
      hideFilters={true}
    />
  );
});
SettingInactiveClientListPageContent.displayName = 'SettingInactiveClientListPageContent';

export default SettingInactiveClientListPage;