import React, { useState, useEffect } from "react";
import { twoFactorAPI } from "../../services/api";

interface TwoFactorVerifyModalProps {
  show: boolean;
  onHide: () => void;
  onSuccess: () => void;
  action?: string;
  methods?: ("totp" | "email" | "recovery")[];
}

const TwoFactorVerifyModal: React.FC<TwoFactorVerifyModalProps> = ({
  show,
  onHide,
  onSuccess,
  action,
  methods = ["totp", "email", "recovery"],
}) => {
  const [activeTab, setActiveTab] = useState<"totp" | "email" | "recovery">(
    methods[0] || "totp"
  );
  const [code, setCode] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [emailSent, setEmailSent] = useState(false);

  // Reset state when modal opens/closes
  useEffect(() => {
    if (show) {
      setCode("");
      setError(null);
      setEmailSent(false);
      setActiveTab(methods[0] || "totp");
    }
  }, [show, methods]);

  const getActionDescription = (actionType?: string) => {
    switch (actionType) {
      case "password_change":
        return "change your password";
      case "email_change":
        return "change your email address";
      case "payout":
        return "request a payout";
      case "account_delete":
        return "delete your account";
      case "2fa_disable":
        return "disable multi-factor authentication";
      case "recovery_regenerate":
        return "regenerate recovery codes";
      default:
        return "complete this action";
    }
  };

  const handleCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let value = e.target.value;

    if (activeTab === "recovery") {
      // Format recovery code: XXXX-XXXX
      value = value.toUpperCase().replace(/[^A-Z0-9-]/g, "");
      if (value.length > 4 && !value.includes("-")) {
        value = value.slice(0, 4) + "-" + value.slice(4);
      }
      value = value.slice(0, 9);
    } else {
      // TOTP and email: 6 digits only
      value = value.replace(/\D/g, "").slice(0, 6);
    }

    setCode(value);
    setError(null);
  };

  const handleSendEmailOtp = async () => {
    setLoading(true);
    setError(null);
    try {
      await twoFactorAPI.requestEmailOtp();
      setEmailSent(true);
    } catch (err: any) {
      setError(err.response?.data?.error || "Failed to send verification code");
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = async () => {
    setLoading(true);
    setError(null);

    try {
      let response;

      switch (activeTab) {
        case "totp":
          response = await twoFactorAPI.verifyTotp(code);
          break;
        case "email":
          response = await twoFactorAPI.verifyEmailOtp(code);
          break;
        case "recovery":
          response = await twoFactorAPI.verifyRecoveryCode(code);
          break;
      }

      onSuccess();
      onHide();
    } catch (err: any) {
      setError(err.response?.data?.error || "Verification failed");
    } finally {
      setLoading(false);
    }
  };

  const isCodeValid = () => {
    if (activeTab === "recovery") {
      return /^[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(code);
    }
    return code.length === 6;
  };

  if (!show) return null;

  const renderTotpTab = () => (
    <div className="p-3">
      <p className="text-muted mb-3">
        Enter the 6-digit code from your authenticator app.
      </p>

      <input
        type="text"
        className={`form-control form-control-lg text-center font-monospace mb-3 ${
          error && activeTab === "totp" ? "is-invalid" : ""
        }`}
        placeholder="000000"
        value={code}
        onChange={handleCodeChange}
        maxLength={6}
        autoFocus
        style={{ letterSpacing: "0.5em" }}
      />
    </div>
  );

  const renderEmailTab = () => (
    <div className="p-3">
      {!emailSent ? (
        <>
          <p className="text-muted mb-3">
            We'll send a verification code to your email address.
          </p>
          <button
            className="btn btn-primary w-100"
            onClick={handleSendEmailOtp}
            disabled={loading}
          >
            {loading ? (
              <>
                <span className="spinner-border spinner-border-sm me-2"></span>
                Sending...
              </>
            ) : (
              <>
                <i className="bi bi-envelope me-2"></i>
                Send Verification Code
              </>
            )}
          </button>
        </>
      ) : (
        <>
          <div className="alert alert-success mb-3">
            <i className="bi bi-check-circle me-2"></i>
            Verification code sent to your email.
          </div>

          <input
            type="text"
            className={`form-control form-control-lg text-center font-monospace mb-3 ${
              error && activeTab === "email" ? "is-invalid" : ""
            }`}
            placeholder="000000"
            value={code}
            onChange={handleCodeChange}
            maxLength={6}
            autoFocus
            style={{ letterSpacing: "0.5em" }}
          />

          <button
            className="btn btn-link btn-sm p-0"
            onClick={handleSendEmailOtp}
            disabled={loading}
          >
            Resend code
          </button>
        </>
      )}
    </div>
  );

  const renderRecoveryTab = () => (
    <div className="p-3">
      <p className="text-muted mb-3">
        Enter one of your recovery codes. Each code can only be used once.
      </p>

      <input
        type="text"
        className={`form-control form-control-lg text-center font-monospace mb-3 ${
          error && activeTab === "recovery" ? "is-invalid" : ""
        }`}
        placeholder="XXXX-XXXX"
        value={code}
        onChange={handleCodeChange}
        maxLength={9}
        autoFocus
        style={{ letterSpacing: "0.2em" }}
      />
    </div>
  );

  return (
    <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">
              <i className="bi bi-shield-lock me-2"></i>
              Verify Your Identity
            </h5>
            <button type="button" className="btn-close" onClick={onHide}></button>
          </div>
          <div className="modal-body p-0">
            <div className="p-3 pb-0">
              <p className="text-muted mb-0">
                Multi-factor authentication is required to {getActionDescription(action)}.
              </p>
            </div>

            <ul className="nav nav-tabs px-3 pt-3">
              {methods.includes("totp") && (
                <li className="nav-item">
                  <button
                    className={`nav-link ${activeTab === "totp" ? "active" : ""}`}
                    onClick={() => {
                      setActiveTab("totp");
                      setCode("");
                      setError(null);
                    }}
                  >
                    <i className="bi bi-phone me-1"></i>
                    App
                  </button>
                </li>
              )}
              {methods.includes("email") && (
                <li className="nav-item">
                  <button
                    className={`nav-link ${activeTab === "email" ? "active" : ""}`}
                    onClick={() => {
                      setActiveTab("email");
                      setCode("");
                      setError(null);
                    }}
                  >
                    <i className="bi bi-envelope me-1"></i>
                    Email
                  </button>
                </li>
              )}
              {methods.includes("recovery") && (
                <li className="nav-item">
                  <button
                    className={`nav-link ${activeTab === "recovery" ? "active" : ""}`}
                    onClick={() => {
                      setActiveTab("recovery");
                      setCode("");
                      setError(null);
                    }}
                  >
                    <i className="bi bi-key me-1"></i>
                    Recovery
                  </button>
                </li>
              )}
            </ul>

            {activeTab === "totp" && renderTotpTab()}
            {activeTab === "email" && renderEmailTab()}
            {activeTab === "recovery" && renderRecoveryTab()}

            {error && (
              <div className="px-3 pb-3">
                <div className="alert alert-danger mb-0">
                  <i className="bi bi-exclamation-circle me-2"></i>
                  {error}
                </div>
              </div>
            )}
          </div>
          <div className="modal-footer">
            <button className="btn btn-outline-secondary" onClick={onHide}>
              Cancel
            </button>
            {(activeTab !== "email" || emailSent) && (
              <button
                className="btn btn-primary"
                onClick={handleVerify}
                disabled={loading || !isCodeValid()}
              >
                {loading ? (
                  <>
                    <span className="spinner-border spinner-border-sm me-2"></span>
                    Verifying...
                  </>
                ) : (
                  "Verify"
                )}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default TwoFactorVerifyModal;
