"use client";
import { InputField } from "@/components/forms/Inputs";
import { TSloginSchema, loginSchema } from "@/components/forms/schema/login";
import { useSettings } from "@/utils/settings";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Card, Spinner } from "flowbite-react";
import { signIn } from "next-auth/react";
import Link from "next/link";
import type { FC } from "react";
import { useEffect, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { toast } from "react-toastify";
import Logo from "../common/logo";
import { TSclientLoginSchema, clientLoginSchema } from "../forms/schema/client-login";
const ClientLogin: FC = function () {
  const [loading, setLoading] = useState(false);
  const [host, setHost] = useState("");
  const loginForm = useForm<TSclientLoginSchema>({
    resolver: zodResolver(clientLoginSchema),
    mode: "onChange",
  });

  useEffect(() => {
    const domain = window?.location?.hostname;
    setHost(domain);
  });

  const {
    handleSubmit,
    formState: { errors },
  } = loginForm;

  const submit = async (data: TSclientLoginSchema) => {
    Object.assign(data, { host: host, api_url: "/api/v1/auth/client" });
    setLoading(true);
    const res: any = await signIn("credentials", {
      ...data,
      redirect: false,

    }).catch((error: any) => {
      setLoading(false);
    });
    if (res?.error && res.status === 401) {
      toast.error(`Username or password not match!`, { autoClose: 10000 });
    }
    console.log(res, 'login res');
    if (res?.ok) {
      location.href = "/";
    }
    setLoading(false);
  };

  return (
    <>
      <div className="flex flex-col items-center justify-center px-2 lg:h-screen lg:gap-y-5">
        <Link href="/" className="my-6 flex items-center gap-x-1 lg:my-0">
          <Logo />
        </Link>
        <Card
          horizontal
          className="w-full md:max-w-[500px] md:[&>*]:w-full px-2  lg:[&>img]:block rounded-3xl border-2 border-rose-500 shadow-gray-200 "
        >
          <h1 className="mb-3 text-xl font-medium text-center text-gray-500 dark:text-white md:text-3xl">
            {useSettings("name") ? <>{useSettings("name")} Login</> : <>Login</>}
          </h1>
          <FormProvider {...loginForm}>
            <form onSubmit={handleSubmit(submit)}>
              <div className="mb-4 flex flex-col gap-y-3">
                <InputField
                  labelText="phone"
                  name="phone"
                  placeholder="phone"
                  inputType="text"
                  errors={errors}
                />
              </div>
              <div className="mb-6 flex flex-col gap-y-3">
                <InputField
                  labelText="Password"
                  name="password"
                  placeholder="••••••••"
                  inputType="password"
                  errors={errors}
                />
              </div>
              <div className="mb-6">
                <Button
                  type="submit"
                  className=" bg-gray-400 w-full"
                  color="blue"
                >
                  {loading && (
                    <Spinner
                      aria-label="spinner button"
                      size="sm"
                      className="mr-1"
                    />
                  )}
                  Login
                </Button>
                <div className="mt-6 text-center">
                  <Link
                    href="/home"
                    className="w-1/2 text-center text-sm text-primary-600 dark:text-primary-300"
                  >
                    Home
                  </Link>
                </div>
              </div>
            </form>
          </FormProvider>
        </Card>
      </div>
    </>
  );
};

export default ClientLogin;
