// src/pages/Admin/Setting/InactiveClient/Update/Page.jsx

import React, { useState, useEffect, useMemo, useCallback, memo } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { useCustomerManager } from "../../../../../services/Services";
import {
  Breadcrumb,
  PageHeader,
  Alert,
  FormCard,
  Button,
  DetailPageIcon,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  UserIcon,
  ArrowLeftIcon,
  ChevronRightIcon,
  XMarkIcon,
  ArchiveBoxIcon,
  ExclamationTriangleIcon,
  ChartBarIcon,
  BuildingOffice2Icon,
  HomeIcon,
  InformationCircleIcon,
  Cog6ToothIcon,
  ArrowPathIcon,
  AcademicCapIcon,
  HeartIcon,
  BuildingOfficeIcon,
  UserGroupIcon,
  CheckCircleIcon,
  ChevronLeftIcon,
} from "@heroicons/react/24/outline";
import {
  CUSTOMER_TYPE_VALUES,
  CUSTOMER_TYPE_LABELS,
  CUSTOMER_STATUS,
  CUSTOMER_STATUS_LABELS,
  CUSTOMER_DEACTIVATION_REASONS,
  CUSTOMER_DEACTIVATION_REASON_LABELS,
} from "../../../../../constants/Customer";

function SettingInactiveClientUpdatePage() {
  return (
    <UIXThemeProvider>
      <SettingInactiveClientUpdatePageContent />
    </UIXThemeProvider>
  );
}

