"use client";
import { useRouter } from "next/navigation";
import { useAuth } from "./context/AuthContext";
import { useState, useEffect } from "react";
import Link from "next/link";
import Button1 from "./ui/buttons/button1";
import { account, ID } from "./lib/appwrite";

export default function AuthPage() {
  const router = useRouter();
  const { isAuthenticated, loading: authLoading, setIsAuthenticated } = useAuth();
  const [isLoginForm, setIsLoginForm] = useState(true);
  const [darkMode, setDarkMode] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

  // Form states
  const [loginData, setLoginData] = useState({
    email: "",
    password: "",
    rememberMe: false,
  });

  const [signupData, setSignupData] = useState({
    fname: "",
    lname: "",
    email: "",
    password: "",
    agreeTerms: false,
  });

  const [errors, setErrors] = useState({
    agreeTerms: "",
    general: "",
  });

  useEffect(() => {
    if (!authLoading && isAuthenticated) {
      router.push("/dashboard");
    }
  }, [isAuthenticated, authLoading, router]);

  const handleLoginChange = (e) => {
    const { name, value, type, checked } = e.target;
    setLoginData({
      ...loginData,
      [name]: type === "checkbox" ? checked : value,
    });
  };

  const handleSignupChange = (e) => {
    const { name, value, type, checked } = e.target;
    setSignupData({
      ...signupData,
      [name]: type === "checkbox" ? checked : value,
    });
    if (name === "agreeTerms") {
      setErrors({ ...errors, agreeTerms: "" });
    }
  };

  const validateSignupForm = () => {
    let isValid = true;
    const newErrors = { ...errors };

    if (!signupData.agreeTerms) {
      newErrors.agreeTerms = "You must agree to the terms and conditions";
      isValid = false;
    } else {
      newErrors.agreeTerms = "";
    }

    setErrors(newErrors);
    return isValid;
  };

  const handleLogin = async (e) => {
    e.preventDefault();
    setLoading(true);
    setErrors({ ...errors, general: "" });

    try {
      const session = await account.createEmailPasswordSession(
        loginData.email,
        loginData.password
      );
      
      if (session) {
        const user = await account.get();
        if (user) {
          localStorage.setItem("isLoggedIn", "true");
          setIsAuthenticated(true);
          router.push("/dashboard");
        }
      }
    } catch (error) {
      let errorMessage = 'Login failed. Please try again.';
      if (error.type === 'user_invalid_credentials') {
        errorMessage = 'Invalid email or password';
      } else if (error.type === 'general_argument_invalid') {
        errorMessage = 'Invalid email format';
      }
      setErrors({ ...errors, general: errorMessage });
    } finally {
      setLoading(false);
    }
  };

  const handleSignup = async (e) => {
    e.preventDefault();

    if (!validateSignupForm()) {
      return;
    }

    setLoading(true);
    setErrors({ ...errors, general: "" });

    try {
      await account.create(
        ID.unique(),
        signupData.email,
        signupData.password,
        `${signupData.fname} ${signupData.lname}`
      );
      await account.createEmailPasswordSession(signupData.email, signupData.password);
      const user = await account.get();
      if (user) {
        localStorage.setItem("isLoggedIn", "true");
        setIsAuthenticated(true);
        router.push("/dashboard");
      }
    } catch (error) {
      console.error("Signup error:", error);
      setErrors({
        ...errors,
        general: error.message || "Signup failed. Please try again.",
      });
    } finally {
      setLoading(false);
    }
  };

  if (authLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 dark:border-gray-100 mx-auto"></div>
          <p className="mt-4 text-lg font-semibold text-gray-900 dark:text-gray-100">
            Loading...
          </p>
        </div>
      </div>
    );
  }

  if (isAuthenticated) {
    return null;
  }

  return (
    <div className={`min-h-screen ${darkMode ? "dark bg-gray-900" : "bg-white"}`}>
      <div className="flex flex-col items-center justify-center p-6">
        <div className="w-full max-w-md">
          <div className="mb-8">
            <h1 className="text-2xl font-bold text-gray-800 dark:text-white/90">
              {isLoginForm ? "Sign In" : "Sign Up"}
            </h1>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {isLoginForm 
                ? "Enter your email and password to sign In!" 
                : "Enter your deatils to create an account!"}
            </p>
          </div>

          {errors.general && (
            <div className="mb-4 p-3 text-sm text-red-600 bg-red-50 rounded-lg dark:bg-red-900/20 dark:text-red-300">
              {errors.general}
            </div>
          )}

          {isLoginForm ? (
            // Login Form
            <form onSubmit={handleLogin} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Email*
                </label>
                <input
                  type="email"
                  name="email"
                  value={loginData.email}
                  onChange={handleLoginChange}
                  className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:border-gray-700 dark:text-white"
                  placeholder="your@email.com"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Password*
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? "text" : "password"}
                    name="password"
                    value={loginData.password}
                    onChange={handleLoginChange}
                    className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:border-gray-700 dark:text-white"
                    placeholder="••••••••"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 dark:text-gray-400"
                  >
                    {showPassword ? "Hide" : "Show"}
                  </button>
                </div>
              </div>

              <div className="flex items-center justify-between">
                <label className="flex items-center space-x-2 text-sm text-gray-700 dark:text-gray-300">
                  <input
                    type="checkbox"
                    name="rememberMe"
                    checked={loginData.rememberMe}
                    onChange={handleLoginChange}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700"
                  />
                  <span>Remember me</span>
                </label>

                <a href="#" className="text-sm text-blue-600 hover:underline dark:text-blue-400">
                  Forgot password?
                </a>
              </div>

              <Button1
                type="submit"
                className="w-full py-2 px-4 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition"
                disabled={loading}
              >
                {loading ? "Signing in..." : "Sign in"}
              </Button1>
            </form>
          ) : (
            // Sign Up Form
            <form onSubmit={handleSignup} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    First Name*
                  </label>
                  <input
                    type="text"
                    name="fname"
                    value={signupData.fname}
                    onChange={handleSignupChange}
                    className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:border-gray-700 dark:text-white"
                    placeholder="John"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Last Name*
                  </label>
                  <input
                    type="text"
                    name="lname"
                    value={signupData.lname}
                    onChange={handleSignupChange}
                    className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:border-gray-700 dark:text-white"
                    placeholder="Doe"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Email*
                </label>
                <input
                  type="email"
                  name="email"
                  value={signupData.email}
                  onChange={handleSignupChange}
                  className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:border-gray-700 dark:text-white"
                  placeholder="your@email.com"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Password*
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? "text" : "password"}
                    name="password"
                    value={signupData.password}
                    onChange={handleSignupChange}
                    className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:border-gray-700 dark:text-white"
                    placeholder="••••••••"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 dark:text-gray-400"
                  >
                    {showPassword ? "Hide" : "Show"}
                  </button>
                </div>
              </div>

              <div>
                <label className="flex items-start space-x-2 text-sm text-gray-700 dark:text-gray-300">
                  <input
                    type="checkbox"
                    name="agreeTerms"
                    checked={signupData.agreeTerms}
                    onChange={handleSignupChange}
                    className="mt-1 rounded border-gray-300 text-blue-600 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700"
                  />
                  <span>
                    By creating an account means you agree to <a href="#" className="text-blue-600 hover:underline dark:text-blue-400">Terms</a>and<a href="#" className="text-blue-600 hover:underline dark:text-blue-400">Conditions</a> and our <a href="#" className="text-blue-600 hover:underline dark:text-blue-400">Privacy Policy</a>
                  </span>
                </label>
                {errors.agreeTerms && (
                  <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                    {errors.agreeTerms}
                  </p>
                )}
              </div>

              <Button1
                type="submit"
                className="w-full py-2 px-4 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition"
                disabled={loading}
              >
                {loading ? "Creating account..." : "Sign up"}
              </Button1>
            </form>
          )}

          <div className="mt-6 text-center">
            <p className="text-sm text-gray-600 dark:text-gray-400">
              {isLoginForm ? "Don't have an account?" : "Already have an account?"}
              <button
                onClick={() => setIsLoginForm(!isLoginForm)}
                className="ml-1 text-blue-600 hover:underline dark:text-blue-400 font-medium"
              >
                {isLoginForm ? "Sign up" : "Sign in"}
              </button>
            </p>
          </div>
        </div>
      </div>

      {/* Dark mode toggle */}
      <button
        onClick={() => setDarkMode(!darkMode)}
        className="fixed bottom-6 right-6 p-3 rounded-full bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200"
      >
        {darkMode ? (
          <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path fillRule="evenodd" d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z" clipRule="evenodd" />
          </svg>
        ) : (
          <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z" />
          </svg>
        )}
      </button>
    </div>
  );
}