"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,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { useRouter } from "@/i18n/routing";
import { Input } from "@/components/ui/input";

import { Fragment, useEffect, useState } from "react";

import { useToast } from "@/components/ui/use-toast";
import { getCategories, getCategoriesAll } from "@/service/settings/settings";
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",
  }),
});

export default function CreateTagModal() {
  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),
  });

  const onSubmit = async (data: z.infer<typeof FormSchema>) => {
    const request = {
      tagName: data.name,
      categoryId: Number(data.category),
      isActive: true,
    };
    console.log("reqqq", request);
    // const response = await postDataFeedback(request);
    // close();
    // if (response?.error) {
    //   toast({ title: stringify(response.message), variant: "destructive" });
    //   return false;
    // }
    toast({
      title: "Succes",
      description: "Tag berhasil dibuat",
    });
    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>
        <Button color="primary" size="md">
          Tambah Tag
        </Button>
      </DialogTrigger>
      <DialogContent size="md">
        <DialogHeader>
          <DialogTitle>Tambah 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>
                      <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 placeholder="Masukkan nama tag" {...field} />
                  </FormControl>

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