"use client";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { useRouter } from "@/i18n/routing";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import {
  detailDataFAQ,
  getUserRoles,
  postCategory,
  postDataFAQ,
} from "@/service/settings/settings";
import { Fragment, useEffect, useState } from "react";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Icon } from "@iconify/react/dist/iconify.js";
import { Textarea } from "@/components/ui/textarea";
import { close, error, loading } from "@/config/swal";
import { useToast } from "@/components/ui/use-toast";
import { stringify } from "querystring";
import { useDropzone } from "react-dropzone";
import { CloudUpload } from "lucide-react";
import Image from "next/image";
import { Upload } from "tus-js-client";
import { id } from "date-fns/locale";
import { htmlToString } from "@/utils/globals";

const FormSchema = z.object({
  answer: z.string({
    required_error: "Required",
  }),
  question: z.string({
    required_error: "Required",
  }),
  publishTo: z.string({
    required_error: "Required",
  }),

  // publishTo: z.array(z.string()).refine((value) => value.some((item) => item), {
  //   message: "Required",
  // }),
});

const publishToList = [
  {
    id: "mabes",
    name: "Nasional",
  },
  {
    id: "polda",
    name: "Polda",
  },
  {
    id: "satker",
    name: "Satker",
  },
  {
    id: "internasional",
    name: "Internasional",
  },
];

export default function EditFAQModal(props: { id: string; isDetail: boolean }) {
  const { id, isDetail } = props;
  const router = useRouter();
  const { toast } = useToast();

  const [isOpen, setIsOpen] = useState(false);

  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
  });

  useEffect(() => {
    initState();
  }, [id]);

  const initState = async () => {
    const res = await detailDataFAQ(id);
    const data = res?.data?.data;
    form.setValue("question", htmlToString(data.question));
    form.setValue("answer", htmlToString(data.answer));
    form.setValue(
      "publishTo",
      data.isInternational ? "international" : "wilayah"
    );
  };

  const onSubmit = async (data: z.infer<typeof FormSchema>) => {
    const request = {
      id: Number(id),
      question: data.question,
      answer: data.answer,
      isInternational: data.publishTo === "wilayah" ? false : true,
      isActive: true,
    };

    const response = await postDataFAQ(request);
    close();
    if (response?.error) {
      toast({ title: stringify(response.message), variant: "destructive" });
      return false;
    }
    toast({
      title: "Succes",
      description: "FAQ berhasil diubah",
    });
    router.push("/admin/settings/faq?dataChange=true");
    setIsOpen(false);
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <a className="hover:underline cursor-pointer">
          {isDetail ? "Detail" : "Edit"}
        </a>
      </DialogTrigger>
      <DialogContent size="md">
        <DialogHeader>
          <DialogTitle>{isDetail ? "Detail" : "Edit"} FAQ</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-3 bg-white rounded-sm"
          >
            <FormField
              control={form.control}
              name="publishTo"
              render={({ field }) => (
                <FormItem className="space-y-3">
                  <FormLabel>Wilayah Publish</FormLabel>
                  <FormControl>
                    <RadioGroup
                      onValueChange={field.onChange}
                      value={field.value}
                      className="flex flex-row space-x-1"
                    >
                      <FormItem className="flex items-center space-x-3 space-y-0">
                        <FormControl>
                          <RadioGroupItem value="wilayah" />
                        </FormControl>
                        <FormLabel className="font-normal">Wilayah</FormLabel>
                      </FormItem>
                      <FormItem className="flex items-center space-x-3 space-y-0">
                        <FormControl>
                          <RadioGroupItem value="international" />
                        </FormControl>
                        <FormLabel className="font-normal">
                          Internasional
                        </FormLabel>
                      </FormItem>
                    </RadioGroup>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            {/* <FormField
              control={form.control}
              name="publishTo"
              render={() => (
                <FormItem>
                  <FormLabel>Wilayah Publish</FormLabel>

                  <div className="flex flex-row items-center gap-2">
                    <div className="flex gap-3 items-center">
                      <Checkbox
                        id="all"
                        disabled={isDetail}
                        checked={isAllTargetChecked}
                        onCheckedChange={(checked) => {
                          if (checked) {
                            form.setValue(
                              "publishTo",
                              publishToList.map((item) => item.id)
                            );
                          } else {
                            form.setValue("publishTo", []);
                          }
                        }}
                      />
                      <label htmlFor="all" className="text-sm">
                        Semua
                      </label>
                    </div>
                    {publishToList.map((item) => (
                      <>
                        <FormField
                          key={item.id}
                          control={form.control}
                          name="publishTo"
                          render={({ field }) => {
                            return (
                              <FormItem
                                key={item.id}
                                className="flex flex-row items-start "
                              >
                                <div className="flex items-center gap-3">
                                  <FormControl>
                                    <Checkbox
                                      disabled={isDetail}
                                      checked={field.value?.includes(item.id)}
                                      onCheckedChange={(checked) => {
                                        return checked
                                          ? field.onChange([
                                              ...field.value,
                                              item.id,
                                            ])
                                          : field.onChange(
                                              field.value?.filter(
                                                (value) => value !== item.id
                                              )
                                            );
                                      }}
                                    />
                                  </FormControl>
                                  <FormLabel className="font-normal">
                                    {item.name}{" "}
                                  </FormLabel>
                                </div>
                              </FormItem>
                            );
                          }}
                        />
                        {item.id === "polda" &&
                          form.getValues("publishTo")?.includes(item.id) && (
                            <UnitMapping
                              unit="Polda"
                              isDetail={isDetail}
                              sendDataToParent={(data) => setUnitData(data)}
                            />
                          )}
                        {item.id === "satker" &&
                          form.getValues("publishTo")?.includes(item.id) && (
                            <UnitMapping
                              isDetail={isDetail}
                              unit="Satker"
                              sendDataToParent={(data) => setSatkerData(data)}
                            />
                          )}
                      </>
                    ))}
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            /> */}

            <FormField
              control={form.control}
              name="question"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Pertanyaan</FormLabel>
                  <FormControl>
                    <Textarea
                      readOnly={isDetail}
                      placeholder="Masukkan pertanyaan"
                      value={field.value}
                      onChange={field.onChange}
                    />
                  </FormControl>

                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="answer"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Jawaban</FormLabel>
                  <FormControl>
                    <Textarea
                      readOnly={isDetail}
                      placeholder="Masukkan jawaban"
                      value={field.value}
                      onChange={field.onChange}
                    />
                  </FormControl>

                  <FormMessage />
                </FormItem>
              )}
            />
            {!isDetail && (
              <DialogFooter>
                <Button
                  type="submit"
                  color="primary"
                  size="md"
                  className="text-xs"
                >
                  Edit FAQ
                </Button>
              </DialogFooter>
            )}
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
