"use client";
import getCountryId from "@/api/countries/getCountryId";
import fetchData from "@/api/fetch-data";
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 { zodResolver } from "@hookform/resolvers/zod";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { FaSpinner } from "react-icons/fa";
import ar from "react-phone-number-input/locale/ar";
import en from "react-phone-number-input/locale/en";
import { z } from "zod";
import CountrySelect from "../shared/CountrySelect";
import CustomPhoneInput from "../shared/CustomPhoneInput";
import ShippingMethod from "./ShippingMethod";

export default function PersonalDetailsForm({ paymentId }) {
  const error = useTranslations("form-errors");
  const label = useTranslations("form-labels");
  const locale = useLocale();
  const t = useTranslations("checkout-info");
  const [cities, setCities] = useState([]);
  const [isCitiesLoading, setIsCitiesLoading] = useState(false);
  const [shippingData, setShippingData] = useState({});
  const [continuePay, setContinuePay] = useState(false);

  const form = useForm({
    resolver: zodResolver(
      z.object({
        name: z
          .string({ errorMap: () => ({ message: error("required") }) })
          .min(1),
        lastname: z
          .string({ errorMap: () => ({ message: error("required") }) })
          .min(1),
        email: z
          .string({ errorMap: () => ({ message: error("email") }) })
          .email(),
        phone: z
          .string({ errorMap: () => ({ message: error("mobile") }) })
          .min(10)
          .max(16),
        country: z
          .string({ errorMap: () => ({ message: error("required") }) })
          .min(1),
        city: z
          .string({ errorMap: () => ({ message: error("required") }) })
          .min(1),
        region: z
          .string({ errorMap: () => ({ message: error("required") }) })
          .min(1),
        address: z
          .string({ message: error("required") })
          .min(3, { message: error("at-least3") }),
      })
    ),
  });
  const {
    formState: { isSubmitting },
  } = form;
  // Submit handler
  const onSubmit = async (values) => {
    const countryId = await getCountryId(values.country);
    values.country = countryId;
    setShippingData({
      ...values,
      payment_method: paymentId,
    });
    setContinuePay(true);
  };

  async function getCitiesByCountryId(countryCode) {
    const { setValue } = form;
    setValue("country", countryCode);
    const countryId = await getCountryId(countryCode);
    if (countryId) {
      setIsCitiesLoading(true);
      const response = await fetchData({ endPoint: `/cities/${countryId}` });
      if (response.error == false) {
        setIsCitiesLoading(false);
        setCities(response.data);
      }
      setIsCitiesLoading(false);
    }
  }

  return (
    <>
      <section>
        <h1 className="text-xl font-bold mb-6">{t("personal-details")}</h1>
        <Form {...form}>
          <form className="space-y-4" onSubmit={form.handleSubmit(onSubmit)}>
            <div className="grid grid-cols-2 gap-4">
              <FormField
                name="name"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <Input
                        className="focus-visible:ring-dark border-dark"
                        {...field}
                        placeholder={label("first-name")}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                name="lastname"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <Input
                        className="focus-visible:ring-dark border-dark"
                        {...field}
                        placeholder={label("last-name")}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <FormField
              name="email"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      className="focus-visible:ring-dark border-dark"
                      {...field}
                      placeholder={label("email")}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              name="phone"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <div id="personal-details-mobile">
                      <CustomPhoneInput
                        value={field.value}
                        valueOnChange={field.onChange}
                        className="flex gap-4 items-start"
                        placeholder={label("mobile")}
                        labels={locale === "ar" ? ar : en}
                      />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              name="country"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <CountrySelect
                      value={field.value}
                      onChange={getCitiesByCountryId}
                      placeholder={label("country")}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              name="city"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Select
                      dir={locale === "ar" ? "rtl" : "ltr"}
                      value={field.value}
                      onValueChange={field.onChange}
                    >
                      <SelectTrigger className="focus-visible:ring-dark border-dark">
                        <SelectValue placeholder={label("city")} />
                      </SelectTrigger>
                      <SelectContent className="max-h-60">
                        {!isCitiesLoading ? (
                          cities?.map((city) => (
                            <SelectItem key={city.id} value={String(city.id)}>
                              {city.title}
                            </SelectItem>
                          ))
                        ) : (
                          <FaSpinner className="animate-spin m-5 " />
                        )}
                      </SelectContent>
                    </Select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              name="region"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      className="focus-visible:ring-dark border-dark"
                      {...field}
                      placeholder={label("area")}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              name="address"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      className="focus-visible:ring-dark border-dark"
                      {...field}
                      placeholder={label("address")}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            {continuePay ? null : (
              <button
                type="submit"
                className="btn btn-btnColor-default w-full flex justify-center items-center"
              >
                {isSubmitting ? (
                  <>
                    <FaSpinner size={20} className="text-white animate-spin" />
                    &nbsp;{t("orderInProgress")}
                  </>
                ) : (
                  <> {t("completeOrder")}</>
                )}
              </button>
            )}
          </form>
        </Form>
      </section>
      {continuePay && <ShippingMethod shippingData={shippingData} />}
    </>
  );
}
