"use client";

import { useSigninMutation } from "@/api/auth.api";
import { ISigninRequest } from "@/api/types/auth";
import { parseApiError } from "@/api/utils/error-handler";
import { setAuthTokens } from "@/lib/auth-cookies";
import { useAppDispatch, useAppSelector } from "@/redux/hooks";
import { setCredentials } from "@/redux/slices/authSlice";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "react-hot-toast";

export default function LoginPage() {
  const [signin, { isLoading }] = useSigninMutation();
  const [showPassword, setShowPassword] = useState(false);
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { isAuthenticated } = useAppSelector((state) => state.auth);

  // Return the user to wherever they came from after signing in. Only relative
  // paths are honoured to avoid open redirects.
  const [redirectTo, setRedirectTo] = useState("/");
  useEffect(() => {
    const r = new URLSearchParams(window.location.search).get("redirect");
    if (r && r.startsWith("/") && !r.startsWith("//")) setRedirectTo(r);
  }, []);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<ISigninRequest>({
    defaultValues: { email: "", password: "" },
  });

  useEffect(() => {
    if (isAuthenticated) router.push(redirectTo);
  }, [isAuthenticated, router, redirectTo]);

  if (isAuthenticated) return null;

  const onSubmit = async (data: ISigninRequest) => {
    try {
      const response = await signin(data).unwrap();
      if (response?.id) {
        setAuthTokens(response.token, response.refreshToken);
        dispatch(
          setCredentials({
            user: {
              id: response.id.toString(),
              email: response.email,
              name: response.userProfile.name,
              profileImage: response.userProfile.profileImage?.filePath || null,
              rankName: response.userProfile?.rank?.name || "",
              isPremium: response.userSetting.isPremium,
              billingRegion: response.userSetting.billingRegion ?? null,
            },
          }),
        );
        toast.success("Login successful!");
        // Returning to a specific page (e.g. /discussion) does a full load so it
        // refetches with the new auth token; the plain home case stays a snappy
        // client transition.
        if (redirectTo === "/") router.push("/");
        else window.location.href = redirectTo;
      }
    } catch (error: any) {
      toast.error(parseApiError(error));
    }
  };

  return (
    <div className="w-full">
      <div className="text-center mb-8">
        <h1 className="text-2xl leading-[normal] font-bold text-[#111827]">Welcome back</h1>
        <p className="mt-1.5 text-sm leading-[normal] text-[#6b7280]">Sign in to your account to continue</p>
      </div>

      <div className="bg-white rounded-2xl shadow-[0_25px_50px_-12px_rgba(0,0,0,0.25)] p-8">
        <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-5">
          {/* Email */}
          <div>
            <label className="block text-sm leading-[normal] font-semibold text-[#374151] mb-1.5">
              Email address
            </label>
            <div className="relative">
              <span className="absolute left-3.5 top-1/2 -translate-y-1/2 flex items-center pointer-events-none text-[#9ca3af]">
                <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                </svg>
              </span>
              <input
                type="email"
                placeholder="you@example.com"
                autoComplete="email"
                {...register("email", {
                  required: "Email is required",
                  pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: "Invalid email format" },
                })}
                className={`w-full py-2.5 pl-10 pr-4 text-sm leading-[normal] border rounded-xl bg-white text-[#111827] placeholder:text-[#d1d5db] outline-none transition-all focus:border-transparent focus:ring-2 focus:ring-[#60a5fa] ${errors.email ? "border-red-400" : "border-[#e5e7eb]"}`}
              />
            </div>
            {errors.email && (
              <p className="mt-1 text-xs leading-[normal] text-[#ef4444]">{errors.email.message}</p>
            )}
          </div>

          {/* Password */}
          <div>
            <div className="flex items-center justify-between mb-1.5">
              <label className="text-sm leading-[normal] font-semibold text-[#374151]">Password</label>
              <Link
                href="/forgot-password"
                className="text-xs leading-[normal] font-medium text-[#3b82f6] no-underline"
              >
                Forgot password?
              </Link>
            </div>
            <div className="relative">
              <span className="absolute left-3.5 top-1/2 -translate-y-1/2 flex items-center pointer-events-none text-[#9ca3af]">
                <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                  <rect x="3" y="11" width="18" height="11" rx="2"/>
                  <path d="M7 11V7a5 5 0 0110 0v4"/>
                </svg>
              </span>
              <input
                type={showPassword ? "text" : "password"}
                placeholder="••••••••"
                autoComplete="current-password"
                {...register("password", { required: "Password is required" })}
                className={`w-full py-2.5 pl-10 pr-10 text-sm leading-[normal] border rounded-xl bg-white text-[#111827] placeholder:text-[#d1d5db] outline-none transition-all focus:border-transparent focus:ring-2 focus:ring-[#60a5fa] ${errors.password ? "border-red-400" : "border-[#e5e7eb]"}`}
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3.5 top-1/2 -translate-y-1/2 bg-transparent border-none cursor-pointer text-[#9ca3af] hover:text-[#6b7280] flex items-center p-0.5 transition-colors"
              >
                {showPassword ? (
                  <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"/>
                  </svg>
                ) : (
                  <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                  </svg>
                )}
              </button>
            </div>
            {errors.password && (
              <p className="mt-1 text-xs leading-[normal] text-[#ef4444]">{errors.password.message}</p>
            )}
          </div>

          <button
            type="submit"
            disabled={isLoading}
            className="w-full py-3 rounded-xl text-sm leading-[normal] font-semibold text-white bg-[#3b82f6] hover:bg-[#2563eb] border-none cursor-pointer transition-colors disabled:opacity-50"
          >
            {isLoading ? "Signing in..." : "Sign in"}
          </button>
        </form>

        <div className="flex items-center gap-3 my-6">
          <div className="flex-1 h-px bg-[#f3f4f6]" />
          <span className="text-xs leading-[normal] text-[#9ca3af] whitespace-nowrap">New to MySeaTime?</span>
          <div className="flex-1 h-px bg-[#f3f4f6]" />
        </div>

        <Link
          href={`/signup?redirect=${encodeURIComponent(redirectTo)}`}
          className="block w-full py-2.5 rounded-xl text-sm leading-[normal] font-semibold text-[#374151] bg-white border border-[#e5e7eb] text-center no-underline hover:bg-[#f9fafb] transition-colors"
        >
          Create an account
        </Link>
      </div>
    </div>
  );
}
