"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 {
  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";

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 CreateFAQModal() {
  const router = useRouter();
  const { toast } = useToast();

  const [isOpen, setIsOpen] = useState(false);
  const [satkerData, setSatkerData] = useState<string[]>([]);
  const [unitData, setUnitData] = useState<string[]>([]);

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

  const target = form.watch("publishTo");
  const isAllTargetChecked = publishToList.every((item) =>
    target?.includes(item.id)
  );

  const onSubmit = async (data: z.infer<typeof FormSchema>) => {
    const request = {
      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 dibuat",
    });
    router.push("/admin/settings/faq?dataChange=true");
    setIsOpen(false);
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <Button color="primary" size="md">
          Tambah FAQ
        </Button>
      </DialogTrigger>
      <DialogContent size="md">
        <DialogHeader>
          <DialogTitle>Tambah 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"
                        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
                                      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={false}
                              sendDataToParent={(data) => setUnitData(data)}
                            />
                          )}
                        {item.id === "satker" &&
                          form.getValues("publishTo")?.includes(item.id) && (
                            <UnitMapping
                              isDetail={false}
                              unit="Satker"
                              sendDataToParent={(data) => setSatkerData(data)}
                            />
                          )}
                      </>
                    ))}
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            /> */}

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

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

                  <FormMessage />
                </FormItem>
              )}
            />
            <DialogFooter>
              <Button
                type="submit"
                color="primary"
                size="md"
                className="text-xs"
              >
                Tambah FAQ
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
