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

interface TwoFactorSetupModalProps {
  show: boolean;
  onHide: () => void;
  onSuccess: () => void;
}

type SetupStep =
  | "choose"
  | "totp-qr"
  | "totp-verify"
  | "email-verify"
  | "recovery-codes";

const TwoFactorSetupModal: React.FC<TwoFactorSetupModalProps> = ({
  show,
  onHide,
  onSuccess,
}) => {
  const [step, setStep] = useState<SetupStep>("choose");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // TOTP setup state
  const [qrCodeDataUrl, setQrCodeDataUrl] = useState<string>("");
  const [verificationCode, setVerificationCode] = useState("");

  // Recovery codes
  const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);

  const resetState = () => {
    setStep("choose");
    setLoading(false);
    setError(null);
    setQrCodeDataUrl("");
    setVerificationCode("");
    setRecoveryCodes([]);
  };

  const handleClose = () => {
    resetState();
    onHide();
  };

  const handleInitTotp = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await twoFactorAPI.initTotpSetup();
      setQrCodeDataUrl(response.data.qrCodeDataUrl);
      setStep("totp-qr");
    } catch (err: any) {
      setError(err.response?.data?.error || "Failed to initialize TOTP setup");
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyTotp = async () => {
    if (verificationCode.length !== 6) {
      setError("Please enter a 6-digit code");
      return;
    }

    setLoading(true);
    setError(null);
    try {
      const response = await twoFactorAPI.verifyTotpSetup(verificationCode);
      setRecoveryCodes(response.data.recoveryCodes);
      setStep("recovery-codes");
    } catch (err: any) {
      setError(err.response?.data?.error || "Invalid verification code");
    } finally {
      setLoading(false);
    }
  };

  const handleInitEmailSetup = async () => {
    setLoading(true);
    setError(null);
    try {
      await twoFactorAPI.initEmailSetup();
      setStep("email-verify");
    } catch (err: any) {
      setError(
        err.response?.data?.error || "Failed to send verification email"
      );
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyEmail = async () => {
    if (verificationCode.length !== 6) {
      setError("Please enter a 6-digit code");
      return;
    }

    setLoading(true);
    setError(null);
    try {
      const response = await twoFactorAPI.verifyEmailSetup(verificationCode);
      setRecoveryCodes(response.data.recoveryCodes);
      setStep("recovery-codes");
    } catch (err: any) {
      setError(err.response?.data?.error || "Invalid verification code");
    } finally {
      setLoading(false);
    }
  };

  const handleComplete = () => {
    handleClose();
    onSuccess();
  };

  const handleCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/\D/g, "").slice(0, 6);
    setVerificationCode(value);
    setError(null);
  };

  if (!show) return null;

  const renderChooseMethod = () => (
    <>
      <div className="modal-header">
        <h5 className="modal-title">Set Up MFA</h5>
        <button
          type="button"
          className="btn-close"
          onClick={handleClose}
        ></button>
      </div>
      <div className="modal-body">
        <div className="d-grid gap-3">
          <button
            className="btn btn-outline-primary p-3 text-start"
            onClick={handleInitTotp}
            disabled={loading}
          >
            <div className="d-flex align-items-center">
              <i className="bi bi-phone fs-3 me-3"></i>
              <div>
                <strong>Authenticator App</strong>
                <span className="badge bg-success ms-2">Recommended</span>
                <br />
                <small className="text-muted">
                  Use Google Authenticator, Authy, or similar app
                </small>
              </div>
            </div>
          </button>

          <button
            className="btn btn-outline-secondary p-3 text-start"
            onClick={handleInitEmailSetup}
            disabled={loading}
          >
            <div className="d-flex align-items-center">
              <i className="bi bi-envelope fs-3 me-3"></i>
              <div>
                <strong>Email Verification</strong>
                <br />
                <small className="text-muted">
                  Receive codes via email when verification is needed
                </small>
              </div>
            </div>
          </button>
        </div>

        {error && (
          <div className="alert alert-danger mt-3 mb-0">
            <i className="bi bi-exclamation-circle me-2"></i>
            {error}
          </div>
        )}
      </div>
    </>
  );

  const renderTotpQR = () => (
    <>
      <div className="modal-header">
        <h5 className="modal-title">Scan QR Code</h5>
        <button
          type="button"
          className="btn-close"
          onClick={handleClose}
        ></button>
      </div>
      <div className="modal-body">
        <p className="text-muted mb-3">
          Scan this QR code with your authenticator app to add Village Share.
        </p>

        <div className="text-center mb-3">
          {qrCodeDataUrl && (
            <img
              src={qrCodeDataUrl}
              alt="QR Code for authenticator app"
              className="img-fluid border rounded"
              style={{ maxWidth: "200px" }}
            />
          )}
        </div>

        <button
          className="btn btn-primary w-100"
          onClick={() => setStep("totp-verify")}
        >
          Continue
        </button>
      </div>
    </>
  );

  const renderTotpVerify = () => (
    <>
      <div className="modal-header">
        <h5 className="modal-title">Enter Verification Code</h5>
        <button
          type="button"
          className="btn-close"
          onClick={handleClose}
        ></button>
      </div>
      <div className="modal-body">
        <p className="text-muted mb-3">
          Enter the 6-digit code from your authenticator app to verify the
          setup.
        </p>

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

        <div className="d-flex gap-2">
          <button
            className="btn btn-outline-secondary flex-fill"
            onClick={() => {
              setStep("totp-qr");
              setVerificationCode("");
              setError(null);
            }}
          >
            Back
          </button>
          <button
            className="btn btn-primary flex-fill"
            onClick={handleVerifyTotp}
            disabled={loading || verificationCode.length !== 6}
          >
            {loading ? (
              <>
                <span className="spinner-border spinner-border-sm me-2"></span>
                Verifying...
              </>
            ) : (
              "Verify"
            )}
          </button>
        </div>
      </div>
    </>
  );

  const renderEmailVerify = () => (
    <>
      <div className="modal-header">
        <h5 className="modal-title">Check Your Email</h5>
        <button
          type="button"
          className="btn-close"
          onClick={handleClose}
        ></button>
      </div>
      <div className="modal-body">
        <div className="text-center mb-3">
          <i className="bi bi-envelope-check fs-1 text-primary"></i>
        </div>

        <p className="text-muted mb-3 text-center">
          We've sent a 6-digit verification code to your email address. Enter it
          below to complete setup.
        </p>

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

        <div className="d-flex gap-2">
          <button
            className="btn btn-outline-secondary flex-fill"
            onClick={() => {
              setStep("choose");
              setVerificationCode("");
              setError(null);
            }}
          >
            Back
          </button>
          <button
            className="btn btn-primary flex-fill"
            onClick={handleVerifyEmail}
            disabled={loading || verificationCode.length !== 6}
          >
            {loading ? (
              <>
                <span className="spinner-border spinner-border-sm me-2"></span>
                Verifying...
              </>
            ) : (
              "Verify"
            )}
          </button>
        </div>
      </div>
    </>
  );

  const renderRecoveryCodes = () => (
    <>
      <div className="modal-header">
        <h5 className="modal-title">Save Your Recovery Codes</h5>
      </div>
      <div className="modal-body">
        <RecoveryCodesDisplay
          codes={recoveryCodes}
          onAcknowledge={handleComplete}
          showAcknowledgeButton={true}
        />
      </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">
          {step === "choose" && renderChooseMethod()}
          {step === "totp-qr" && renderTotpQR()}
          {step === "totp-verify" && renderTotpVerify()}
          {step === "email-verify" && renderEmailVerify()}
          {step === "recovery-codes" && renderRecoveryCodes()}
        </div>
      </div>
    </div>
  );
};

export default TwoFactorSetupModal;
