"use client";
import fetchData from "@/api/fetch-data";
import postData from "@/api/post-data";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import JoditEditor from "jodit-react";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import SubmitButton from "../shared/SubmitButton";
import config from "@/services/jodit-config";


export default function TranslateProduct({ id }) {
  const [selectLang, setSelectLang] = useState("ar");
  const [isPending, setIsPending] = useState(false);
  const f = useTranslations("form-labels");
  const e = useTranslations("form-errors");
  const t = useTranslations("vendor");
  const l = useLocale();

  // Form schema
  const formSchema = z.object({
    title: z
      .string({ message: e("required") })
      .min(6, { message: e("min6") })
      .trim(),
    description: z.string().optional(),
    information: z.string().optional(),
  });

  // Initialize form
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      title: "",
      description: "",
      information: "",
    },
  });

  // Fetch translation data when language or product changes
  useEffect(() => {
    async function fetchTranslation() {
      if (!id) return;

      setIsPending(true);
      const { error, data } = await fetchData({
        endPoint: `/user/products/translation/${id}/${selectLang}`,
      });
      setIsPending(false);
      if (error) {
        form.reset();
      } else {
        // Explicitly set form values
        form.setValue("title", data?.title || "");
        form.setValue("description", data?.description || "");
        form.setValue("information", data?.info || "");
      }
    }

    fetchTranslation();
  }, [id, selectLang, form]);

  // Submit handler
  async function onSubmit(values) {
    const lang_id = selectLang === "ar" ? 2 : 1;

    const formData = new FormData();
    formData.append("id", id);
    formData.append("lang_id", lang_id);

    Object.entries(values).forEach(([key, value]) => {
      formData.append(key, value);
    });

    const { error, message } = await postData({
      endPoint: `/user/products/translation`,
      body: formData,
    });

    // Handle response as needed
    if (error) {
      toastError(message);
    } else {
      // Success handling
      toastSuccess(message);
    }
  }

  return (
    <section className="md:ms-4">
      <Select
        disabled={isPending}
        value={selectLang}
        dir={l === "en" ? "ltr" : "rtl"}
        onValueChange={(value) => {
          setSelectLang(value);
        }}
      >
        <SelectTrigger className="w-full md:w-[180px] mb-2">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="en">{t("en-translate")}</SelectItem>
          <SelectItem value="ar">{t("ar-translate")}</SelectItem>
        </SelectContent>
      </Select>
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-2 md:w-1/2"
        >
          <FormField
            name="title"
            control={form.control}
            render={({ field }) => (
              <FormItem>
                <FormLabel>{f("title")}</FormLabel>
                <FormControl>
                  <Input type="text" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            name="description"
            control={form.control}
            render={({ field }) => (
              <FormItem>
                <FormLabel>{f("description")}</FormLabel>
                <FormControl>
                  <JoditEditor
                    onChange={field.onChange}
                    value={field.value}
                    config={config}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            name="information"
            control={form.control}
            render={({ field }) => (
              <FormItem>
                <FormLabel>{f("account-info")}</FormLabel>
                <FormControl>
                  <Textarea {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <SubmitButton
            loading={form.formState.isSubmitting}
            text={f("save")}
          />
        </form>
      </Form>
    </section>
  );
}
