"use client";
import SubmitButton from "@/app/ui/shared/SubmitButton";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { createProductFeature } from "@/services/create-product-feature";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { deleteProductFeature } from "@/services/delete-product-feature";
import { updateProductFeature } from "@/services/update-product-feature";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

export default function Size({ data, productId }) {
  const size = data && data.options[0];
  const t = useTranslations("vendor");
  const error = useTranslations("form-errors");
  const [isPending, setIsPending] = useState(false);


  const form = useForm({
    resolver: zodResolver(
      z.object({
        quantity: z.string({ errorMap: () => ({ message: error("required") }) }),
        price: z.string({ errorMap: () => ({ message: error("required") }) }),
        name: z.string({ errorMap: () => ({ message: error("required") }) }),
        value: z.string({ errorMap: () => ({ message: error("required") }) }),
      })
    ),
    defaultValues: {
      name: size?.name || '',
      price: size?.price || '',
      value: size?.title || '',
      quantity: size?.count || '',
    }
  });

  const { formState: { isSubmitting } } = form;


  async function onSubmit(values) {
    if (data) { // Update color feature
      const formData = new FormData();
      formData.append('name', values.name);
      formData.append('value', values.value);
      formData.append('count', values.quantity);
      formData.append('price', values.price);
      const { message, error } = await updateProductFeature(data.id, formData)
      if (error) {
        toastError(message);
        return;
      }
      toastSuccess(message);
      return;
    } /////

    // Create new color feature 
    const formData = new FormData();
    formData.append('feature[0][type]', 'size');
    formData.append('feature[0][name]', values.name);
    formData.append('feature[0][value]', values.value);
    formData.append('feature[0][quantity]', values.quantity);
    formData.append('feature[0][price]', values.price);

    const { message, error } = await createProductFeature(productId, formData);
    if (error) {
      toastError(message);
      return;
    }
    toastSuccess(message);
  }
  async function deleteFeature() {
    setIsPending(true);
    const { message, error } = await deleteProductFeature(data.id);
    setIsPending(false);
    if (error) {
      toastError(message);
      return;
    }
    toastSuccess(message);
  }

  return (
    <Form {...form}>
      <form
        method="post"
        onSubmit={form.handleSubmit(onSubmit)}
        className="grid grid-cols-4 md:w-3/4 gap-4 mt-4 flex-wrap"
      >
        <FormField
          name="name"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t("size")}</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  placeholder={t("size")}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          name="value"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t("value")}</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  placeholder={t("value")}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          name="price"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t("addedPrice")}</FormLabel>
              <FormControl>
                <Input
                  type="number"
                  {...field}
                  placeholder={t("addedPrice")}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          name="quantity"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t("availableQuantity")}</FormLabel>
              <FormControl>
                <Input
                  type="number"
                  {...field}
                  placeholder={t("availableQuantity")}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        {/* Submit buttons */}
        {
          size ?
            <div className="flex gap-4">
              <SubmitButton
                className="bg-amber-500 hover:bg-amber-500/90"
                isIcon={false}
                text={t('update')}
                loading={isSubmitting}
              />
              <Button disabled={isPending} type="button" onClick={deleteFeature} className="bg-red-500 hover:bg-red-500/90">
                {
                  isPending ? <Loader2 className="animate-spin" />
                    :
                    t('delete')
                }
              </Button>
            </div>
            :
            <SubmitButton
              className="w-28 self-center"
              isIcon={false}
              text={t("save")}
              loading={isSubmitting}
            />
        }
      </form>
    </Form>
  );
}
