"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,
  detailDataFeedback,
  getCategoriesAll,
  getUserRoles,
  postCategory,
  postDataFAQ,
  postDataFeedback,
} from "@/service/settings/settings";
import { Fragment, useEffect, useState } from "react";

import { close, error, loading } from "@/config/swal";
import { useToast } from "@/components/ui/use-toast";
import { stringify } from "querystring";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Check, ChevronsUpDown } from "lucide-react";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { cn } from "@/lib/utils";

const FormSchema = z.object({
  name: z.string({
    required_error: "Required",
  }),
  category: 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 EditTagModal(props: {
  id: string;
  isDetail: boolean;
  data: {
    id: number;
    tagName: string;
    categoryId: number;
    subCategoryId: number;
  };
}) {
  const { id, isDetail, data } = props;
  const router = useRouter();
  const { toast } = useToast();
  const [categoryList, setCategoryList] = useState<
    { id: number; label: string; value: string }[]
  >([]);
  const [isOpen, setIsOpen] = useState(false);

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

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

  const initState = async () => {
    form.setValue("name", data.tagName);
    form.setValue("category", String(data.categoryId));
  };

  const onSubmit = async (data: z.infer<typeof FormSchema>) => {
    const request = {
      id: Number(id),
      tagName: data.name,
      categoryId: Number(data.category),
      isActive: true,
    };

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

  useEffect(() => {
    getCategoryParent();
  }, []);
  async function getCategoryParent() {
    const response = await getCategoriesAll();
    const res = response?.data?.data.content;
    console.log("res", res);
    var levelsArr: { id: number; label: string; value: string }[] = [];
    res.forEach((levels: { id: number; name: string }) => {
      levelsArr.push({
        id: levels.id,
        label: levels.name,
        value: String(levels.id),
      });
    });
    setCategoryList(levelsArr);
  }

  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"} Tag</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-3 bg-white rounded-sm"
          >
            <FormField
              control={form.control}
              name="category"
              render={({ field }) => (
                <FormItem className="flex flex-col">
                  <FormLabel>Pilih Category</FormLabel>
                  <Popover>
                    <PopoverTrigger asChild disabled={isDetail}>
                      <FormControl>
                        <Button
                          variant="outline"
                          role="combobox"
                          className={cn(
                            "w-[400px] justify-between",
                            !field.value && "text-muted-foreground"
                          )}
                        >
                          {field.value
                            ? categoryList.find(
                                (categ) => categ.value === field.value
                              )?.label
                            : "Pilih level"}
                          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                      </FormControl>
                    </PopoverTrigger>
                    <PopoverContent className="w-[400px] p-0">
                      <Command>
                        <CommandInput />
                        <CommandList>
                          <CommandEmpty>No role found.</CommandEmpty>
                          <CommandGroup>
                            {categoryList.map((role) => (
                              <CommandItem
                                value={role.label}
                                key={role.value}
                                onSelect={() => {
                                  form.setValue("category", role.value);
                                }}
                              >
                                {role.label}
                                <Check
                                  className={cn(
                                    "ml-auto",
                                    role.value === field.value
                                      ? "opacity-100"
                                      : "opacity-0"
                                  )}
                                />
                              </CommandItem>
                            ))}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Nama Tag</FormLabel>
                  <FormControl>
                    <Input
                      readOnly={isDetail}
                      placeholder="Masukkan nama tag"
                      value={field.value}
                      onChange={field.onChange}
                    />
                  </FormControl>

                  <FormMessage />
                </FormItem>
              )}
            />

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