const SettingInactiveClientUpdatePageContent = memo(function SettingInactiveClientUpdatePageContent() {
  const { id } = useParams();
  const navigate = useNavigate();
  const customerManager = useCustomerManager();
  const { getThemeClasses } = useUIXTheme();

  // Memoize theme classes
  const themeClasses = useMemo(
    () => ({
      bgGradientPrimary: getThemeClasses('bg-gradient-primary'),
      loadingSpinner: getThemeClasses('loading-spinner'),
      textMuted: getThemeClasses('text-muted'),
      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'),
      badgeErrorBg: getThemeClasses('badge-error-bg'),
      badgeErrorText: getThemeClasses('badge-error-text'),
      alertInfoBg: getThemeClasses('alert-info-bg'),
      linkText: getThemeClasses('text-primary'),
    }),
    [getThemeClasses],
  );

  // State management
  const [client, setClient] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  // Handle unauthorized access
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Fetch client details
  const fetchClientDetails = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await customerManager.getCustomerById(
        id,
        onUnauthorized,
      );

      if (response) {
        setClient(response);
      } else {
        setClient(null);
      }
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error("Failed to fetch client details:", err);
      setError("Failed to load client details. Please try again.");
      }
    } finally {
      setLoading(false);
    }
  }, [id, customerManager, onUnauthorized]);

  // Handle restore client
  const handleRestoreClient = async () => {
    try {
      setSaving(true);
      setError(null);

      // Update the client to set status back to active
      const updateData = {
        ...client,
        status: CUSTOMER_STATUS.ACTIVE,
        deactivationReason: null,
        deactivationReasonOther: null,
      };

      await customerManager.updateCustomer(id, updateData, onUnauthorized);

      // Navigate back to inactive clients list with success message
      navigate("/admin/settings/inactive-clients", {
        state: {
          successMessage: "Client restored to active status successfully",
        },
      });
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error("Failed to restore client:", err);
      setError("Failed to restore client. Please try again.");
      }
      setSaving(false);
    }
  };

  // Load client data on mount
  useEffect(() => {
    if (id) {
      fetchClientDetails();
    }
  }, [id, fetchClientDetails]);

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

  // 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";
  };

  if (loading) {
    return (
      <div className={`min-h-screen ${themeClasses.bgGradientPrimary} flex items-center justify-center`}>
        <div className="text-center">
          <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.loadingSpinner} mx-auto`}></div>
          <p className={`mt-4 ${themeClasses.linkText}`}>Loading client details...</p>
        </div>
      </div>
    );
  }

  if (!client) {
    return (
      <div className={`min-h-screen ${themeClasses.bgGradientPrimary}`}>
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
          <div className="text-center py-12">
            <ExclamationTriangleIcon className={`mx-auto h-12 w-12 ${themeClasses.textMuted}`} />
            <h3 className={`mt-2 text-sm font-medium ${themeClasses.linkText}`}>
              Client Not Found
            </h3>
            <p className={`mt-1 text-sm ${themeClasses.textMuted}`}>
              The client you're looking for could not be found.
            </p>
            <div className="mt-6">
              <Button
                variant="primary"
                onClick={() => navigate("/admin/settings/inactive-clients")}
                icon={ChevronLeftIcon}
              >
                Back to Inactive Clients
              </Button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`min-h-screen ${themeClasses.bgGradientPrimary}`}>
      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
        <Breadcrumb items={[
          {
            label: 'Dashboard',
            to: '/admin/dashboard',
            icon: ChartBarIcon
          },
          {
            label: 'Settings',
            to: '/admin/settings',
            icon: Cog6ToothIcon
          },
          {
            label: 'Inactive Clients',
            to: '/admin/settings/inactive-clients',
            icon: ArchiveBoxIcon
          },
          {
            label: 'Restore Client',
            icon: ArrowPathIcon,
            isActive: true
          }
        ]} />

        <PageHeader
          title="Restore Inactive Client"
          subtitle="Confirm restoring this client to active status"
          backButton={{
            text: "Back to List",
            onClick: () => navigate("/admin/settings/inactive-clients")
          }}
        />

        {/* Error Messages */}
        {error && (
          <Alert
            type="error"
            message={error}
            onClose={() => setError(null)}
            className="mb-6"
          />
        )}

        {/* Main Content Layout - Centered */}
        <div className="max-w-4xl mx-auto">
          <FormCard title="Restore Client Confirmation">

            <div className="space-y-6">
              <p className="text-gray-700 text-lg">
                Are you sure you want to restore the following client to active
                status? They will be removed from the inactive list and will be
                able to use the system again.
              </p>

              <div className={`${themeClasses.badgeErrorBg} rounded-lg p-6 border-l-4 ${themeClasses.loadingSpinner}`}>
                <h3 className="text-base font-semibold text-gray-900 mb-4">
                  Client to be Restored
                </h3>
                <dl className="space-y-3 text-sm">
                  <div className="flex">
                    <dt className="w-32 font-medium text-gray-600 shrink-0">
                      Name
                    </dt>
                    <dd className="text-gray-900 font-medium">{client.name}</dd>
                  </div>
                  {client.email && (
                    <div className="flex">
                      <dt className="w-32 font-medium text-gray-600 shrink-0">
                        Email
                      </dt>
                      <dd className="text-gray-900">{client.email}</dd>
                    </div>
                  )}
                  <div className="flex items-center">
                    <dt className="w-32 font-medium text-gray-600 shrink-0">
                      Type
                    </dt>
                    <dd>
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getTypeBadgeColor(client.type)}`}>
                        {getCustomerTypeIcon(client.type)}
                        {CUSTOMER_TYPE_LABELS[client.type] || client.type}
                      </span>
                    </dd>
                  </div>
                  <div className="flex">
                    <dt className="w-32 font-medium text-gray-600 shrink-0">
                      Current Status
                    </dt>
                    <dd>
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${themeClasses.badgeErrorBg} ${themeClasses.badgeErrorText}`}>
                        {CUSTOMER_STATUS_LABELS[client.status] || client.status}
                      </span>
                    </dd>
                  </div>
                  <div className="flex">
                    <dt className="w-32 font-medium text-gray-600 shrink-0">
                      Deactivation Reason
                    </dt>
                    <dd className="text-gray-900">
                      {getDeactivationReasonText(
                        client.deactivationReason,
                        client.deactivationReasonOther,
                      )}
                    </dd>
                  </div>
                </dl>
              </div>

              <Alert
                type="info"
                message="The client's status will be set to 'Active', and they will no longer appear in the inactive client list. All deactivation reasons will be cleared."
                showIcon
              />

              <div className="flex items-center justify-end gap-4 mt-8">
                <Button
                  variant="secondary"
                  onClick={() => navigate("/admin/settings/inactive-clients")}
                >
                  Cancel
                </Button>
                <Button
                  variant="primary"
                  onClick={handleRestoreClient}
                  disabled={saving}
                  loading={saving}
                  loadingText="Restoring..."
                  icon={ArrowPathIcon}
                >
                  Confirm and Restore
                </Button>
              </div>
            </div>
          </FormCard>

          {/* Additional Actions Card */}
          <FormCard title="Need More Information?" className="mt-6">
            <p className="text-sm text-gray-600 mb-4">
              If you need to review the client's full history or details before
              restoring, you can view their complete profile.
            </p>
            <Button
              variant="secondary"
              onClick={() => navigate(`/admin/customers/${id}`)}
              icon={UserIcon}
            >
              View Full Client Details
            </Button>
          </FormCard>
        </div>
      </div>
    </div>
  );
});
SettingInactiveClientUpdatePageContent.displayName = 'SettingInactiveClientUpdatePageContent';

export default SettingInactiveClientUpdatePage;