import React, { useEffect, useState, useRef } from "react";
import { useNavigate, useSearchParams, Link } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext";
import { authAPI } from "../services/api";

const VerifyEmail: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { checkAuth, user, loading: authLoading } = useAuth();
  const [error, setError] = useState<string>("");
  const [errorCode, setErrorCode] = useState<string>("");
  const [success, setSuccess] = useState(false);
  const [processing, setProcessing] = useState(true);
  const [resending, setResending] = useState(false);
  const [resendSuccess, setResendSuccess] = useState(false);
  const [resendCooldown, setResendCooldown] = useState(0);
  const [showManualEntry, setShowManualEntry] = useState(false);
  const [code, setCode] = useState<string[]>(["", "", "", "", "", ""]);
  const [verifying, setVerifying] = useState(false);
  const hasProcessed = useRef(false);
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

  // Handle resend cooldown timer
  useEffect(() => {
    if (resendCooldown > 0) {
      const timer = setTimeout(
        () => setResendCooldown(resendCooldown - 1),
        1000
      );
      return () => clearTimeout(timer);
    }
  }, [resendCooldown]);

  // Clear resend success after 3 seconds
  useEffect(() => {
    if (resendSuccess) {
      const timer = setTimeout(() => setResendSuccess(false), 3000);
      return () => clearTimeout(timer);
    }
  }, [resendSuccess]);

  // Check authentication and handle verification
  useEffect(() => {
    // Wait for auth to finish loading
    if (authLoading) return;

    const handleVerification = async () => {
      // Prevent double execution in React StrictMode
      if (hasProcessed.current) return;
      hasProcessed.current = true;

      const token = searchParams.get("token");

      // If not logged in, redirect to login with return URL
      if (!user) {
        const returnUrl = token
          ? `/verify-email?token=${token}`
          : "/verify-email";
        navigate(`/?login=true&redirect=${encodeURIComponent(returnUrl)}`, {
          replace: true,
        });
        return;
      }

      // If user is already verified, show success
      if (user.isVerified) {
        setSuccess(true);
        setProcessing(false);
        setTimeout(() => navigate("/", { replace: true }), 3000);
        return;
      }

      // If no token in URL, show manual entry form
      if (!token) {
        setShowManualEntry(true);
        setProcessing(false);
        return;
      }

      // Auto-verify with token from URL
      try {
        await authAPI.verifyEmail(token);
        setSuccess(true);
        setProcessing(false);
        await checkAuth();
        setTimeout(() => navigate("/", { replace: true }), 3000);
      } catch (err: any) {
        handleVerificationError(err);
        setProcessing(false);
      }
    };

    handleVerification();
  }, [searchParams, navigate, checkAuth, user, authLoading]);

  const handleVerificationError = (err: any) => {
    const errorData = err.response?.data;
    const code = errorData?.code || "";
    setErrorCode(code);

    switch (code) {
      case "VERIFICATION_EXPIRED":
        setError(
          "Your verification code has expired. Please request a new code below."
        );
        setShowManualEntry(true);
        break;
      case "VERIFICATION_INVALID":
        setError(
          "That code didn't match. Please try again or request a new code below."
        );
        setShowManualEntry(true);
        break;
      case "TOO_MANY_ATTEMPTS":
        setError("Too many attempts. Please request a new code below.");
        setShowManualEntry(true);
        break;
      case "ALREADY_VERIFIED":
        setError("Your email is already verified.");
        break;
      case "NO_CODE":
        setError(
          "No verification code found. Please request a new code below."
        );
        setShowManualEntry(true);
        break;
      default:
        setError(
          errorData?.error || "Failed to verify email. Please try again."
        );
        setShowManualEntry(true);
    }
  };

  const handleInputChange = (index: number, value: string) => {
    if (value && !/^\d$/.test(value)) return;

    const newCode = [...code];
    newCode[index] = value;
    setCode(newCode);
    setError("");
    setErrorCode("");

    if (value && index < 5) {
      inputRefs.current[index + 1]?.focus();
    }

    if (value && index === 5 && newCode.every((d) => d !== "")) {
      handleManualVerify(newCode.join(""));
    }
  };

  const handleKeyDown = (index: number, e: React.KeyboardEvent) => {
    if (e.key === "Backspace" && !code[index] && index > 0) {
      inputRefs.current[index - 1]?.focus();
    }
  };

  const handlePaste = (e: React.ClipboardEvent) => {
    e.preventDefault();
    const pastedData = e.clipboardData
      .getData("text")
      .replace(/\D/g, "")
      .slice(0, 6);
    if (pastedData.length === 6) {
      const newCode = pastedData.split("");
      setCode(newCode);
      handleManualVerify(pastedData);
    }
  };

  const handleManualVerify = async (verificationCode: string) => {
    setVerifying(true);
    setError("");
    setErrorCode("");

    try {
      await authAPI.verifyEmail(verificationCode);
      setSuccess(true);
      await checkAuth();
      setTimeout(() => navigate("/", { replace: true }), 3000);
    } catch (err: any) {
      handleVerificationError(err);
      setCode(["", "", "", "", "", ""]);
      inputRefs.current[0]?.focus();
    } finally {
      setVerifying(false);
    }
  };

  const handleResendVerification = async () => {
    setResending(true);
    setError("");
    setErrorCode("");
    setResendSuccess(false);

    try {
      await authAPI.resendVerification();
      setResendSuccess(true);
      setResendCooldown(60);
      setCode(["", "", "", "", "", ""]);
      inputRefs.current[0]?.focus();
    } catch (err: any) {
      const errorData = err.response?.data;
      if (errorData?.code === "ALREADY_VERIFIED") {
        setError("Your email is already verified.");
      } else if (err.response?.status === 429) {
        setError("Please wait before requesting another code.");
      } else {
        setError(
          errorData?.error ||
            "Failed to resend verification email. Please try again."
        );
      }
    } finally {
      setResending(false);
    }
  };

  // Show loading while auth is initializing
  if (authLoading) {
    return (
      <div className="container">
        <div className="row justify-content-center mt-5">
          <div className="col-md-6">
            <div className="card">
              <div className="card-body text-center py-5">
                <div className="spinner-border text-primary mb-3" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
                <h5>Loading...</h5>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container">
      <div className="row justify-content-center mt-5">
        <div className="col-md-6">
          <div className="card">
            <div className="card-body text-center py-5">
              {processing ? (
                <>
                  <div
                    className="spinner-border text-primary mb-3"
                    role="status"
                  >
                    <span className="visually-hidden">Loading...</span>
                  </div>
                  <h5>Verifying Your Email...</h5>
                  <p className="text-muted">
                    Please wait while we verify your email address.
                  </p>
                </>
              ) : success ? (
                <>
                  <i
                    className="bi bi-check-circle text-success"
                    style={{ fontSize: "3rem" }}
                  ></i>
                  <h5 className="mt-3">Email Verified Successfully!</h5>
                  <p className="text-muted">
                    Your email has been verified. You will be redirected
                    shortly.
                  </p>
                  <Link to="/" className="btn btn-success mt-3">
                    Go to Home Page
                  </Link>
                </>
              ) : showManualEntry ? (
                <>
                  <i
                    className="bi bi-envelope-check text-success"
                    style={{ fontSize: "3rem" }}
                  ></i>
                  <h5 className="mt-3">Enter Verification Code</h5>
                  <p className="text-muted">
                    Enter the 6-digit code sent to your email
                  </p>

                  {error && (
                    <div className="alert alert-danger py-2" role="alert">
                      {error}
                    </div>
                  )}

                  {resendSuccess && (
                    <div className="alert alert-success py-2" role="alert">
                      New code sent! Check your email.
                    </div>
                  )}

                  {/* 6-digit code input */}
                  <div
                    className="d-flex justify-content-center gap-2 my-4"
                    onPaste={handlePaste}
                  >
                    {code.map((digit, index) => (
                      <input
                        key={index}
                        ref={(el) => {
                          inputRefs.current[index] = el;
                        }}
                        type="text"
                        inputMode="numeric"
                        maxLength={1}
                        value={digit}
                        onChange={(e) =>
                          handleInputChange(index, e.target.value)
                        }
                        onKeyDown={(e) => handleKeyDown(index, e)}
                        className="form-control text-center"
                        style={{
                          width: "50px",
                          height: "60px",
                          fontSize: "24px",
                          fontWeight: "bold",
                        }}
                        disabled={verifying}
                      />
                    ))}
                  </div>

                  <button
                    className="btn btn-success w-100 py-3"
                    onClick={() => handleManualVerify(code.join(""))}
                    disabled={verifying || code.some((d) => d === "")}
                  >
                    {verifying ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2" />
                        Verifying...
                      </>
                    ) : (
                      "Verify Email"
                    )}
                  </button>

                  <div className="mt-4">
                    <p className="text-muted small mb-2">
                      Didn't receive the code?
                    </p>
                    <button
                      className="btn btn-link text-decoration-none p-0"
                      onClick={handleResendVerification}
                      disabled={resending || resendCooldown > 0}
                    >
                      {resendCooldown > 0
                        ? `Resend in ${resendCooldown}s`
                        : resending
                        ? "Sending..."
                        : "Send Code"}
                    </button>
                  </div>

                  <p className="text-muted small mt-3">
                    Check your spam folder if you don't see the email.
                  </p>

                  <Link to="/" className="btn btn-outline-secondary mt-3">
                    Return to Home
                  </Link>
                </>
              ) : error ? (
                <>
                  <i
                    className="bi bi-exclamation-circle text-danger"
                    style={{ fontSize: "3rem" }}
                  ></i>
                  <h5 className="mt-3">Verification Failed</h5>
                  <p className="text-danger">{error}</p>
                  <div className="mt-3">
                    <Link to="/" className="btn btn-outline-secondary">
                      Return to Home
                    </Link>
                  </div>
                </>
              ) : null}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VerifyEmail;
