"use client";

import { useState } from "react";
import { apiCall } from "@/utils/callApi";
import { useRouter, useSearchParams } from "next/navigation";
import { toast } from "sonner";
import { useAuthContext } from "@/contexts/AuthProvider";
import Link from "next/link";

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { login } = useAuthContext();
  const nextPath = searchParams.get("next") || "/dashboard";

  const [form, setForm] = useState({
    email: "",
    password: "",
  });
  const [errors, setErrors] = useState({
    email: "",
    password: "",
  });
  const [rememberMe, setRememberMe] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;

    setForm((prev) => ({
      ...prev,
      [name]: value,
    }));

    setErrors((prev) => ({
      ...prev,
      [name]: "",
    }));
  };

  const validate = () => {
    const newErrors = {
      email: "",
      password: "",
    };

    let isValid = true;

    if (!form.email.trim()) {
      newErrors.email = "Email is required";
      isValid = false;
    } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(form.email)) {
      newErrors.email = "Please enter a valid email address";
      isValid = false;
    }

    if (!form.password.trim()) {
      newErrors.password = "Password is required";
      isValid = false;
    }

    setErrors(newErrors);
    return isValid;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validate()) {
      return;
    }

    try {
      setLoading(true);

      const res = await apiCall<any>("/clientapi/login", {
        method: "POST",
        body: {
          email: form.email.trim(),
          password: form.password,
          guestId: localStorage.getItem("guestId"),
          rememberMe: rememberMe,
        },
      });

      if (res?.data?.success) {
        const { token, user } = res.data.data;

        login(user, token);

        toast.success("Login successful");

        const redirectTo = nextPath && nextPath.startsWith("/") ? nextPath : "/dashboard";

        router.replace(redirectTo);
        router.refresh();
        // window.location.href = redirectTo;
      } else {
        toast.error(res?.error || res?.data?.message || "Login failed");
      }
    } catch (error: any) {
      toast.error(error?.message || error?.response?.data?.message || "Failed to login");
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* Hero Section */}
      <section className="py-6 md:py-10 2xl:py-16">
        <div className="container container-xxl px-3 mx-auto">
          <div className="flex flex-wrap -mx-2 justify-center">
            <div className="2xl:w-9/12 xl:w-9/12 lg:w-10/12 md:w-full sm:w-full w-full px-2">
              <div className="w-full bg-white shadow-xl overflow-hidden rounded-xl">
                <div className="grid md:grid-cols-2">
                  
                  {/* Left Section - Welcome Message */}
                  <div className="bg-[linear-gradient(to_bottom_right,#dda16b,#dda16ba6,#dda16b)] text-white flex flex-col justify-center items-center px-6 py-6 sm:px-8 sm:py-12 lg:px-10 lg:py-16 text-center">
                    <h1 className="text-2xl md:text-4xl 3xl:text-5xl font-bold mb-2 lg:mb-4">
                      Hello, There!
                    </h1>
                    <p className="text-sm md:text-base lg:text-lg 2xl:text-xl leading-relaxed max-w-sm mb-4 lg:mb-8">
                      Enter your personal details and start your journey with us.
                    </p>
                    <Link href="/register" className="default-btn inline-block px-6 py-2 bg-white text-[#dda16b] rounded-lg hover:bg-gray-100 transition">
                      Sign Up
                    </Link>
                  </div>
                  
                  {/* Right Section - Login Form */}
                  <div className="px-4 py-4 sm:px-8 sm:py-8 md:px-10 md:py-12 xl:px-12 xl:py-14 flex flex-col justify-center">
                    <h2 className="text-2xl md:text-4xl 2xl:text-5xl font-bold text-gray-800 text-center mb-4 lg:mb-8">
                      Sign In
                    </h2>
                    
                    <form onSubmit={handleSubmit} className="space-y-4">
                      {/* Email / Username */}
                      <div className="form-group">
                        <label className="block text-sm md:text-sm 2xl:text-lg font-medium text-gray-700 mb-1">
                          Email / User
                        </label>
                        <input
                          type="email"
                          name="email"
                          value={form.email}
                          onChange={handleChange}
                          placeholder="Enter your email"
                          className={`form-control h-[40px] md:h-[44px] lg:h-[48px] 2xl:h-[60px] text-xs lg:text-sm 2xl:text-lg w-full border rounded-lg px-3 focus:outline-none focus:ring-2 focus:ring-primary ${
                            errors.email ? 'border-red-500' : 'border-gray-300'
                          }`}
                        />
                        {errors.email && (
                          <p className="text-red-500 text-xs mt-1">{errors.email}</p>
                        )}
                      </div>
                      
                      {/* Password */}
                      <div className="form-group">
                        <label className="block text-sm md:text-sm 2xl:text-lg font-medium text-gray-700 mb-1">
                          Password
                        </label>
                        <input
                          type="password"
                          name="password"
                          value={form.password}
                          onChange={handleChange}
                          placeholder="Enter your password"
                          className={`form-control h-[40px] md:h-[44px] lg:h-[48px] 2xl:h-[60px] text-xs lg:text-sm 2xl:text-lg w-full border rounded-lg px-3 focus:outline-none focus:ring-2 focus:ring-primary ${
                            errors.password ? 'border-red-500' : 'border-gray-300'
                          }`}
                        />
                        {errors.password && (
                          <p className="text-red-500 text-xs mt-1">{errors.password}</p>
                        )}
                      </div>
                      
                      {/* Remember & Forgot */}
                      <div className="flex items-center justify-between text-sm">
                        {/* <label className="flex items-center gap-2 cursor-pointer text-xs lg:text-sm 2xl:text-lg">
                          <input
                            type="checkbox"
                            checked={rememberMe}
                            onChange={(e) => setRememberMe(e.target.checked)}
                            className="rounded text-primary focus:ring-primary"
                          />
                          <span className="text-gray-600">
                            Remember this Device
                          </span>
                        </label> */}
                        {/* <Link
                          href="/forgot-password"
                          className="text-xs lg:text-sm 2xl:text-lg text-primary hover:text-primary/85 font-medium"
                        >
                          Forgot Password?
                        </Link> */}
                      </div>
                      
                      {/* Sign In Button */}
                      <button
                        type="submit"
                        disabled={loading}
                        className="w-full theme-btn h-[40px] md:h-[44px] lg:h-[48px] 2xl:h-[60px] bg-primary text-white rounded-lg hover:bg-primary-dark transition disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {loading ? (
                          <span className="flex items-center justify-center gap-2">
                            <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            Signing In...
                          </span>
                        ) : (
                          "Sign In"
                        )}
                      </button>
                    </form>
                    
                    {/* Footer */}
                    <p className="text-center text-gray-600 text-xs lg:text-sm 2xl:text-lg mt-5">
                      Don't have an account?
                      <Link href="/register" className="text-primary font-semibold hover:text-primary/85 ml-1">
                        Create an account
                      </Link>
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}