// File: src/components/UIX/EntityActionConfirmationPage/EntityActionConfirmationPage.jsx

import React, { useState, useEffect, useCallback } from "react";
import { Link, useNavigate } from "react-router";
import {
  ChevronLeftIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  XMarkIcon,
  InformationCircleIcon,
} from "@heroicons/react/24/outline";
import { useUIXTheme } from "../themes/useUIXTheme.jsx";
import { useAuth } from "../../../services/Services";

/**
 * EntityActionConfirmationPage
 *
 * A reusable component for entity action confirmation pages (archive, delete, ban, etc.)
 *
 * @param {Object} props
 * @param {string} props.entityType - Type of entity (e.g., 'customer', 'speaker', 'facilitator')
 * @param {string} props.entityId - ID of the entity
 * @param {string} props.actionType - Type of action ('archive', 'unarchive', 'delete', 'ban', 'unban', 'upgrade', 'downgrade')
 * @param {Function} props.fetchEntity - Function to fetch entity data: (id, onSuccess, onError, onDone, onUnauthorized) => void
 * @param {Function} props.executeAction - Function to execute the action: (id, onSuccess, onError, onDone, onUnauthorized) => void
 * @param {Array} props.breadcrumbItems - Breadcrumb navigation items
 * @param {Object} props.pageConfig - Page configuration (title, subtitle, icon, etc.)
 * @param {Function} props.renderEntityInfo - Function to render entity information: (entity) => ReactNode
 * @param {Object} props.warningConfig - Warning message configuration
 * @param {Array} props.statusAlerts - Array of status alert configurations: [{condition: (entity) => boolean, type: 'info'|'warning'|'error', message: string, icon: Component}]
 * @param {Function} props.isActionDisabled - Function to check if action should be disabled: (entity) => boolean
 * @param {string} props.returnPath - Path to navigate after action
 * @param {string} props.successRedirectPath - Path to redirect after successful action (defaults to returnPath)
 * @param {number} props.successRedirectDelay - Delay before redirect in ms (default: 2000)
 */
