// File Path: monorepo/web/frontend/src/pages/Admin/Facilitator/Detail/More/Ban/Page.jsx

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import {
  ChartBarIcon,
  UserGroupIcon,
  InformationCircleIcon,
  EllipsisHorizontalIcon,
  NoSymbolIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  ShieldExclamationIcon,
} from "@heroicons/react/24/outline";
import { useFacilitatorManager } from "../../../../../../services/Services";
import {
  UIXThemeProvider,
  useUIXTheme,
  Breadcrumb,
  Alert,
  Card,
  Textarea,
  Button,
  Modal,
  Spinner,
  Badge,
} from "../../../../../../components/UIX";

function AdminFacilitatorDetailMoreBanPage() {
  const { aid } = useParams();
  const navigate = useNavigate();
  const facilitatorManager = useFacilitatorManager();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [facilitator, setFacilitator] = useState(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [successMessage, setSuccessMessage] = useState("");
  const [banReason, setBanReason] = useState("");
  const [isBanning, setIsBanning] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);

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

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

    const fetchFacilitator = async () => {
      if (import.meta.env.DEV) {
        console.log("Fetching facilitator with ID:", aid);
      }
      setFetching(true);
      setErrors({});

      try {
        const data = await facilitatorManager.getFacilitatorDetail(
          aid,
          onUnauthorized,
        );
        if (import.meta.env.DEV) {
          console.log("Facilitator data received:", data);
        }

        if (mounted) {
          setFacilitator(data);
          setIsInitialized(true);
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Failed to fetch facilitator:", error);
        }
        if (mounted) {
          setErrors(error || { message: "Failed to load facilitator details" });
          setIsInitialized(true);
        }
      } finally {
        if (mounted) {
          setFetching(false);
        }
      }
    };

    if (aid) {
      fetchFacilitator();
    } else {
      if (import.meta.env.DEV) {
        console.error("No facilitator ID provided");
      }
      setErrors({ message: "No facilitator ID provided" });
      setIsInitialized(true);
    }

    return () => {
      mounted = false;
    };
  }, [aid, facilitatorManager, onUnauthorized]);

  // Handle ban confirmation
  const handleConfirmBan = useCallback(async () => {
    // Validate reason
    if (!banReason || banReason.trim().length === 0) {
      setErrors({ reason: "Ban reason is required" });
      return;
    }

    if (banReason.trim().length < 10) {
      setErrors({ reason: "Ban reason must be at least 10 characters long" });
      return;
    }

    setShowConfirmModal(false);
    setErrors({});
    setIsBanning(true);

    try {
      // Prepare ban data
      const banData = {
        facilitator_id: aid,
        reason: banReason.trim(),
      };

      if (import.meta.env.DEV) {
        console.log("Ban data:", banData);
      }

      // Note: Implement actual ban API call here
      // await facilitatorManager.banFacilitator(aid, banData, onUnauthorized);

      // Simulate API call for now
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // Set success message
      setSuccessMessage("Facilitator has been successfully banned");

      // Navigate to facilitators list after a short delay
      setTimeout(() => {
        navigate("/admin/facilitators");
      }, 2000);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Failed to ban facilitator:", error);
      }
      setErrors(error || { message: "Failed to ban facilitator" });
      setIsBanning(false);
    }
  }, [aid, banReason, navigate, onUnauthorized]);

  // Format phone number for display
  const formatPhone = useCallback((phone) => {
    if (!phone) return "N/A";
    return phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
  }, []);

  // Check if already banned
  const isAlreadyBanned = facilitator?.status === 100 || facilitator?.isBanned;

  // Get status badge
  const getStatusBadge = useCallback((status) => {
    if (status === 100 || facilitator?.isBanned) {
      return <Badge variant="error" size="sm" icon={NoSymbolIcon}>Banned</Badge>;
    } else if (status === 1) {
      return <Badge variant="success" size="sm">Active</Badge>;
    } else if (status === 2) {
      return <Badge variant="warning" size="sm">Archived</Badge>;
    }
    return <Badge variant="default" size="sm">Unknown</Badge>;
  }, [facilitator?.isBanned]);

  // Breadcrumb configuration
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: ChartBarIcon,
    },
    {
      label: "Facilitators",
      to: "/admin/facilitators",
      icon: UserGroupIcon,
    },
    {
      label: "Detail",
      to: `/admin/facilitator/${aid}`,
      icon: InformationCircleIcon,
    },
    {
      label: "More",
      to: `/admin/facilitator/${aid}/more`,
      icon: EllipsisHorizontalIcon,
    },
    {
      label: "Ban",
      icon: NoSymbolIcon,
      isActive: true,
    },
  ];

  // Render loading state
  if (isFetching) {
    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">
            <Spinner size="lg" />
            <p className={`mt-4 ${getThemeClasses('text-secondary')}`}>
              Loading facilitator details...
            </p>
          </div>
        </div>
      </div>
    );
  }

  // Render error state
  if (isInitialized && !facilitator && Object.keys(errors).length > 0) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <Alert type="error" className="mb-6">
          {errors.message ||
            errors.detail ||
            "Failed to load facilitator details. Please try again."}
        </Alert>
        <Button
          variant="outline"
          icon={ChartBarIcon}
          onClick={() => navigate(`/admin/facilitator/${aid}/more`)}
        >
          Back to More
        </Button>
      </div>
    );
  }

  // Don't render main content until we have facilitator data
  if (!facilitator) {
    return null;
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      {/* Breadcrumb */}
      <Breadcrumb items={breadcrumbItems} className="mb-6" />

      {/* Page Title */}
      <div className="mb-6">
        <h1 className={`text-2xl md:text-3xl font-bold ${getThemeClasses('text-primary')} flex items-center`}>
          <UserGroupIcon className={`w-6 h-6 md:w-8 md:h-8 mr-3 ${getThemeClasses('text-accent')}`} />
          Facilitator: {facilitator.firstName} {facilitator.lastName}
        </h1>
        <p className={`mt-1 text-sm ${getThemeClasses('text-secondary')} flex items-center`}>
          <ShieldExclamationIcon className="w-4 h-4 mr-1" />
          Ban Facilitator
        </p>
      </div>

      {/* Success Message */}
      {successMessage && (
        <Alert type="success" icon={CheckCircleIcon} className="mb-4">
          {successMessage}
        </Alert>
      )}

      {/* Error Messages */}
      {errors && errors.reason && (
        <Alert type="error" className="mb-4">
          {errors.reason}
        </Alert>
      )}

      {/* Main Content Card */}
      <Card>
        <div className="p-6">
          {/* Warning Message */}
          <Alert type="error" icon={ExclamationTriangleIcon} className="mb-6">
            <div className="flex-1">
              <h3 className={`text-lg font-semibold ${getThemeClasses('text-primary')} mb-3`}>
                Ban Facilitator - Severe Action Warning
              </h3>
              <p className={`${getThemeClasses('text-primary')} mb-3`}>
                You are about to <strong>permanently ban</strong> this
                facilitator. This means:
              </p>
              <ul className={`space-y-2 ${getThemeClasses('text-secondary')} ml-4`}>
                <li className="flex items-start">
                  <span className="text-red-500 mr-2">•</span>
                  The facilitator will be <strong>immediately</strong> logged out
                </li>
                <li className="flex items-start">
                  <span className="text-red-500 mr-2">•</span>
                  They will <strong>not</strong> be able to log in again
                </li>
                <li className="flex items-start">
                  <span className="text-red-500 mr-2">•</span>
                  All access to the system will be{" "}
                  <strong>permanently revoked</strong>
                </li>
                <li className="flex items-start">
                  <span className="text-red-500 mr-2">•</span>
                  The facilitator will not be able to receive or complete any
                  work orders
                </li>
                <li className="flex items-start">
                  <span className="text-red-500 mr-2">•</span>
                  This action is <strong>irreversible</strong> without system
                  administrator intervention
                </li>
              </ul>
              <p className={`mt-4 font-semibold ${getThemeClasses('text-primary')}`}>
                This action should only be taken for serious violations or
                security concerns.
              </p>
            </div>
          </Alert>

          {/* Facilitator Information */}
          <div className={`${getThemeClasses('bg-muted')} rounded-lg p-6 mb-6`}>
            <h4 className={`text-lg font-semibold ${getThemeClasses('text-primary')} mb-4`}>
              Facilitator Information:
            </h4>
            <dl className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <dt className={`text-sm font-medium ${getThemeClasses('text-secondary')}`}>
                  Name:
                </dt>
                <dd className={`mt-1 text-sm ${getThemeClasses('text-primary')}`}>
                  {facilitator.firstName} {facilitator.lastName}
                </dd>
              </div>
              <div>
                <dt className={`text-sm font-medium ${getThemeClasses('text-secondary')}`}>
                  Email:
                </dt>
                <dd className={`mt-1 text-sm ${getThemeClasses('text-primary')}`}>
                  {facilitator.email}
                </dd>
              </div>
              <div>
                <dt className={`text-sm font-medium ${getThemeClasses('text-secondary')}`}>
                  Phone:
                </dt>
                <dd className={`mt-1 text-sm ${getThemeClasses('text-primary')}`}>
                  {formatPhone(facilitator.phone)}
                </dd>
              </div>
              <div>
                <dt className={`text-sm font-medium ${getThemeClasses('text-secondary')}`}>
                  Current Status:
                </dt>
                <dd className="mt-1 text-sm">
                  {getStatusBadge(facilitator.status)}
                </dd>
              </div>
              {facilitator.typeOf && (
                <div>
                  <dt className={`text-sm font-medium ${getThemeClasses('text-secondary')}`}>
                    Type:
                  </dt>
                  <dd className={`mt-1 text-sm ${getThemeClasses('text-primary')}`}>
                    {facilitator.typeOf === 1
                      ? "Unassigned"
                      : facilitator.typeOf === 2
                        ? "Residential"
                        : facilitator.typeOf === 3
                          ? "Commercial"
                          : "Unknown"}
                  </dd>
                </div>
              )}
            </dl>
          </div>

          {/* Ban Reason Input */}
          {!isAlreadyBanned && (
            <div className="mb-6">
              <Textarea
                id="banReason"
                name="banReason"
                label="Ban Reason"
                value={banReason}
                onChange={(e) => {
                  setBanReason(e.target.value);
                  setErrors({}); // Clear errors when typing
                }}
                disabled={isBanning}
                error={errors.reason}
                required
                rows={5}
                placeholder="Please provide a detailed reason for banning this facilitator..."
                maxLength={500}
                helperText="This reason will be recorded in the system logs and may be reviewed by administrators."
              />
            </div>
          )}

          {/* Already Banned Message */}
          {isAlreadyBanned && (
            <Alert type="info" icon={InformationCircleIcon}>
              This facilitator is already banned. No further action is needed.
            </Alert>
          )}

          {/* Action Buttons */}
          <div className={`flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 pt-4 border-t ${getThemeClasses('border-border')}`}>
            <Button
              variant="outline"
              onClick={() => navigate(`/admin/facilitator/${aid}/more`)}
              disabled={isBanning}
            >
              Back to More
            </Button>

            {!isAlreadyBanned && (
              <Button
                variant="danger"
                icon={NoSymbolIcon}
                onClick={() => setShowConfirmModal(true)}
                disabled={isBanning || !banReason.trim()}
              >
                {isBanning ? "Processing..." : "Proceed with Ban"}
              </Button>
            )}
          </div>
        </div>
      </Card>

      {/* Confirmation Modal */}
      <Modal
        isOpen={showConfirmModal}
        onClose={() => setShowConfirmModal(false)}
        title="Final Ban Confirmation"
        icon={ExclamationTriangleIcon}
        iconColor="error"
      >
        <div className="space-y-4">
          <Alert type="error" className="text-center">
            <p className="font-semibold">⚠️ THIS ACTION CANNOT BE UNDONE</p>
          </Alert>

          <p className={`text-sm ${getThemeClasses('text-secondary')}`}>
            You are about to permanently ban:
          </p>

          <p className={`text-sm font-semibold ${getThemeClasses('text-primary')}`}>
            {facilitator.firstName} {facilitator.lastName} ({facilitator.email})
          </p>

          <div className={`${getThemeClasses('bg-muted')} rounded-lg p-3`}>
            <p className={`text-sm font-medium ${getThemeClasses('text-secondary')} mb-1`}>
              Ban Reason:
            </p>
            <p className={`text-sm ${getThemeClasses('text-primary')} italic`}>
              {banReason}
            </p>
          </div>

          <p className={`text-sm ${getThemeClasses('text-secondary')}`}>
            This will immediately revoke all access and log the facilitator out
            of the system.
          </p>

          <p className="text-sm font-semibold text-red-600">
            Are you absolutely certain you want to proceed?
          </p>
        </div>

        <div className="mt-6 flex flex-col-reverse sm:flex-row sm:justify-end gap-3">
          <Button
            variant="outline"
            onClick={() => setShowConfirmModal(false)}
            disabled={isBanning}
          >
            Cancel
          </Button>
          <Button
            variant="danger"
            onClick={handleConfirmBan}
            disabled={isBanning}
          >
            {isBanning ? "Banning..." : "Yes, Ban Facilitator"}
          </Button>
        </div>
      </Modal>
    </div>
  );
}

function AdminFacilitatorDetailMoreBanPageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminFacilitatorDetailMoreBanPage />
    </UIXThemeProvider>
  );
}

export default AdminFacilitatorDetailMoreBanPageWrapper;
