"use client";
import postData from "@/api/post-data";
import SubmitButton from "@/app/ui/shared/SubmitButton";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { useLocale, useTranslations } from "next-intl";
import { useForm } from "react-hook-form";
import { z } from "zod";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import config from "@/services/jodit-config";
import JoditEditor from "jodit-react";
import { useEffect, useState } from "react";
import { FaSpinner } from "react-icons/fa";

export default function ProductDetailsForm({
  shippingType,
  brands,
  weightUnits,
  country,
  productId,
  productDetails,
}) {
  const e = useTranslations("form-errors");
  const t = useTranslations("vendor");
  const l = useLocale();
  const [isFetching, setIsFetching] = useState(true);


  useEffect(() => {
    if (shippingType) {
      setIsFetching(false);
    }
  }, [shippingType]);

  const form = useForm({
    resolver: zodResolver(
      z.object({
        is_free_shipping: z.string({ message: e('required') }).min(1, { message: e('required') }),
        text: z.string({ message: e('required') }).min(1, { message: e('required') }),
        weight: z.string({ message: e('required') }).min(1, { message: e('required') }),
        weight_unit: z.string({ message: e('required') }).min(1, { message: e('required') }),
        price: z.string({ message: e('required') }).min(1, { message: e('required') })
          .refine((value) => !isNaN(value) && parseFloat(value) > 0, {
            message: t("positive_number"),
          }),
        cost: z.string({ message: e('required') }).min(1, { message: e('required') })
          .refine((value) => !isNaN(value) && parseFloat(value) > 0, {
            message: t("positive_number"),
          }),
        discount: z.string({ message: e('required') }).min(1, { message: e('required') })
          .refine(
            (value) =>
              !isNaN(value) &&
              parseFloat(value) >= 0 &&
              parseFloat(value) <= 99,
            { message: t("discount") }
          ),
        brand: z.string({ message: e('required') }).min(1, { message: e('required') }),
        country_of_origin: z.string({ message: e('required') }).min(1, { message: e('required') }),
        description: z.string({ message: e('required') }).min(1, { message: e('required') }),
        sku: z.string({ message: e('required') }).min(1, { message: e('required') }),
        points: z.string({ message: e('required') }).min(1, { message: e('required') }),
        refrence: z.string({ message: e('required') }).min(1, { message: e('required') }),
      }).refine((data) => parseFloat(data.price) > parseFloat(data.cost), {
        message: t("price_error"),
        path: ["price"],
      })
    ),
    defaultValues: {
      is_free_shipping: productDetails?.is_free_shipping || '',
      weight: productDetails?.weight || '',
      weight_unit: productDetails?.weight_unit || '',
      price: productDetails?.price || '',
      cost: productDetails?.cost || '',
      discount: productDetails?.discount || '',
      brand: productDetails?.brand_id || '',
      country_of_origin: productDetails?.country_of_origin || '',
      description: productDetails?.text || '',
      text: productDetails?.description[0] || '',
      sku: productDetails?.sku || '',
      points: productDetails?.points || '',
      refrence: productDetails?.ref_number || '',
    }
  });

  const {
    formState: { isSubmitting },
  } = form;

  async function onSubmit(values) {
    const formData = new FormData();
    for (const [key, value] of Object.entries(values)) {
      formData.append(key, value);
    }
    formData.append("id", productId);
    const { error, message } = await postData({
      endPoint: "/user/products/savedetails",
      body: formData,
    });

    if (error) {
      return toastError(message);
    }
    toastSuccess(message);
  }

  return (
    <Form {...form}>
      <form
        method="post"
        onSubmit={form.handleSubmit(onSubmit)}
        className="flex flex-col gap-4 max-md:mx-4 mt-12 mb-20 rounded-lg py-4 max-w-5xl"
      >
        {/*  type of shipping */}
        <FormField
          control={form.control}
          name="is_free_shipping"
          render={({ field }) => (
            <FormItem>
              <Select
                onValueChange={field.onChange}
                value={field.value}
                dir={l === "en" ? "ltr" : "rtl"}
              >
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder={t("shipping_type")} />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {isFetching ? (
                    <FaSpinner className="animate-spin m-5 " />
                  ) : shippingType.length == 0 ? (
                    <p>{t("no_shipping")}</p>
                  ) : (
                    shippingType?.map((shipping, i) => (
                      <SelectItem key={i} value={String(shipping?.value)}>
                        {shipping?.key}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>

              <FormMessage />
            </FormItem>
          )}
        />
        {/* weight of package */}
        <div className="flex gap-2">
          {/* weight */}
          <FormField
            name="weight"
            control={form.control}
            render={({ field }) => (
              <FormItem className="flex-1">
                <FormControl>
                  <Input
                    type="number"
                    {...field}
                    placeholder={t("product_weight")}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          {/* unit */}
          <FormField
            control={form.control}
            name="weight_unit"
            render={({ field }) => (
              <FormItem className="flex-1">
                <Select
                  onValueChange={field.onChange}
                  value={field.value}
                  dir={l === "en" ? "ltr" : "rtl"}
                >
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder={t("product_weight_unit")} />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {isFetching ? (
                      <FaSpinner className="animate-spin m-5 " />
                    ) : weightUnits.length == 0 ? (
                      <p>{t("no_units")}</p>
                    ) : (
                      weightUnits?.map((unit, i) => (
                        <SelectItem key={i} value={unit?.value}>
                          {unit?.value}
                        </SelectItem>
                      ))
                    )}
                  </SelectContent>
                </Select>

                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* code */}
        <FormField
          name="sku"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Input
                  {...field}
                  type="text"
                  placeholder={t("product_code")}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* price before and after*/}
        <div className="flex gap-2">
          {/* init price */}
          <FormField
            name="cost"
            control={form.control}
            render={({ field }) => (
              <FormItem className="flex-1">
                <FormControl>
                  <Input
                    type="number"
                    {...field}
                    placeholder={t("product_init_price")}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          {/* final price */}
          <FormField
            name="price"
            control={form.control}
            render={({ field }) => (
              <FormItem className="flex-1">
                <FormControl>
                  <Input
                    type="number"
                    {...field}
                    placeholder={t("product_final_price")}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* discount */}
        <FormField
          name="discount"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Input
                  type="number"
                  {...field}
                  placeholder={t("product_discount")}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        {/*  type of brands*/}
        <FormField
          control={form.control}
          name="brand"
          render={({ field }) => (
            <FormItem>
              <Select
                onValueChange={field.onChange}
                defaultValue={field.value}
                dir={l === "en" ? "ltr" : "rtl"}
              >
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder={t("product_brand")} />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {isFetching ? (
                    <FaSpinner className="animate-spin m-5 " />
                  ) : brands.length == 0 ? (
                    <p>{t("no_brands")}</p>
                  ) : (
                    brands?.map((brand, i) => (
                      <SelectItem key={i} value={String(brand?.id)}>
                        {brand?.name}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>

              <FormMessage />
            </FormItem>
          )}
        />
        {/* country */}
        <FormField
          name="country_of_origin"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <Select
                onValueChange={field.onChange}
                defaultValue={field.value}
                dir={l === "en" ? "ltr" : "rtl"}
              >
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder={t("country")} />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {isFetching ? (
                    <FaSpinner className="animate-spin m-5 " />
                  ) : country.length == 0 ? (
                    <p>{t("no_countries")}</p>
                  ) : (
                    country?.map((country, i) => (
                      <SelectItem key={i} value={country?.country_id}>
                        {country?.title}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>

              <FormMessage />
            </FormItem>
          )}
        />
        {/* points */}
        <FormField
          name="points"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Input
                  type="number"
                  {...field}
                  placeholder={t("product_points")}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* refrence number_fatoorah_number */}
        <FormField
          name="refrence"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Input
                  type="number"
                  {...field}
                  placeholder={t("number_fatoorah_number")}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* account details*/}
        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Textarea
                  placeholder={t("account_details")}
                  className="resize-none"
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField control={form.control} name="text" render={({ field }) => (
          <FormItem>
            <FormControl>
              <JoditEditor
                value={field.value} // Use value from props
                config={config}
                onChange={field.onChange}
              />
            </FormControl>
            <FormMessage />
          </FormItem>
        )} />

        {/* Submit button */}
        <SubmitButton
          className="w-28"
          isIcon={false}
          text={t("save")}
          loading={isSubmitting}
        />
      </form>
    </Form>
  );
}