function EntityActionConfirmationPage({
  entityType = "entity",
  entityId,
  actionType = "action",
  fetchEntity,
  executeAction,
  breadcrumbItems = [],
  pageConfig = {},
  renderEntityInfo,
  warningConfig = {},
  statusAlerts = [],
  isActionDisabled,
  returnPath,
  successRedirectPath,
  successRedirectDelay = 2000,
}) {
  const navigate = useNavigate();
  const { authManager } = useAuth();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [entity, setEntity] = useState(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [successMessage, setSuccessMessage] = useState("");

  // Default page config
  const {
    title = `${entityType} - ${actionType}`,
    subtitle = `${actionType} ${entityType}`,
    icon: PageIcon,
    actionIcon: ActionIcon,
    loadingText = `Loading ${entityType} details...`,
  } = pageConfig;

  // Default warning config
  const {
    title: warningTitle = `${actionType} ${entityType} - Are you sure?`,
    description = `You are about to ${actionType} this ${entityType}.`,
    consequences = [],
    confirmationText = "Are you sure you would like to continue?",
    warningType = "amber", // 'amber', 'red', 'yellow'
  } = warningConfig;

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

  // Load entity details
  useEffect(() => {
    let mounted = true;

    const fetchEntityData = async () => {
      if (!authManager.isAuthenticated()) {
        navigate("/login");
        return;
      }

      if (!entityId) {
        setErrors({ general: `${entityType} ID is required` });
        setFetching(false);
        return;
      }

      setFetching(true);
      setErrors({});

      try {
        await fetchEntity(
          entityId,
          (entityData) => {
            if (mounted) {
              setEntity(entityData);
            }
          },
          (error) => {
            if (mounted) {
              if (import.meta.env.DEV) {
                console.error(`Failed to fetch ${entityType}:`, error);
              }
              setErrors(error);
            }
          },
          () => {
            if (mounted) {
              setFetching(false);
            }
          },
          onUnauthorized,
        );
      } catch (error) {
        if (mounted) {
          if (import.meta.env.DEV) {
            console.error(`Failed to fetch ${entityType}:`, error);
          }
          setErrors({ general: `Failed to load ${entityType} information` });
          setFetching(false);
        }
      }
    };

    fetchEntityData();

    return () => {
      mounted = false;
    };
  }, [entityId, fetchEntity, authManager, navigate, onUnauthorized, entityType]);

  // Handle action confirmation
  const handleConfirmAction = useCallback(async () => {
    setShowConfirmModal(false);
    setErrors({});
    setFetching(true);

    try {
      await executeAction(
        entityId,
        () => {
          // Success callback
          const capitalizedAction = actionType.charAt(0).toUpperCase() + actionType.slice(1);
          setSuccessMessage(`${entityType} has been successfully ${actionType}d`);

          // Navigate after delay
          setTimeout(() => {
            navigate(successRedirectPath || returnPath);
          }, successRedirectDelay);
        },
        (error) => {
          // Error callback
          if (import.meta.env.DEV) {
            console.error(`Failed to ${actionType} ${entityType}:`, error);
          }
          setErrors(error);
          setFetching(false);
        },
        () => {
          // Done callback
          if (!successMessage) {
            setFetching(false);
          }
        },
        onUnauthorized,
      );
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error(`Failed to ${actionType} ${entityType}:`, error);
      }
      setErrors({ general: `Failed to ${actionType} ${entityType}` });
      setFetching(false);
    }
  }, [
    entityId,
    executeAction,
    actionType,
    entityType,
    navigate,
    onUnauthorized,
    successMessage,
    returnPath,
    successRedirectPath,
    successRedirectDelay,
  ]);

  // Get warning color classes
  const getWarningClasses = () => {
    switch (warningType) {
      case "red":
        return {
          bg: "bg-red-50",
          border: "border-red-200",
          iconText: "text-red-600",
          titleText: "text-red-900",
          descText: "text-red-800",
          listText: "text-red-700",
          bulletBg: "bg-red-600",
          confirmText: "text-red-900",
        };
      case "yellow":
        return {
          bg: "bg-yellow-50",
          border: "border-yellow-200",
          iconText: "text-yellow-600",
          titleText: "text-yellow-900",
          descText: "text-yellow-800",
          listText: "text-yellow-700",
          bulletBg: "bg-yellow-600",
          confirmText: "text-yellow-900",
        };
      case "amber":
      default:
        return {
          bg: "bg-amber-50",
          border: "border-amber-200",
          iconText: "text-amber-600",
          titleText: "text-amber-900",
          descText: "text-amber-800",
          listText: "text-amber-700",
          bulletBg: "bg-amber-600",
          confirmText: "text-amber-900",
        };
    }
  };

  const warningClasses = getWarningClasses();

  // Render loading state
  if (isFetching && !entity) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
            <p className={`mt-4 ${getThemeClasses("text-secondary")}`}>
              {loadingText}
            </p>
          </div>
        </div>
      </div>
    );
  }

  const actionDisabled = isActionDisabled ? isActionDisabled(entity) : false;

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      {/* Breadcrumb */}
      {breadcrumbItems.length > 0 && (
        <nav className="flex mb-6" aria-label="Breadcrumb">
          <ol className="inline-flex items-center space-x-1 md:space-x-3">
            {breadcrumbItems.map((item, index) => (
              <li
                key={index}
                className={item.isActive ? "inline-flex items-center" : ""}
                aria-current={item.isActive ? "page" : undefined}
              >
                {index > 0 && (
                  <span className={`mx-2 ${getThemeClasses("text-muted")}`}>
                    /
                  </span>
                )}
                {item.to && !item.isActive ? (
                  <Link
                    to={item.to}
                    className={`inline-flex items-center text-sm font-medium ${getThemeClasses("text-primary")} hover:text-blue-600`}
                  >
                    {item.icon && <item.icon className="w-4 h-4 mr-2" />}
                    {item.label}
                  </Link>
                ) : (
                  <span
                    className={`text-sm font-medium ${getThemeClasses("text-muted")} inline-flex items-center`}
                  >
                    {item.icon && <item.icon className="w-4 h-4 mr-2" />}
                    {item.label}
                  </span>
                )}
              </li>
            ))}
          </ol>
        </nav>
      )}

      {/* Page Title */}
      <div className="mb-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className={`text-2xl md:text-3xl font-bold ${getThemeClasses("text-primary")} flex items-center`}>
              {PageIcon && (
                <PageIcon className="w-6 h-6 md:w-8 md:h-8 mr-3 text-blue-600" />
              )}
              {title}
            </h1>
            <p className={`mt-1 text-sm ${getThemeClasses("text-secondary")} flex items-center`}>
              {ActionIcon && <ActionIcon className="w-4 h-4 mr-1" />}
              {subtitle}
            </p>
          </div>
        </div>
      </div>

      {/* Success Message */}
      {successMessage && (
        <div className="mb-4 bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg flex items-center">
          <CheckCircleIcon className="w-5 h-5 mr-2" />
          {successMessage}
        </div>
      )}

      {/* Error Messages */}
      {errors && Object.keys(errors).length > 0 && (
        <div className="mb-4 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
          <div className="flex justify-between items-center">
            <span className="flex items-center">
              <XMarkIcon className="w-5 h-5 mr-2" />
              {errors.general ||
                errors.message ||
                errors.detail ||
                "An error occurred. Please try again."}
            </span>
            <button
              onClick={() => setErrors({})}
              className="text-red-700 hover:text-red-900"
            >
              <XMarkIcon className="w-5 h-5" />
            </button>
          </div>
        </div>
      )}

      {/* Status Alerts */}
      {statusAlerts.map((alert, index) => {
        if (!alert.condition || !alert.condition(entity)) return null;

        const alertColors = {
          info: { bg: "bg-blue-50", border: "border-blue-200", text: "text-blue-700" },
          warning: { bg: "bg-amber-50", border: "border-amber-200", text: "text-amber-700" },
          error: { bg: "bg-red-50", border: "border-red-200", text: "text-red-700" },
        };

        const colors = alertColors[alert.type] || alertColors.info;
        const AlertIcon = alert.icon || InformationCircleIcon;

        return (
          <div
            key={index}
            className={`mb-4 ${colors.bg} border ${colors.border} ${colors.text} px-4 py-3 rounded-lg flex items-center`}
          >
            <AlertIcon className="w-5 h-5 mr-2" />
            {alert.message}
          </div>
        );
      })}

      {/* Main Content */}
      <div className={`${getThemeClasses("bg-card")} shadow-sm rounded-lg overflow-hidden`}>
        <div className="p-6">
          {/* Warning Message */}
          <div className={`mb-6 ${warningClasses.bg} border ${warningClasses.border} rounded-lg p-6`}>
            <div className="flex items-start">
              <ExclamationTriangleIcon
                className={`w-6 h-6 ${warningClasses.iconText} mt-1 mr-3 flex-shrink-0`}
              />
              <div className="flex-1">
                <h3 className={`text-lg font-semibold ${warningClasses.titleText} mb-2`}>
                  {warningTitle}
                </h3>
                <p className={`${warningClasses.descText} mb-3`}>
                  {description}
                </p>
                {consequences.length > 0 && (
                  <ul className={`space-y-2 ${warningClasses.listText} ml-4`}>
                    {consequences.map((consequence, index) => (
                      <li key={index} className="flex items-start">
                        <span
                          className={`inline-block w-2 h-2 ${warningClasses.bulletBg} rounded-full mt-1.5 mr-2 flex-shrink-0`}
                        ></span>
                        {consequence}
                      </li>
                    ))}
                  </ul>
                )}
                <p className={`mt-4 font-semibold ${warningClasses.confirmText}`}>
                  {confirmationText}
                </p>
              </div>
            </div>
          </div>

          {/* Entity Information */}
          {entity && renderEntityInfo && renderEntityInfo(entity)}

          {/* Action Buttons */}
          <div className="flex flex-col sm:flex-row justify-between gap-4">
            <Link to={returnPath}>
              <button
                disabled={isFetching}
                className={`w-full sm:w-auto inline-flex items-center justify-center px-4 py-2 border ${getThemeClasses("border-border")} rounded-lg text-sm font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("bg-card")} hover:bg-opacity-80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed`}
              >
                <ChevronLeftIcon className="w-4 h-4 mr-2" />
                Back to More
              </button>
            </Link>

            <button
              onClick={() => setShowConfirmModal(true)}
              disabled={isFetching || actionDisabled}
              className={`w-full sm:w-auto inline-flex items-center justify-center px-4 py-2 border rounded-lg text-sm font-medium transition-colors ${
                actionDisabled
                  ? `${getThemeClasses("border-border")} ${getThemeClasses("text-muted")} ${getThemeClasses("bg-card")} cursor-not-allowed`
                  : "border-red-300 text-white bg-red-600 hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
              }`}
            >
              {ActionIcon && <ActionIcon className="w-4 h-4 mr-2" />}
              {isFetching
                ? "Processing..."
                : actionDisabled
                  ? `Already ${actionType}d`
                  : `Confirm and ${actionType}`}
            </button>
          </div>
        </div>
      </div>

      {/* Confirmation Modal */}
      {showConfirmModal && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
            {/* Background overlay */}
            <div
              className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
              onClick={() => setShowConfirmModal(false)}
            ></div>

            {/* Modal panel */}
            <div className="relative transform overflow-hidden rounded-lg bg-white text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg">
              <div className="bg-white px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
                <div className="sm:flex sm:items-start">
                  <div className="mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                    <ExclamationTriangleIcon
                      className="h-6 w-6 text-red-600"
                      aria-hidden="true"
                    />
                  </div>
                  <div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left">
                    <h3 className={`text-lg font-semibold leading-6 ${getThemeClasses("text-primary")}`}>
                      Confirm {actionType.charAt(0).toUpperCase() + actionType.slice(1)}
                    </h3>
                    <div className="mt-2">
                      <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                        <strong>Final Confirmation</strong>
                      </p>
                      <p className={`mt-2 text-sm ${getThemeClasses("text-secondary")}`}>
                        {description}
                      </p>
                      <p className="mt-3 text-sm font-medium text-red-600">
                        Are you absolutely sure you want to proceed?
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              <div className={`${getThemeClasses("bg-muted")} px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6`}>
                <button
                  type="button"
                  onClick={handleConfirmAction}
                  disabled={isFetching}
                  className="inline-flex w-full justify-center rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-500 sm:ml-3 sm:w-auto disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isFetching ? `${actionType}ing...` : `Yes, ${actionType}`}
                </button>
                <button
                  type="button"
                  onClick={() => setShowConfirmModal(false)}
                  disabled={isFetching}
                  className={`mt-3 inline-flex w-full justify-center rounded-md ${getThemeClasses("bg-card")} px-3 py-2 text-sm font-semibold ${getThemeClasses("text-primary")} shadow-sm ring-1 ring-inset ${getThemeClasses("border-border")} hover:bg-opacity-80 sm:mt-0 sm:w-auto disabled:opacity-50 disabled:cursor-not-allowed`}
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default EntityActionConfirmationPage;
