import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import _ from "lodash";
import { Check } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { rolesApi } from "~/api/roles-api.service";
import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "~/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
} from "~/components/ui/form";
import { APPROLE } from "~/types/enum";
import { roleClassMap } from "../../utils";
import Loader from "~/components/loader";
import { delay } from "~/features/delay";

const schema = z.object({
  inherits: z.array(z.string()).optional(),
});

export function RoleExtendsModal({
  children,
  init,
  onClose,
}: {
  onClose?: () => void;
  children: React.ReactNode;
  init: IRole;
}) {
  const [open, setOpen] = useState(false);

  const query = {
    filters: {
      not: {
        role_key: APPROLE.ROOT,
      },
    },
  };

  const { data } = useQuery({
    queryKey: ["roles", query],
    queryFn: async () => {
      const response = await rolesApi.index(query);
      return response.data;
    },
  });

  const form = useForm<z.infer<typeof schema>>({
    resolver: zodResolver(schema),
    defaultValues: {
      inherits: init.inherits || [],
    },
  });

  const mutation = useMutation({
    mutationFn: async (values: z.infer<typeof schema>) => {
      // Delay to smooth UI
      await delay(300);

      return rolesApi.customAction(init.id, "extends", {
        id: init.id,
        inherits: values.inherits,
      });
    },

    onSuccess: () => {
      setOpen(false);
      onClose?.();
    },
    onError: (error) => {
      console.error("Lỗi khi cập nhật quyền kế thừa:", error);
    },
  });

  const onSubmit = (values: z.infer<typeof schema>) => {
    mutation.mutate(values);
  };

  const availableRoles = (data || []).filter((r: IRole) => r.id !== init?.id);

  return (
    <Dialog
      open={open}
      onOpenChange={(value) => {
        setOpen(value);
        if (!value) {
          form.reset({});
          onClose?.();
        }
      }}
    >
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent className="sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>Cấu hình kế thừa quyền - {init.role_name}</DialogTitle>
          <DialogDescription>
            Thiết lập vai trò {init.role_name} kế thừa quyền từ các vai trò khác
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="space-y-3">
              {availableRoles.length > 0 && (
                <>
                  <h4 className="font-medium">Chọn vai trò để kế thừa:</h4>

                  <FormField
                    control={form.control}
                    name="inherits"
                    render={({ field }) => (
                      <>
                        {availableRoles.map((role: IRole) => {
                          const checked = field.value?.includes(role.role_key);

                          const toggle = () => {
                            const exists = field.value?.includes(role.role_key);
                            field.onChange(
                              exists
                                ? (field?.value || []).filter(
                                    (v) => v !== role.role_key
                                  )
                                : [...(field.value || []), role.role_key]
                            );
                          };

                          return (
                            <FormItem
                              key={role.id}
                              className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50"
                            >
                              <div className="flex items-center space-x-3">
                                <Badge className={roleClassMap[role.role_key]}>
                                  {role.role_name}
                                </Badge>
                                <div>
                                  <p className="font-medium">
                                    Kế thừa từ {role.role_name}
                                  </p>
                                  <p className="text-sm text-muted-foreground">
                                    Tự động có tất cả quyền của vai trò{" "}
                                    {role.role_name}
                                  </p>
                                </div>
                              </div>
                              <FormControl>
                                <div className="flex items-center space-x-2">
                                  <Checkbox
                                    checked={checked}
                                    onCheckedChange={toggle}
                                  />
                                  <FormLabel className="text-sm">
                                    Kế thừa
                                  </FormLabel>
                                </div>
                              </FormControl>
                            </FormItem>
                          );
                        })}
                      </>
                    )}
                  />
                </>
              )}

              {availableRoles.length <= 0 && (
                <div className="flex items-center justify-center min-h-[100px]">
                  <span className="text"> Không tìm thấy vai trò phù hợp</span>
                </div>
              )}
            </div>

            <DialogFooter>
              <DialogClose asChild>
                <Button variant="outline" type="button">
                  Đóng
                </Button>
              </DialogClose>
              <Button
                disabled={
                  _.isEqual(init.inherits, form.watch("inherits")) ||
                  mutation.isPending
                }
                type="submit"
              >
                {mutation.isPending ? (
                  <Loader color="white" />
                ) : (
                  <>
                    <Check className="mr-1 w-4 h-4" />
                    Lưu cấu hình
                  </>
                )}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
