import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Check } from "lucide-react";
import { Button } from "~/components/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "~/components/ui/dialog";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { rolesSchema, type RoleFormData } from "~/lib/schema/roles.schema";
import { useMutation } from "@tanstack/react-query";
import { rolesApi } from "~/api/roles-api.service";
import { useState } from "react";
import { delay } from "~/features/delay";
import { queryClient } from "~/lib/query-client";

export function RoleCreateModal({
  children,
  onSubmited,
}: {
  children: React.ReactNode;
  onSubmited?: () => void;
}) {
  const {
    reset,
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<RoleFormData>({
    resolver: zodResolver(rolesSchema.create),
  });

  const [open, setOpen] = useState(false);

  const createMutation = useMutation({
    mutationFn: async (data: Partial<IRole>) => {
      await delay(300);

      return rolesApi.create(data);
    },
    onSuccess: (data) => {
      if (data) {
        onSubmited?.();
        queryClient.invalidateQueries({ queryKey: ["roles"] });
      }

      setOpen(false);
    },
  });

  const onSubmit = (data: RoleFormData) => {
    console.log("Submit role:", data);
    createMutation.mutate(data);
  };

  return (
    <Dialog
      onOpenChange={(value) => {
        setOpen(value);

        if (!value) {
          reset({});
        }
      }}
      open={open}
    >
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <form onSubmit={handleSubmit(onSubmit)}>
          <DialogHeader>
            <DialogTitle>Tạo vai trò mới</DialogTitle>
            <DialogDescription>
              Nhập thông tin khóa và tên vai trò. Nhấn lưu để tạo.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="role_key">Key</Label>
              <Input
                placeholder="msg: manager"
                id="role_key"
                {...register("role_key")}
              />
              {errors.role_key && (
                <p className="text-sm text-red-500">
                  {errors.role_key.message}
                </p>
              )}
            </div>
            <div className="grid gap-2">
              <Label htmlFor="role_name">Name</Label>
              <Input
                placeholder="msg: Manager"
                id="role_name"
                {...register("role_name")}
              />
              {errors.role_name && (
                <p className="text-sm text-red-500">
                  {errors.role_name.message}
                </p>
              )}
            </div>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">Hủy</Button>
            </DialogClose>
            <Button type="submit">
              <Check />
              Lưu
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
