"use client";

import { formSchema } from "@/pages/auth/lib/form";
import { authLogin, getMe } from "@/shared/config/api/auth/api";
import useUserStore from "@/shared/hooks/user";
import {
  getAuthToken,
  setAuthRefToken,
  setAuthToken,
} from "@/shared/lib/authCookies";
import formatPhone from "@/shared/lib/formatPhone";
import onlyNumber from "@/shared/lib/onlyNumber";
import { Button } from "@/shared/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import LangToggle from "@/widgets/lang-toggle/ui/lang-toggle";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Eye, EyeOff, LoaderCircle } from "lucide-react";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { z } from "zod";

const Login = () => {
  const [showPassword, setShowPassword] = useState(false);
  const { setUser } = useUserStore();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const token = getAuthToken();

  const { mutate, isPending } = useMutation({
    mutationFn: ({ password, phone }: { password: string; phone: string }) =>
      authLogin({ password, phone }),
    onSuccess: (res) => {
      setAuthToken(res.data.access);
      setAuthRefToken(res.data.refresh);
      queryClient.invalidateQueries({ queryKey: ["auth_get_me"] });
    },
    onError: () => {
      toast.error("Xatolik yuz berdi", {
        richColors: true,
        position: "top-center",
      });
    },
  });

  const { data } = useQuery({
    queryKey: ["auth_get_me"],
    queryFn: () => getMe(),
    enabled: !!token,
  });

  useEffect(() => {
    if (data) {
      setUser(data.data.data);
    }
    if (data && data.data.data.role !== "user") {
      navigate("/");
    }
  }, [data]);

  const { t } = useTranslation();

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

  function onSubmit(values: z.infer<typeof formSchema>) {
    const cleanPhone = onlyNumber(values.phone);

    // allow both 998 and 888 prefixes
    if (!cleanPhone.startsWith("998") && !cleanPhone.startsWith("888")) {
      toast.error(t("Telefon raqami +998 yoki +888 bilan boshlanishi kerak"));
      return;
    }

    mutate({
      password: values.password,
      phone: cleanPhone,
    });
  }

  useEffect(() => {
    if (data) {
      const userData = data.data.data;
      setUser(userData);

      if (userData.role === "user") {
        toast.error(t("Sizga tizimga kirishga ruxsat berilmagan"), {
          richColors: true,
          position: "top-center",
        });

        setAuthToken("");
        setAuthRefToken("");
        queryClient.clear();

        navigate("/login", { replace: true });
      } else {
        navigate("/", { replace: true });
      }
    }
  }, [data]);

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-900 px-4 w-full">
      <div className="absolute top-4 right-4 flex gap-2">
        <LangToggle />
      </div>
      <div className="w-full max-w-xl rounded-2xl bg-gray-800 p-8 shadow-lg">
        <h2 className="mb-6 text-center text-3xl font-semibold text-white">
          {t("Admin Panelga Kirish")}
        </h2>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-200">
                    {t("Telefon raqam")}
                  </FormLabel>
                  <FormControl>
                    <Input
                      placeholder="+998 yoki +888 bilan boshlang"
                      {...field}
                      value={field.value}
                      onChange={(e) => {
                        const inputValue = e.target.value;

                        if (inputValue.trim() === "") {
                          field.onChange("");
                          return;
                        }

                        // Formatlash
                        field.onChange(formatPhone(inputValue));
                      }}
                      maxLength={19}
                      className="h-[56px] text-lg rounded-xl bg-gray-700 border-gray-600 text-white placeholder-gray-400"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-200">{t("Parol")}</FormLabel>
                  <FormControl>
                    <div className="relative">
                      <Input
                        type={showPassword ? "text" : "password"}
                        placeholder={t("Parolingizni kiriting")}
                        {...field}
                        className="h-[56px] text-lg rounded-xl bg-gray-700 border-gray-600 text-white placeholder-gray-400 pr-12"
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-200"
                        tabIndex={-1}
                      >
                        {showPassword ? (
                          <EyeOff className="w-5 h-5" />
                        ) : (
                          <Eye className="w-5 h-5" />
                        )}
                      </button>
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <Button
              type="submit"
              className="w-full h-[56px] rounded-xl text-lg font-medium"
            >
              {isPending ? (
                <LoaderCircle className="animate-spin" />
              ) : (
                t("Kirish")
              )}
            </Button>
          </form>
        </Form>

        <p className="mt-6 text-center text-sm text-gray-400">
          &copy; {new Date().getFullYear()} {t("Admin Panel")}
        </p>
      </div>
    </div>
  );
};

export default Login;
