"use client";
import fetchData from "@/api/fetch-data";
import postData from "@/api/post-data";
import updateUserProfile from "@/api/user/updateUserProfile";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import clsx from "clsx";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { HiOutlineEnvelope } from "react-icons/hi2";
import { ImSpinner10 } from "react-icons/im";
import PhoneInput from "react-phone-number-input";
import { z } from "zod";
import AlertWarning from "../ui/shared/AlertWarning";
import Loading from "../ui/shared/Loading";
import SubmitButton from "../ui/shared/SubmitButton";

export default function Profile() {
  const locale = useLocale();
  const [isUpdating, setIsUpdating] = useState(false);
  const e = useTranslations("form-errors");
  const label = useTranslations("form-labels");
  const t = useTranslations("user");
  const fileInputRef = useRef(null);
  const [imageLoading, setImageLoading] = useState(false);
  const [image, setImage] = useState(null);
  const queryClient = useQueryClient();
  const { data, isPending, isError } = useQuery({
    queryKey: ["user", locale],
    queryFn: () => fetchData({ endPoint: "/user/get/profile" }),
  });

  const form = useForm({
    resolver: zodResolver(
      z.object({
        name: z.string({ errorMap: () => ({ message: e("required") }) }).min(1),
        lastname: z
          .string({ errorMap: () => ({ message: e("required") }) })
          .min(1),
        phone: z
          .string({ errorMap: () => ({ message: e("mobile") }) })
          .min(10)
          .max(16),
        gender: z
          .string({ errorMap: () => ({ message: e("required") }) })
          .min(1),
        birthdate: z
          .string({ errorMap: () => ({ message: e("required") }) })
          .min(1),
      })
    ),
    defaultValues: {
      name: "",
      lastname: "",
      gender: "",
      phone: "",
      birthdate: "",
    },
  });

  const {
    formState: { isSubmitting },
    reset,
  } = form; // Form settings
  const user = data?.data;
  // Use useEffect to set form values once data is loaded
  useEffect(() => {
    if (user) {
      reset({
        name: user?.name,
        lastname: user?.lastname,
        gender: user?.gender,
        phone: user?.phone,
        birthdate: user?.birthdate,
      });
    }
  }, [reset, user]);

  // States check
  if (isPending) {
    return <Loading />;
  }

  if (isError) {
    return <AlertWarning message={data?.message} />;
  }

  async function changeImage(ele) {
    setImageLoading(true);
    const formData = new FormData();
    const file = ele.files ? ele.files[0] : "";
    formData.append("image", file);
    const { error, message, data } = await postData({
      endPoint: "/user/update/image",
      body: formData,
    });
    setImageLoading(false);
    if (error) {
      fileInputRef.current.value = "";
      toastError(message);
      return;
    }
    setImage(data);
    toastSuccess(message);
  }

  async function onSubmit(values) {
    const formData = new FormData();
    for (const [key, value] of Object.entries(values)) {
      formData.append(key, value);
    }
    const { error, message } = await updateUserProfile(formData);
    if (error) {
      toastError(message);
      return;
    }
    queryClient.invalidateQueries({ queryKey: ["user"] });
    toastSuccess(message);
    setIsUpdating(false);
  }

  return (
    <div className="me-auto lg:w-[80%] p-4">
      <div className="profile xl:space-y-10">
        <div className="info gap-6">
          <div>
            <h1 className="text-2xl py-3 font-bold text-center lg:text-start">
              {t("info-account")}
            </h1>
            {isUpdating && (
              <Avatar
                disabled={imageLoading}
                className={clsx(
                  `mx-auto relative cursor-pointer mb-4 size-28 md:size-36`,
                  {
                    "brightness-50": imageLoading,
                  }
                )}
                onClick={() => fileInputRef.current?.click()}
              >
                <AvatarImage src={image ? image : user?.image} />
                <AvatarFallback className="text-3xl md:text-5xl bg-main text-white">
                  {user?.name?.slice(0, 2)}
                </AvatarFallback>
                {imageLoading ? (
                  <ImSpinner10 className="text-btnColor text-2xl md:text-4xl absolute inset-0 m-auto animate-spin" />
                ) : (
                  ""
                )}
              </Avatar>
            )}
            <Input
              disabled={imageLoading}
              ref={fileInputRef}
              type="file"
              onChange={(event) => changeImage(event.target)}
              className="hidden"
            />
            <div className="rounded-xl mt-8">
              <Form {...form}>
                <form
                  method="post"
                  onSubmit={form.handleSubmit(onSubmit)}
                  className="space-y-6"
                >
                  <FormField
                    name="name"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormControl>
                          <Input
                            {...field}
                            disabled={!isUpdating}
                            className={clsx({
                              "border border-black": isUpdating,
                              "bg-[#E1F6FF]": !isUpdating,
                            })}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    name="lastname"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormControl>
                          <Input
                            {...field}
                            disabled={!isUpdating}
                            className={clsx({
                              "border border-black": isUpdating,
                              "bg-[#E1F6FF]": !isUpdating,
                            })}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  {!isUpdating && (
                    <div className={`relative`}>
                      <HiOutlineEnvelope
                        className={`text-2xl absolute top-1/2 start-0 transform ms-2 -translate-y-1/2`}
                      />
                      <Input
                        value={user?.email}
                        disabled={!isUpdating}
                        className={clsx("indent-6", {
                          "border border-black": isUpdating,
                          "bg-[#E1F6FF]": !isUpdating,
                        })}
                      />
                    </div>
                  )}
                  {isUpdating && (
                    <FormField
                      name="birthdate"
                      control={form.control}
                      render={({ field }) => (
                        <FormItem>
                          <FormControl>
                            <Input
                              {...field}
                              type="date"
                              className={
                                "border text-start inline border-black"
                              }
                            />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                  )}
                  <FormField
                    name="gender"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormControl>
                          <Select
                            value={field.value || user?.gender}
                            onValueChange={field.onChange}
                            disabled={!isUpdating}
                            dir={locale === "ar" ? "rtl" : "ltr"}
                          >
                            <SelectTrigger
                              className={clsx({
                                "border border-black": isUpdating,
                                "bg-[#E1F6FF]": !isUpdating,
                              })}
                            >
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="male">
                                {label("male")}
                              </SelectItem>
                              <SelectItem value="female">
                                {label("female")}
                              </SelectItem>
                            </SelectContent>
                          </Select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    name="phone"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormControl>
                          <PhoneInput
                            value={field.value}
                            onChange={field.onChange}
                            disabled={!isUpdating}
                            className={clsx({
                              "border border-black rounded-lg": isUpdating,
                              "bg-[#E1F6FF]": !isUpdating,
                            })}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  {isUpdating ? (
                    <div className="flex gap-x-6 justify-between">
                      <SubmitButton text={t("save")} loading={isSubmitting} />
                      <Button
                        type="button"
                        onClick={() => {
                          reset();
                          setIsUpdating(false);
                        }}
                        className="w-full"
                        variant="outline"
                      >
                        {t("close")}
                      </Button>
                    </div>
                  ) : (
                    <div
                      className="btn-main cursor-pointer bg-[#394448] text-white py-3 px-10 xl:my-5 xl:px-32 rounded-sm w-fit m-auto"
                      onClick={() => {
                        setIsUpdating(true);
                      }}
                    >
                      {t("update")}
                    </div>
                  )}
                </form>
              </Form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
