import React, { useState, useEffect, useCallback } from "react";
import { twoFactorAPI } from "../../services/api";
import { TwoFactorStatus } from "../../types";
import TwoFactorSetupModal from "./TwoFactorSetupModal";
import TwoFactorVerifyModal from "./TwoFactorVerifyModal";
import RecoveryCodesDisplay from "./RecoveryCodesDisplay";

const TwoFactorManagement: React.FC = () => {
  const [status, setStatus] = useState<TwoFactorStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Modal states
  const [showSetupModal, setShowSetupModal] = useState(false);
  const [showVerifyModal, setShowVerifyModal] = useState(false);
  const [showRecoveryCodes, setShowRecoveryCodes] = useState(false);
  const [newRecoveryCodes, setNewRecoveryCodes] = useState<string[]>([]);
  const [pendingAction, setPendingAction] = useState<
    "disable" | "regenerate" | null
  >(null);

  const fetchStatus = useCallback(async () => {
    try {
      const response = await twoFactorAPI.getStatus();
      setStatus(response.data);
    } catch (err: any) {
      setError(err.response?.data?.error || "Failed to load 2FA status");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchStatus();
  }, [fetchStatus]);

  const handleSetupSuccess = () => {
    fetchStatus();
  };

  const handleDisable = () => {
    setPendingAction("disable");
    setShowVerifyModal(true);
  };

  const handleRegenerateRecoveryCodes = () => {
    setPendingAction("regenerate");
    setShowVerifyModal(true);
  };

  const handleVerifySuccess = async () => {
    setShowVerifyModal(false);

    if (pendingAction === "disable") {
      try {
        await twoFactorAPI.disable();
        fetchStatus();
      } catch (err: any) {
        setError(err.response?.data?.error || "Failed to disable 2FA");
      }
    } else if (pendingAction === "regenerate") {
      try {
        const response = await twoFactorAPI.regenerateRecoveryCodes();
        setNewRecoveryCodes(response.data.recoveryCodes);
        setShowRecoveryCodes(true);
        fetchStatus();
      } catch (err: any) {
        setError(
          err.response?.data?.error || "Failed to regenerate recovery codes"
        );
      }
    }

    setPendingAction(null);
  };

  if (loading) {
    return (
      <div className="text-center py-4">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  return (
    <div>
      <h5 className="mb-3">
        <i className="bi bi-shield-lock me-2"></i>
        Multi-Factor Authentication
      </h5>

      {error && (
        <div className="alert alert-danger mb-3">
          <i className="bi bi-exclamation-circle me-2"></i>
          {error}
          <button
            type="button"
            className="btn-close float-end"
            onClick={() => setError(null)}
          ></button>
        </div>
      )}

      {status?.enabled ? (
        <div className="card">
          <div className="card-body">
            <div className="d-flex align-items-center mb-3">
              <div className="flex-shrink-0">
                <span className="badge bg-success fs-6">
                  <i className="bi bi-check-circle me-1"></i>
                  Enabled
                </span>
              </div>
              <div className="flex-grow-1 ms-3">
                <strong>
                  {status.method === "totp"
                    ? "Authenticator App"
                    : "Email Verification"}
                </strong>
              </div>
            </div>

            <hr />

            <div className="mb-3">
              <div className="d-flex justify-content-between align-items-center">
                <div>
                  <strong>Recovery Codes</strong>
                  <div className="text-muted small">
                    {status.hasRecoveryCodes
                      ? status.lowRecoveryCodes
                        ? "Running low"
                        : "Available"
                      : "None remaining"}
                  </div>
                </div>
                <button
                  className="btn btn-outline-secondary btn-sm"
                  onClick={handleRegenerateRecoveryCodes}
                >
                  <i className="bi bi-arrow-clockwise me-1"></i>
                  Regenerate
                </button>
              </div>

              {status.lowRecoveryCodes && (
                <div className="alert alert-warning mt-2 mb-0">
                  <i className="bi bi-exclamation-triangle me-2"></i>
                  You're running low on recovery codes. Consider regenerating
                  new ones.
                </div>
              )}
            </div>

            <hr />

            <button className="btn btn-outline-danger" onClick={handleDisable}>
              <i className="bi bi-shield-x me-1"></i>
              Disable MFA
            </button>
          </div>
        </div>
      ) : (
        <div className="card">
          <div className="card-body">
            <p className="text-muted mb-3">
              Multi-Factor Authentication (MFA) adds an extra layer of security
              to your account. When enabled, you'll need to do an additional
              verficiation step when performing sensitive actions like changing
              your password.
            </p>

            <button
              className="btn btn-primary"
              onClick={() => setShowSetupModal(true)}
            >
              Set Up MFA
            </button>
          </div>
        </div>
      )}

      {/* Setup Modal */}
      <TwoFactorSetupModal
        show={showSetupModal}
        onHide={() => setShowSetupModal(false)}
        onSuccess={handleSetupSuccess}
      />

      {/* Verify Modal for disable/regenerate */}
      <TwoFactorVerifyModal
        show={showVerifyModal}
        onHide={() => {
          setShowVerifyModal(false);
          setPendingAction(null);
        }}
        onSuccess={handleVerifySuccess}
        action={
          pendingAction === "disable" ? "2fa_disable" : "recovery_regenerate"
        }
        methods={
          status?.method === "totp"
            ? ["totp", "email", "recovery"]
            : ["email", "recovery"]
        }
      />

      {/* Recovery Codes Display Modal */}
      {showRecoveryCodes && (
        <div
          className="modal show d-block"
          tabIndex={-1}
          style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
        >
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content">
              <div className="modal-header">
                <h5 className="modal-title">New Recovery Codes</h5>
              </div>
              <div className="modal-body">
                <RecoveryCodesDisplay
                  codes={newRecoveryCodes}
                  onAcknowledge={() => {
                    setShowRecoveryCodes(false);
                    setNewRecoveryCodes([]);
                  }}
                  showAcknowledgeButton={true}
                />
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TwoFactorManagement;
