import { useState, useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import toast from "react-hot-toast";
import { setAccessToken, setRefreshToken } from "@/auth-state";
import { useAuth } from "@/contexts/AuthContext";
import "./Auth.css";

const AuthPage = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const mode = searchParams.get("mode"); // "signup" or null (signin)
  const isSignup = mode === "signup";
  
  const { initialize, currentUser } = useAuth();

  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  // If already logged in, redirect
  useEffect(() => {
    if (currentUser) {
      navigate("/app");
    }
  }, [currentUser, navigate]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const endpoint = isSignup ? "/api/v1/auth/register" : "/api/v1/auth/login";
      const payload = isSignup 
        ? { username, email, password }
        : { username, password };

      const res = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });
      
      const data = await res.json();
      
      if (!res.ok) {
        throw new Error(data.detail || "Authentication failed");
      }
      
      // Set token with expiry (1 day) so it persists in sessionStorage across tab switches
      const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
      setAccessToken(data.access_token, expiresAt);
      setRefreshToken(data.refresh_token ?? null);
      toast.success(isSignup ? "Account created successfully" : "Signed in successfully");
      await initialize(); // Refresh auth state
      navigate("/app");
    } catch (err: any) {
      toast.error(err.message || "Failed to authenticate");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-page">
      {/* Background */}
      <div className="auth-background">
        <div className="auth-gradient-orb orb-1"></div>
        <div className="auth-gradient-orb orb-2"></div>
        <div className="auth-gradient-orb orb-3"></div>
      </div>

      {/* Content */}
      <div className="auth-container">
        {/* Left Side - Branding */}
        <div className="auth-branding">
          <div className="auth-logo" onClick={() => navigate("/")}>
            <svg width="48" height="48" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect width="32" height="32" rx="8" fill="url(#authGradient)" />
              <path d="M10 16L14 20L22 12" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
              <defs>
                <linearGradient id="authGradient" x1="0" y1="0" x2="32" y2="32">
                  <stop stopColor="#6366f1" />
                  <stop offset="1" stopColor="#8b5cf6" />
                </linearGradient>
              </defs>
            </svg>
            <span>CuCu Note</span>
          </div>
          <h1 className="auth-title">
            {isSignup ? "Start your journey" : "Welcome back"}
          </h1>
          <p className="auth-subtitle">
            {isSignup
              ? "Create your account and start organizing your thoughts today."
              : "Sign in to continue to your notes and ideas."}
          </p>
          <div className="auth-features">
            <div className="auth-feature">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M22 11.08V12a10 10 0 11-5.93-9.14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M22 4L12 14.01l-3-3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              <span>Quick capture thoughts</span>
            </div>
            <div className="auth-feature">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M22 11.08V12a10 10 0 11-5.93-9.14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M22 4L12 14.01l-3-3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              <span>Built-in Privacy & EXIF Stripping</span>
            </div>
            <div className="auth-feature">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M22 11.08V12a10 10 0 11-5.93-9.14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M22 4L12 14.01l-3-3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              <span>Fully Local Authority</span>
            </div>
          </div>
        </div>

        {/* Right Side - Custom Auth Form */}
        <div className="auth-form-container">
          <div className="w-full flex flex-col justify-center items-center bg-white p-8 rounded-2xl shadow-sm border border-gray-100">
            <h2 className="text-2xl font-semibold mb-6 flex text-gray-800">
              {isSignup ? "Create an account" : "Sign in"}
            </h2>
            <form onSubmit={handleSubmit} className="w-full flex flex-col gap-4" data-testid="auth-form">
              <div className="flex flex-col gap-1.5">
                <label className="text-sm font-medium text-gray-700">Username</label>
                <input 
                  required
                  data-testid="auth-username"
                  className="px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                  placeholder="Enter your username" 
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                />
              </div>
              
              {isSignup && (
                <div className="flex flex-col gap-1.5">
                  <label className="text-sm font-medium text-gray-700">Email</label>
                  <input 
                    required
                    type="email"
                    data-testid="auth-email"
                    className="px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    placeholder="Enter your email" 
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
              )}

              <div className="flex flex-col gap-1.5">
                <label className="text-sm font-medium text-gray-700">Password</label>
                <input 
                  required
                  type="password"
                  data-testid="auth-password"
                  className="px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                  placeholder="Enter your password" 
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
              </div>

              <button 
                type="submit" 
                disabled={loading}
                data-testid="auth-submit"
                className="w-full mt-4 bg-indigo-600 text-white font-medium py-2 rounded-lg hover:bg-indigo-700 transition disabled:opacity-50"
              >
                {loading ? "Please wait..." : (isSignup ? "Sign Up" : "Sign In")}
              </button>
            </form>
            
            <p className="w-full mt-6 text-sm text-center">
              <span className="text-gray-500">
                {isSignup ? "Already have an account?" : "Don't have an account?"}
              </span>
              <button 
                type="button"
                data-testid="auth-toggle"
                onClick={() => navigate(isSignup ? "/auth" : "/auth?mode=signup")}
                className="cursor-pointer ml-2 text-indigo-600 font-medium hover:underline"
              >
                {isSignup ? "Sign In" : "Sign Up"}
              </button>
            </p>
          </div>
        </div>
      </div>

      {/* Back to Landing */}
      <button className="auth-back-btn" onClick={() => navigate("/")}>
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M15.833 10H4.167M10 15.833L4.167 10 10 4.167" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        Back to home
      </button>
    </div>
  );
};

export default AuthPage;
