"use client";

import React, { useEffect, useRef, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { BACKEND_URL } from "@/config/backend";

type VerifyState = "idle" | "loading" | "success" | "error";

interface VerificationResponse {
  success: boolean;
  data: { message: string; user: { email: string; username: string } };
  message: string;
  redirect?: string;
}
// Removed unused ErrorResponse interface

 

const EmailVerification: React.FC = () => {
  const searchParams = useSearchParams();
  const router = useRouter();

  const [status, setStatus] = useState<VerifyState>("idle");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  const token = searchParams.get("token");
  const didRun = useRef(false);

  useEffect(() => {
    if (!token) {
      setStatus("error");
      setError("No verification token found.");
      return;
    }
    if (didRun.current) return;
    didRun.current = true;

    void verifyEmail(token);
  }, [token]);

  const verifyEmail = async (verificationToken: string) => {
    setStatus("loading");
    setMessage("Verifying your email...");
    setError("");

    const ctrl = new AbortController();
    const timeout = setTimeout(() => ctrl.abort(), 10000);

    try {
      const res = await fetch(
        `${BACKEND_URL}/api/auth/verify-email?token=${verificationToken}&format=json`,
        { method: "GET", headers: { "Accept": "application/json" }, signal: ctrl.signal }
      );

      const txt = await res.text();
      console.log("Raw response text:", txt);
      console.log("Response status:", res.status);
      console.log("Response headers:", Object.fromEntries(res.headers.entries()));
      
      let data: Record<string, unknown> = {};
      try { data = JSON.parse(txt || "{}"); } catch { /* ignore non-JSON */ }
      console.log("Parsed response data:", data);

      if (res.ok && (data as unknown as VerificationResponse)?.success) {
        router.replace("/signin?verified=true");
        return;
      }

      const msg = String(data?.message || "").toLowerCase();
      if (msg.includes("already verified")) {
        // Check if there's a redirect URL in the response for already verified case too
        router.replace("/signin?verified=true");
        return;
      }

      setStatus("error");
      setError(String(data?.message) || `Verification failed (HTTP ${res.status}).`);
    } catch (e: unknown) {
      setStatus("error");
      const error = e as { name?: string };
      setError(error?.name === "AbortError" ? "Request timed out. Please try again." : "Network error. Please try again.");
      console.error("Email verification error:", e);
    } finally {
      clearTimeout(timeout);
    }
  };

  const handleResendVerification = async () => {
    setStatus("loading");
    setMessage("Sending verification email...");
    setError("");

    try {
      const email = prompt("Enter your email to resend the verification link:");
      if (!email) {
        setStatus("error");
        setError("Email is required to resend verification.");
        return;
      }

      const res = await fetch(`${BACKEND_URL}/api/auth/resend-verification`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();

      if (res.ok && data?.success) {
        setStatus("success");
        setMessage("Verification email sent! Please check your inbox.");
      } else {
        setStatus("error");
        setError(data?.message || "Failed to resend verification email.");
      }
    } catch (e) {
      setStatus("error");
      setError("Network error. Please try again.");
      console.error("Resend verification error:", e);
    }
  };

  if (status === "loading") {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-gray-900 mb-1">Verifying Email</h2>
          <p className="text-gray-600">{message}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4">
      <div className="max-w-md w-full space-y-6">
        {status === "success" && (
          <div className="bg-green-50 border border-green-200 rounded-md p-4 text-center">
            <p className="text-green-800 font-medium">{message || "Email verified. Redirecting..."}</p>
          </div>
        )}

        {status === "error" && (
          <div className="bg-red-50 border border-red-200 rounded-md p-4">
            <p className="text-red-800 font-medium text-center">{error}</p>
            <button
              onClick={handleResendVerification}
              className="mt-4 w-full py-2 rounded-md text-white bg-blue-600 hover:bg-blue-700"
            >
              Resend Verification Email
            </button>
          </div>
        )}

        <div className="flex gap-3">
          <button
            onClick={() => (window.location.href = "/auth")}
            className="w-1/2 py-2 rounded-md border bg-white text-gray-700 hover:bg-gray-50"
          >
            Go to Login
          </button>
          <button
            onClick={() => (window.location.href = "/")}
            className="w-1/2 py-2 rounded-md border bg-white text-gray-700 hover:bg-gray-50"
          >
            Go to Home
          </button>
        </div>
      </div>
    </div>
  );
};

export default EmailVerification;