"use client";

import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { loginWithEmail, clearError } from "@/store/slices/authSlice";
import { LoginType } from "@/types/auth";
import { AuthField } from "./AuthField";
import { AuthDivider } from "./AuthDivider";
import { GoogleLoginButton } from "./GoogleLoginButton";
import { useTranslation } from "@/i18n";

const schema = z.object({
  email: z.string().email("Enter a valid email"),
  password: z.string().min(6, "Password must be at least 6 characters"),
  terms: z.boolean().refine((v) => v === true, { message: "auth_termsError" }),
});
type FormValues = z.infer<typeof schema>;

export function LoginForm() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { isLoading, error } = useAppSelector((s) => s.auth);
  const { t } = useTranslation();

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: { terms: false },
  });

  const fillTestCredentials = () => {
    setValue("email", "developer@gmail.com", { shouldValidate: true });
    setValue("password", "123456", { shouldValidate: true });
    setValue("terms", true, { shouldValidate: true });
  };

  const onSubmit = async (data: FormValues) => {
    dispatch(clearError());
    const res = await dispatch(
      loginWithEmail({
        type: LoginType.Normal,
        email: data.email,
        password: data.password,
      }),
    );
    if (loginWithEmail.fulfilled.match(res)) {
      router.push("/");
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
      <AuthField
        label={t("auth_emailLabel")}
        type="email"
        placeholder="you@example.com"
        error={errors.email?.message}
        autoComplete="email"
        {...register("email")}
      />
      <AuthField
        label={t("auth_passwordLabel")}
        isPassword
        placeholder="••••••••"
        error={errors.password?.message}
        autoComplete="current-password"
        {...register("password")}
      />

      <div className="flex justify-end -mt-1">
        <Link
          href="/auth/forgot-password"
          className="text-xs transition-opacity hover:opacity-80"
          style={{ color: "var(--accent)" }}
        >
          {t("auth_forgotPassword")}
        </Link>
      </div>

      <div className="flex flex-col gap-1">
        <label className="flex items-start gap-2 cursor-pointer select-none">
          <input
            type="checkbox"
            {...register("terms")}
            className="mt-0.5 h-4 w-4 rounded border accent-[var(--accent)] cursor-pointer shrink-0"
          />
          <span
            className="text-xs leading-relaxed"
            style={{ color: "var(--text-secondary)" }}
          >
            {t("auth_termsAgree")}{" "}
            <Link
              href="/terms"
              className="underline font-medium hover:opacity-80"
              style={{ color: "var(--accent)" }}
            >
              {t("auth_termsLink")}
            </Link>{" "}
            {t("auth_termsAnd")}{" "}
            <Link
              href="/privacy"
              className="underline font-medium hover:opacity-80"
              style={{ color: "var(--accent)" }}
            >
              {t("auth_privacyLink")}
            </Link>
          </span>
        </label>
        {errors.terms && (
          <p className="text-xs" style={{ color: "#ef4444" }}>
            {t(errors.terms.message as string)}
          </p>
        )}
      </div>

      {error && (
        <p
          className="text-xs px-3 py-2 rounded-lg"
          style={{ background: "rgba(239,68,68,0.1)", color: "#ef4444" }}
        >
          {error}
        </p>
      )}

      <button
        type="button"
        onClick={fillTestCredentials}
        className="w-full py-2.5 rounded-xl text-xs font-semibold border transition-all duration-150 active:scale-[0.98]"
        style={{
          background: "var(--deep)",
          borderColor: "var(--border)",
          color: "var(--text-muted)",
        }}
      >
        Use test account —{" "}
        <span style={{ color: "var(--text-primary)" }}>
          developer@gmail.com
        </span>
      </button>

      <button
        type="submit"
        disabled={isLoading}
        className="w-full py-3 rounded-xl text-sm font-bold tracking-wide text-[#ffffff] transition-all duration-150 active:scale-[0.98] disabled:opacity-60 mt-1"
        style={{ background: "var(--accent)" }}
      >
        {isLoading ? t("auth_signingIn") : t("auth_loginButton")}
      </button>

      <AuthDivider />

      <GoogleLoginButton />

      <Link
        href="/auth/otp"
        className="w-full flex items-center justify-center gap-2 rounded-xl py-3 px-4 text-sm font-medium transition-all duration-150 active:scale-[0.98]"
        style={{
          background: "var(--btn-ghost-hover)",
          border: "1px solid var(--border)",
          color: "var(--text-primary)",
        }}
      >
        <svg
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.8"
          strokeLinecap="round"
          strokeLinejoin="round"
        >
          <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 12 19.79 19.79 0 0 1 1.63 3.18 2 2 0 0 1 3.6 1h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L7.91 8.1a16 16 0 0 0 6 6l.92-.92a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" />
        </svg>
        {t("auth_phoneOtpButton")}
      </Link>
    </form>
  );
}
