"use client";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { useLocale, useTranslations } from "next-intl";
import { ScrollArea } from "@/shared/ui/scroll-area";
import { Form } from "@/shared/ui/form";
import { AuthStage } from "@/interfaces/types";
import AppButton from "@/shared/buttons/AppButton";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "@/store/store";
import FormInput from "@/shared/form-controls/FormInput";
import { useState } from "react";
import axiosInstanceClient from "@/utils/axiosClient";
import { setLocation } from "@/store/location.slice";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
import FormPhoneNumber from "@/shared/form-controls/FormPhoneNumber";
import FormGenralSelect from "@/shared/form-controls/FormGenralSelect";
import { AddAddress, EditAddress } from "@/store/address.slice";
import FormSwitch from "@/shared/form-controls/FormSwtich";
import LoaderSection from "@/shared/LoaderSection/LoaderSection";
import { fetchAddressData, UpdateProfile } from "@/utils/helpers";
import GoogleMap from "@/shared/googleMap/GoogleMap";
import UseSession from "@/hooks/UseSession";
import FormTextarea from "@/shared/form-controls/FormTextarea";

interface LocationFormProps {
  setAuthStage: (stage: AuthStage) => void;
  dialogOpen: (open: boolean) => void;
  setLocationId?: (id: any) => void;
}
const LocationForm: React.FC<LocationFormProps> = ({
  setAuthStage,
  dialogOpen,
  setLocationId,
}) => {
  const t = useTranslations("");
  const locale = useLocale();
  const session = UseSession();

  const { singleItem, mainLoader } = useSelector(
    (state: RootState) => state.AddressConfig,
  );
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch<AppDispatch>();

  const formSchema = yup.object({
    phone_limit: yup.number(),
    phone: yup
      .string()
      .required(t("validations.requiredField", { field: t("LABELS.phone") }))
      .test((value, context) => {
        let phoneLimit = context.parent.phone_limit;
        if (!phoneLimit) return true;
        if (value && value.length !== parseInt(phoneLimit)) {
          return context.createError({
            message: t("validations.phoneLimit", {
              length: `${phoneLimit}`,
            }),
            path: "phone",
          });
        }

        return true;
      }),
    phone_code: yup.string(),
    country_id: yup
      .string()
      .required(t("validations.requiredField", { field: t("LABELS.country") })),
    city_id: yup
      .string()
      .required(t("validations.requiredField", { field: t("LABELS.city") })),
    district_id: yup
      .string()
      .required(
        t("validations.requiredField", { field: t("LABELS.district") }),
      ),
    lng: yup
      .number()
      .required(t("validations.requiredField", { field: t("LABELS.lng") })),
    lat: yup
      .number()
      .required(t("validations.requiredField", { field: t("LABELS.lat") })),
    description: yup.string().required(
      t("validations.requiredField", {
        field: t("LABELS.location_description"),
      }),
    ),

    is_default: yup
      .boolean()
      // .required(
      //   t("validations.requiredField", { field: t("LABELS.is_default") }),
      // )
      .oneOf(
        [true, ...(session?.default_address ? [false] : [])],
        t("validations.requiredField", { field: t("LABELS.is_default") }),
      ),
  });

  const form = useForm({
    resolver: yupResolver(formSchema),
    defaultValues: {
      phone: singleItem?.contact?.phone || "",
      phone_code: singleItem?.contact?.phone_code || "",
      phone_limit: 9,
      country_id: singleItem?.location?.country?.id || "",
      city_id: singleItem?.location?.city?.id || "",
      district_id: singleItem?.location?.district?.id || "",
      lng: singleItem?.location?.longitude || 31.1613696,
      lat: singleItem?.location?.latitude || 30.9585477,
      description: singleItem?.description || "",
      is_default: singleItem?.is_default,
    },
  });
  const { setValue } = form;

  async function onSubmit(values: yup.InferType<typeof formSchema>) {
    const finalOut = {
      ...values,
      longitude: values?.lng?.toString(),
      latitude: values?.lat?.toString(),
      ...(values?.is_default !== undefined
        ? { is_default: +values?.is_default }
        : { is_default: 0 }),
    };
    try {
      setLoading(true);

      const endpoint = singleItem?.id
        ? `client/addresses/${singleItem.id}`
        : "client/addresses";
      const method = singleItem?.id
        ? axiosInstanceClient.put
        : axiosInstanceClient.post;
      const { data } = await method(endpoint, finalOut);

      if (data.status === "success") {
        if (+data?.data?.is_default == 1) {
          UpdateProfile({ dispatch });

          dispatch(
            setLocation({
              id: data?.data?.id,
              is_default: data?.data?.is_default,
              phone_code: data?.data?.contact?.phone_code,
              phone: data?.data?.contact?.phone,
              country: data?.data?.location?.country,
              city: data?.data?.location?.city,
              district: data?.data?.location?.district,
              lng: data?.data?.location?.longitude,
              lat: data?.data?.location?.latitude,
              description: data?.data?.description,
              isLoading: false,
            }),
          );
        }

        if (singleItem?.id) {
          dispatch(EditAddress({ address: data?.data }));
        } else if (!singleItem?.id) {
          dispatch(AddAddress({ address: data?.data }));
        }
        // fetchAddressData({ dispatch });
        if (setLocationId) setLocationId(data?.data?.id);

        setAuthStage("location");
        dialogOpen(false);
        setLoading(false);
        form.reset();
      }
    } catch (error: any) {
      ShowAlertMixin({
        icon: "error",
        title: error.response?.data?.message || error.message,
      });
      setLoading(false);
    }
  }
  if (mainLoader) {
    return (
      <div className="min-h-[650px] flex items-center justify-center">
        <LoaderSection />
      </div>
    );
  }
  return (
    <ScrollArea className="grow " dir={locale === "en" ? "ltr" : "rtl"}>
      <div className="h-[600px] flex flex-col pe-2 py-2">
        <div className="mb-3 px-3">
          <h3 className="text-[20px] font-medium grid grid-cols-[auto_1fr] gap-2">
            {t("NAV.addresses")}
          </h3>
        </div>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="flex flex-col gap-4">
              <div className="grid lg:grid-cols-2 gap-4">
                <FormPhoneNumber name="phone" label="phone" />
                <FormGenralSelect
                  endpoint="guest/countries?paginate=0"
                  general={true}
                  name="country_id"
                  label="country"
                  placeholder="country"
                />
              </div>

              <div className="grid lg:grid-cols-2 gap-3">
                <FormGenralSelect
                  endpoint={`guest/cities?filters[country_id]=${form.getValues("country_id")}&paginate=0`}
                  general={true}
                  name="city_id"
                  label="city"
                  placeholder="city"
                  disabled={form.getValues("country_id") == "" ? true : false}
                  enabled={form.getValues("country_id") == "" ? false : true}
                />
                <FormGenralSelect
                  endpoint={`guest/districts?filters[city_id]=${form.getValues("city_id")}&paginate=0`}
                  general={true}
                  name="district_id"
                  label="district"
                  placeholder="district"
                  disabled={form.getValues("city_id") == "" ? true : false}
                  enabled={form.getValues("city_id") == "" ? false : true}
                />
              </div>
              <FormTextarea
                name="description"
                label="location_description"
                placeholder="location_description"
              />
              <GoogleMap
                defaultMarkerPostion={{
                  lat: singleItem?.location?.latitude || 30.9585477,
                  lng: singleItem?.location?.longitude || 31.1613696,
                }}
                onMarkerPositionChange={(position) => {
                  setValue("lng", position.lng);
                  setValue("lat", position.lat);
                }}
              />
              <FormSwitch name="is_default" label="is_default" />
            </div>

            <div className="flex justify-center lg:justify-end items-center gap-2 mt-8 me-2">
              <button
                type="button"
                onClick={() => {
                  dialogOpen(false);
                  form.reset();
                }}
                disabled={loading || mainLoader}
                className="rounded-xl cursor-pointer font-medium lg:text-lg text-base lg:w-[177px] w-[150px]  text-center !h-[56px]  bg-white hover:bg-primary hover:text-white transition-colors text-primary border border-primary"
              >
                {t("BUTTONS.cancel")}
              </button>
              <AppButton
                title={t("BUTTONS.confirm_location")}
                buttonType="submit"
                loader={loading || mainLoader}
                disabled={loading || mainLoader}
                button
                className="!rounded-xl !font-medium lg:!w-[177px] !w-[150px] lg:!text-lg !text-base   text-center !h-[56px]  bg-primary text-white"
              />
            </div>
          </form>
        </Form>
      </div>
    </ScrollArea>
  );
};

export default LocationForm;
