"use client";

import postData from "@/api/post-data";
import BlackBtn from "@/app/ui/shared/BlackBtn";
import PopUpForm from "@/app/ui/shared/PopUpForm";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { BsArrowRight } from "react-icons/bs";
import { z } from "zod";
import AlertWarning from "../../shared/AlertWarning";
import TicketsUi from "./TicketsUi";

export default function Tickets({ ticketsData, catPirData, locale }) {
  const [tickets, setTickets] = useState(ticketsData.data || []); // State for tickets
  const [categories, setCategories] = useState([]);
  const [priorities, setPriorities] = useState([]);
  const [showModal, setShowModal] = useState(false);

  const e = useTranslations("form-errors");
  const t = useTranslations("form-labels");
  const s = useTranslations("shared");

  const { data, error, message } = catPirData;

  useEffect(() => {
    if (data) {
      setCategories(data.categories || []);
      setPriorities(data.priorities || []);
    }
  }, []);

  const form = useForm({
    resolver: zodResolver(
      z.object({
        subject: z
          .string({ errorMap: () => ({ message: e("at-least20") }) })
          .min(20),
        contents: z
          .string({ errorMap: () => ({ message: e("at-least20") }) })
          .min(20),
        category: z
          .string({ errorMap: () => ({ message: e("required") }) })
          .min(1),
        priority: z
          .string({ errorMap: () => ({ message: e("required") }) })
          .min(1),
      })
    ),
  });

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

  if (error) return <AlertWarning text={message} />;

  const onSubmit = async (formData) => {
    const formDataObject = new FormData();
    formDataObject.append("subject", formData.subject);
    formDataObject.append("contents", formData.contents);
    formDataObject.append("category", formData.category);
    formDataObject.append("priority", formData.priority);

    const { error, message, data } = await postData({
      endPoint: "/tickets/store",
      body: formDataObject,
      locale,
    });
    if (error) {
      for (const [key, value] of Object.entries(data)) {
        toastError(value);
      }
      return;
    }

    toastSuccess(message);
    setShowModal(false);

    // Update tickets state
    setTickets((prevTickets) => [...prevTickets, { ...data }]);
  };

  const modelForm = (
    <Form {...form}>
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 p-6">
        {/* Subject Input */}
        <FormField
          name="subject"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <input
                  {...field}
                  type="text"
                  className="btn-outline-black"
                  placeholder={t("subject")}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        {/* Category Select */}
        <FormField
          name="category"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Select
                  className="btn-outline-black border-black"
                  value={field.value}
                  dir={locale == "en" ? "ltr" : "rtl"}
                  onValueChange={field.onChange}
                >
                  <SelectTrigger className="h-8 md:h-10 lg:h-12 btn-outline-black border-black focus:ring-main">
                    <SelectValue
                      className="placeholder:text-secondary btn-outline-black"
                      placeholder={t("category")}
                    />
                  </SelectTrigger>
                  <SelectContent>
                    {categories.map((item) => (
                      <SelectItem key={item.id} value={String(item.id)}>
                        {item?.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        {/* Priority Select */}
        <FormField
          name="priority"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Select
                  className="btn-outline-black border-black"
                  value={field.value}
                  dir={locale == "en" ? "ltr" : "rtl"}
                  onValueChange={field.onChange}
                >
                  <SelectTrigger className="h-8 md:h-10 lg:h-12 btn-outline-black border-black focus:ring-main">
                    <SelectValue
                      className="placeholder:text-secondary btn-outline-black"
                      placeholder={t("priority")}
                    />
                  </SelectTrigger>
                  <SelectContent>
                    {priorities.map((item) => (
                      <SelectItem key={item.id} value={String(item.id)}>
                        {item?.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        {/* Content Textarea */}
        <FormField
          name="contents"
          control={form.control}
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <textarea
                  {...field}
                  className="btn-outline-black"
                  rows="4"
                  placeholder={t("ticket-des")}
                ></textarea>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        {/* Buttons */}
        <div className="flex justify-start">
          <button
            disabled={isSubmitting}
            type="submit"
            className="btn-main gap-x-1 flex items-center text-white rounded-sm text-sm p-2"
          >
            {isSubmitting ? (
              <Loader2 className="animate-spin" />
            ) : (
              <BsArrowRight />
            )}
            {s("send-ticket")}
          </button>
        </div>
      </form>
    </Form>
  );

  return (
    <section>
      <div className="flex mb-6 flex-wrap gap-2 xl:gap-10 justify-center">
        <BlackBtn
          onclick={() => setShowModal(true)}
          title={s("new-ticket")}
          className={"self-end"}
        />
      </div>
      <TicketsUi ticketsData={{ data: tickets }} />
      {showModal && (
        <PopUpForm
          showModal={showModal}
          setShowModal={setShowModal}
          title={s("new-ticket")}
          form={modelForm}
        />
      )}
    </section>
  );
}
