"use client";

import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/inputs/input";
import { PhoneInput } from "@/components/ui/inputs/phone-input";
import { useAuthApi } from "@/hooks/use-auth-api";
import { setAuthToken } from '@/lib/auth-cookies';
import { countries, type Country } from "@/lib/countries";
import { createLoginFieldSchema, createPasswordSchema } from "@/lib/validation";
import { useAuthStore } from "@/store/authStore";
import { useUserStore } from "@/store/userStore";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

function normalizeRedirectPath(path: string | null): string | null {
  if (!path) return null;
  let decoded = path;
  try {
    decoded = decodeURIComponent(path);
  } catch {
    decoded = path;
  }
  if (
    !decoded.startsWith('/') ||
    decoded.startsWith('//') ||
    decoded.startsWith('/\\')
  ) return null;
  return decoded;
}

export const LoginForm = (): React.ReactNode => {
  const t = useTranslations("dashboard.auth");
  const tValidation = useTranslations("dashboard.auth.validation");
  const [loginMethod, setLoginMethod] = useState<"username" | "phone">(
    "username"
  );
  const [selectedCountry, setSelectedCountry] = useState<Country>(countries[0]);
  const { setResetSteps } = useAuthStore();
  const { setIsLogin, setToken, setUser } = useUserStore();
  const { login, isLoggingIn } = useAuthApi();
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);

  const formSchema = z.object({
    username: createLoginFieldSchema(
      loginMethod === "phone",
      selectedCountry,
      tValidation
    ),
    password: createPasswordSchema(tValidation),
  });

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      username: "",
      password: "",
    },
  });

  useEffect(() => {
    form.clearErrors("username");
    form.setValue("username", "");
  }, [loginMethod, selectedCountry, form]);

  async function onSubmit(values: z.infer<typeof formSchema>) {
    try {
      const userName =
        loginMethod === "phone"
          ? `${selectedCountry.dialCode}${values.username}`
          : values.username;

      const payload = await login({
        user_name: userName,
        password: values.password,
      });

      const payloadData =
        payload?.data && typeof payload.data === "object"
          ? (payload.data as Record<string, unknown>)
          : {};

      const token =
        (typeof payload?.token === "string" ? payload.token : "") ||
        (typeof payloadData.token === "string" ? payloadData.token : "") ||
        (typeof payloadData.access_token === "string"
          ? payloadData.access_token
          : "");

      const userProfile =
        payloadData.user && typeof payloadData.user === "object"
          ? payloadData.user
          : payloadData;

      setIsLogin(true);
      if (token) {
        setToken(token);
        setAuthToken(token);
      }
      setUser({
        rememberMe,

        profile: userProfile || null,
      });

      const searchParams = new URLSearchParams(window.location.search);
      const redirectParam = normalizeRedirectPath(searchParams.get('redirect'));
      const localePrefixMatch = window.location.pathname.match(/^\/(en)(\/|$)/);
      const localePrefix = localePrefixMatch ? '/en' : '';
      window.location.href = redirectParam || `${localePrefix}/dashboard`;
    } catch {

    }
  }

  return (
    <div className="flex h-full w-full flex-col items-center">

      <div className="flex w-full items-start justify-between md:px-20 px-5 pt-10">

        <div className="relative h-14 w-36">
          <div className="absolute inset-0">
            <div className="absolute bottom-[10.19%] left-[39.51%] right-0 top-[67.43%]">
              <Image
                alt={t("logoPart1Alt")}
                fill
                className="max-w-none object-contain"
                src="/images/login/logo-part1.svg"
              />
            </div>
            <div className="absolute bottom-0 left-[39.51%] right-[17.96%] top-[92.09%]">
              <Image
                alt={t("logoPart2Alt")}
                fill
                className="max-w-none object-contain"
                src="/images/login/logo-part2.svg"
              />
            </div>
            <div className="absolute bottom-[34.85%] left-0 right-[0.11%] top-0">
              <Image
                alt={t("logoPart3Alt")}
                fill
                className="max-w-none object-contain"
                src="/images/login/logo-part3.svg"
              />
            </div>
          </div>
        </div>
      </div>

      <div className="flex w-full md:max-w-[876px] translate-y-[-40%] flex-col gap-12 md:px-20 px-10 pt-[calc(50vh-0.5px)]">

        <div className="flex w-full flex-col items-start gap-3">

          <div className="h-14 w-14 overflow-hidden">
            <Image
              alt={t("logoIconAlt")}
              src="/images/login/icons/logo-icon.svg"
              width={56}
              height={56}
            />
          </div>

          <div className="flex items-center justify-center gap-2">
            <h3 className=" text-[28px] font-bold leading-[1.2] text-foreground">
              {t("loginTitle")}
            </h3>
          </div>

          <p className=" text-lg leading-[1.2] text-muted-foreground">
            {t("loginDescriptionLong")}
          </p>
        </div>

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex w-full flex-col gap-6"
          >

            <div className="flex w-full items-center gap-4">
              <button
                type="button"
                onClick={() => setLoginMethod("phone")}
                className={`flex items-center gap-2 rounded-xl border px-4 py-4 ${loginMethod === "phone"
                    ? "border-primary-100 bg-highlights-bg"
                    : "border-border bg-card"
                  }`}
              >
                <p className=" text-sm leading-[1.2] text-muted-foreground">
                  {t("phone")}
                </p>
                <Image
                  src="/images/login/icons/call-calling.svg"
                  alt={t("phoneIconAlt")}
                  width={20}
                  height={20}
                />
              </button>

              <div className=" text-sm text-muted-foreground">{t("or")}</div>

              <button
                type="button"
                onClick={() => setLoginMethod("username")}
                className={`flex items-center gap-2 rounded-xl border px-4 py-4 ${loginMethod === "username"
                    ? "border-primary-100 bg-highlights-bg"
                    : "border-border bg-card"
                  }`}
              >
                <p className=" text-sm leading-[1.2] text-muted-foreground">
                  {t("username")}
                </p>
                <Image
                  src="/images/login/icons/user-bulk.svg"
                  alt={t("userIconAlt")}
                  width={20}
                  height={20}
                />
              </button>
            </div>

            <div className="flex w-full flex-col gap-6">
              <div className="flex w-full flex-col gap-4">

                <FormField
                  control={form.control}
                  name="username"
                  render={({ field }) => (
                    <FormItem className="flex w-full flex-col  gap-2">
                      <FormLabel className=" text-base leading-[1.2] text-foreground">
                        {loginMethod === "username"
                          ? t("username")
                          : t("phone")}
                      </FormLabel>
                      <FormControl>
                        {loginMethod === "phone" ? (
                          <PhoneInput
                            value={field.value}
                            onChange={field.onChange}
                            country={selectedCountry}
                            onCountryChange={setSelectedCountry}
                            placeholder="0000000"
                          />
                        ) : (
                          <div className="relative w-full">
                            <Input
                              {...field}
                              placeholder={t("usernamePlaceholder")}
                              className="h-14 w-full rounded-xl border-border py-5 ps-4 pe-12  text-sm"
                            />
                            <div className="absolute end-4 top-1/2 -translate-y-1/2">
                              <Image
                                src="/images/login/icons/user-outline.svg"
                                alt=""
                                width={20}
                                height={20}
                              />
                            </div>
                          </div>
                        )}
                      </FormControl>
                      <FormMessage className=" " />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem className="flex w-full flex-col  gap-2">
                      <FormLabel className=" text-base leading-normal text-foreground">
                        {t("password")}
                      </FormLabel>
                      <FormControl>
                        <div className="relative w-full">
                          <Input
                            {...field}
                            type={showPassword ? "text" : "password"}
                            placeholder={t("passwordPlaceholder")}
                            className="h-14 w-full rounded-xl border-border py-5 ps-12 pe-12  text-sm"
                          />
                          <div className="absolute end-4 top-1/2 -translate-y-1/2">
                            <Image
                              src="/images/login/icons/lock.svg"
                              alt={t("lockIconAlt")}
                              width={20}
                              height={20}
                              className="rotate-180 scale-y-[-1]"
                            />
                          </div>
                          <button
                            type="button"
                            onClick={() => setShowPassword(!showPassword)}
                            className="absolute start-4 top-1/2 -translate-y-1/2"
                          >
                            <Image
                              src="/images/login/icons/eye-slash.svg"
                              alt={
                                showPassword
                                  ? t("hidePassword")
                                  : t("showPassword")
                              }
                              width={20}
                              height={20}
                            />
                          </button>
                        </div>
                      </FormControl>
                      <FormMessage className=" " />
                    </FormItem>
                  )}
                />

                <div className="flex w-full items-center justify-between">
                  <Button
                    variant="link"
                    onClick={() => setResetSteps("emailWhatsapp")}
                    className=" text-sm leading-normal text-primary underline decoration-solid underline-offset-auto"
                  >
                    {t("forgotPassword")}
                  </Button>

                  <div className="flex items-center gap-2">
                    <label className="cursor-pointer  text-sm leading-normal text-muted-foreground">
                      {t("rememberMe")}
                    </label>
                    <Checkbox
                      checked={rememberMe}
                      onCheckedChange={(checked) =>
                        setRememberMe(checked as boolean)
                      }
                      className="h-5 w-5 rounded border-border"
                    />
                  </div>
                </div>
              </div>

              <Button
                type="submit"
                disabled={isLoggingIn}
                className="flex h-14 w-full items-center justify-center gap-2 rounded-xl bg-primary px-4 py-2.5 hover:bg-primary-800"
              >
                <span className=" text-sm font-bold leading-4 tracking-[-0.084px] text-white">
                  {t("loginAction")}
                </span>
                <Image
                  src="/images/login/icons/login.svg"
                  alt=""
                  width={20}
                  height={20}
                />
              </Button>
            </div>
          </form>
        </Form>
      </div>
    </div>
  );
};
