"use client";

import { useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import AuthCard from "./AuthCard";
import { MailIcon, PasswordIcon, EyeIcon } from "./icons";
import { useAppDispatch, useAppSelector } from "@/state/hooks";
import { loginAdmin } from "@/state/auth";

type LoginFormValues = {
  email: string;
  password: string;
  rememberMe: boolean;
};

export default function LoginScreen() {
  const searchParams = useSearchParams();
  const returnUrl = searchParams.get("returnUrl") || "/dashboard";

  const dispatch = useAppDispatch();
  const { status, error: reduxError } = useAppSelector((state) => state.auth);

  const [showPassword, setShowPassword] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormValues>({
    defaultValues: {
      rememberMe: true,
    },
  });

  const onSubmit = async (data: LoginFormValues) => {
    try {
      const resultAction = await dispatch(
        loginAdmin({
          email: data.email,
          password: data.password,
          rememberMe: data.rememberMe,
        })
      );

      if (loginAdmin.fulfilled.match(resultAction)) {
        toast.success("Login successful");
        window.location.replace(returnUrl);
      } else if (loginAdmin.rejected.match(resultAction)) {
        const errorMsg =
          (resultAction.payload as { message?: string })?.message ||
          "Invalid email or password";
        toast.error(errorMsg);
      }
    } catch (err: unknown) {
      toast.error((err as Error)?.message || "Failed to log in");
    }
  };

  const loading = status === "loading";

  return (
    <AuthCard
      title="Welcome Back"
      subtitle="Log in to manage products, sellers, and platform operations."
    >
      <form
        method="post"
        action="#"
        onSubmit={(e) => {
          e.preventDefault();
          handleSubmit(onSubmit)(e);
        }}
      >
        <div className="min-h-[220px] space-y-4">
          <div>
            <label className="mb-1.5 block text-[14px] font-medium leading-[22px] tracking-[0.01em] text-[#4E616A]">
              Email
            </label>
            <div
              className={`flex h-[54px] items-center gap-2 rounded-lg border bg-white px-4 focus-within:border-[#1657D9] ${
                errors.email ? "border-red-500" : "border-[#D0D5DD]"
              }`}
            >
              <MailIcon />
              <input
                type="email"
                placeholder="example@email.com"
                className="min-w-0 flex-1 border-0 bg-transparent text-[13px] text-[#101828] outline-none placeholder:text-[#98A2B3]"
                {...register("email", { required: "Email is required" })}
              />
            </div>
            {errors.email && (
              <p className="mt-1 text-[11px] text-red-500">
                {errors.email.message}
              </p>
            )}
          </div>

          <div>
            <label className="mb-1.5 block text-[14px] font-medium leading-[22px] tracking-[0.01em] text-[#4E616A]">
              Password
            </label>
            <div
              className={`flex h-[54px] items-center gap-2 rounded-lg border bg-white px-4 focus-within:border-[#1657D9] ${
                errors.password ? "border-red-500" : "border-[#D0D5DD]"
              }`}
            >
              <PasswordIcon />
              <input
                type={showPassword ? "text" : "password"}
                placeholder="••••••••"
                className="min-w-0 flex-1 border-0 bg-transparent text-[13px] text-[#101828] outline-none placeholder:text-[#98A2B3]"
                {...register("password", { required: "Password is required" })}
              />
              <button
                type="button"
                onClick={() => setShowPassword((prev) => !prev)}
                className="flex h-5 w-5 items-center justify-center cursor-pointer"
                aria-label={showPassword ? "Hide password" : "Show password"}
              >
                <EyeIcon open={!showPassword} />
              </button>
            </div>
            {errors.password && (
              <p className="mt-1 text-[11px] text-red-500">
                {errors.password.message}
              </p>
            )}
          </div>

          <div className="flex items-center justify-between pt-1">
            <label className="flex items-center gap-1.5 text-[12px] text-[#475467] cursor-pointer">
              <input
                type="checkbox"
                className="h-3.5 w-3.5 accent-[#1D4ED8]"
                {...register("rememberMe")}
              />
              <span>Remember me</span>
            </label>
            <Link
              href="/forgot-password"
              className="text-[12px] font-medium text-[#1D4ED8] hover:underline"
            >
              Forgot Password?
            </Link>
          </div>

          {reduxError && (
            <p className="text-[12px] font-medium text-red-600 bg-red-50 p-2.5 rounded-lg border border-red-200">
              {reduxError}
            </p>
          )}
        </div>

        <button
          type="submit"
          disabled={loading}
          className="mt-8 h-10 w-full rounded-lg bg-[#1D4ED8] text-[14px] font-medium text-white transition-colors hover:bg-[#1E40AF] disabled:opacity-60 cursor-pointer"
        >
          {loading ? "Logging in..." : "Log In"}
        </button>
      </form>
    </AuthCard>
  );
}
