"use client";
import FormInput from "@/shared/form-controls/FormInput";
import FormPhoneNumber from "@/shared/form-controls/FormPhoneNumber";
import { useTranslations } from "next-intl";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { Form } from "@/shared/ui/form";
import AppButton from "@/shared/buttons/AppButton";
import { UseMutate } from "@/hooks/UseMutate";
import FormGenralSelect from "@/shared/form-controls/FormGenralSelect";
import { setLocation } from "@/store/location.slice";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/store/store";
import { AddAddress } from "@/store/address.slice";
import GoogleMap from "@/shared/googleMap/GoogleMap";
import FormTextarea from "@/shared/form-controls/FormTextarea";
import FormSwitch from "@/shared/form-controls/FormSwtich";

export default function CheckoutLocationForm({
  setLocationId,
}: {
  setLocationId: (value: string) => void;
}) {
  const dispatch = useDispatch<AppDispatch>();
  const t = useTranslations("");
  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],
        t("validations.requiredField", { field: t("LABELS.is_default") }),
      ),
  });

  const form = useForm({
    resolver: yupResolver(formSchema),
    defaultValues: {
      phone: "",
      phone_code: "",
      phone_limit: 9,
      lat: 0,
      lng: 0,
      country_id: "",
      city_id: "",
      district_id: "",
      description: "",
      is_default: false,
    },
  });
  const { setValue, getValues } = form;
  const { mutate, isLoading } = UseMutate({
    endpoint: "client/addresses",
    onSuccess: async (responseData: any) => {
      dispatch(
        setLocation({
          id: responseData?.data?.id,
          is_default: responseData?.data?.is_default,
          phone_code: responseData?.data?.contact?.phone_code,
          phone: responseData?.data?.contact?.phone,
          country: responseData?.data?.location?.country,
          city: responseData?.data?.location?.city,
          district: responseData?.data?.location?.district,
          lng: responseData?.data?.location?.longitude,
          lat: responseData?.data?.location?.latitude,
          description: responseData?.data?.description,
          isLoading: false,
        }),
      );
      setLocationId(responseData?.data?.id);
      dispatch(AddAddress({ address: responseData?.data }));
      form.reset();
    },
  });
  const handleSubmit = async (values: yup.InferType<typeof formSchema>) => {
    const finalOut = {
      ...values,
      is_default: +values?.is_default,
      longitude: values?.lng?.toString(),
      latitude: values?.lat?.toString(),
    };
    mutate({ ...finalOut });
  };
  return (
    <div className="border border-primary-light bg-white p-4 rounded-2xl relative">
      <h2 className=" text-primary-dark font-medium lg:text-xl text-base text-start lg:leading-[50px]   leading-8 mb-4">
        {t("Text.shippingInfo")}
      </h2>
      <Form {...form}>
        <div>
          <div className="flex flex-col gap-4">
            <div className="lg: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: 0, lng: 0 }}
              onMarkerPositionChange={(position) => {
                setValue("lng", position.lng);
                setValue("lat", position.lat);
              }}
            />
            <FormSwitch name="is_default" label="is_default" />

            <div className="flex justify-end">
              <AppButton
                title={t("BUTTONS.save_address")}
                buttonType="button"
                loader={isLoading}
                disabled={isLoading}
                button
                onClick={form.handleSubmit(handleSubmit)}
                className="w-fit xl:rounded-full rounded-xl lg:text-base text-sm lg:px-4 px-2 py-2 font-medium text-center  bg-primary hover:bg-white hover:text-primary transition-colors text-white border border-primary"
              />
            </div>
          </div>
        </div>
      </Form>
    </div>
  );
}
