"use client";

import { z } from "zod";
import { Checkbox } from "@/components/ui/checkbox";
import { cn } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";

import {
  hasPermission,
  roleDefinitionsArray,
} from "@/lib/validation/permissions";
import React from "react";
import { setUserPermissions } from "@/server/actions/user";
import { toast } from "sonner";

const formSchema = z.object({
  permission: z.number().min(1),
});
const dynamicRoles = roleDefinitionsArray.filter(
  ({ role: { name } }) => name !== "User",
);

export type UserPermissionsFormProps = {
  server_permissions: number;
  userId: string;
};

function UserPermissionsForm({
  server_permissions,
  userId,
  cb,
}: UserPermissionsFormProps & {
  cb?: () => void;
}) {
  //   const userRoles = getUserPermissions(permissions);
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      permission: server_permissions,
    },
  });

  // 2. Define a submit handler.
  async function onSubmit(values: z.infer<typeof formSchema>) {
    const result = await setUserPermissions(userId, values.permission);
    if (result.success) toast.success("Benutzerrechte gespeichert");
    else toast.error("Fehler beim Speichern der Benutzerrechte");
    cb?.();
  }
  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-2">
        <FormField
          control={form.control}
          name="permission"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Benutzerrechte</FormLabel>
              <FormControl>
                <ul className="space-y-1">
                  {dynamicRoles.map(({ key, role }) => {
                    const hasRole = hasPermission(field.value, Number(key));
                    return (
                      <li
                        key={key}
                        className={cn(
                          "flex w-full items-center justify-between rounded-md bg-muted px-2 py-1",
                          Object.values(role.color).join(" "),
                        )}
                      >
                        <span>{role.name}</span>
                        <Checkbox
                          id={key}
                          checked={hasRole}
                          onCheckedChange={() => {
                            const newPermissionFlag = hasRole
                              ? field.value - Number(key)
                              : field.value + Number(key);
                            field.onChange(newPermissionFlag);
                          }}
                        />
                      </li>
                    );
                  })}
                </ul>
              </FormControl>

              <FormMessage />
            </FormItem>
          )}
        />
        {form.formState.isDirty && (
          <Button type="submit" className="w-full">
            Speichern
          </Button>
        )}
      </form>
    </Form>
  );
}

export default UserPermissionsForm;
