"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { toast } from "@/components/ui/use-toast";
import { Input } from "./ui/input";
import { User } from "@/types/user";

const roles = [
  {
    id: "ROLE_SUPER_ADMIN",
    label: "ROLE_SUPER_ADMIN",
  },
  {
    id: "ROLE_ADMIN",
    label: "ROLE_ADMIN",
  },
  {
    id: "ROLE_SYSADMIN",
    label: "ROLE_SYSADMIN",
  },
  {
    id: "ROLE_API",
    label: "ROLE_API",
  },
  {
    id: "ROLE_ORGANISATION_ADMIN",
    label: "ROLE_ORGANISATION_ADMIN",
  },
  {
    id: "ROLE_ASSISTANT",
    label: "ROLE_ASSISTANT",
  },
  {
    id: "ROLE_USER",
    label: "ROLE_USER",
  },
] as const;

const displayFormSchema = z.object({
  fullName: z.string().trim().min(1, "Full Name is required."),
  email: z.string().trim().email("Email is required."),
  newPassword: z.string().trim().min(1, "Password is required."),
  repeatPassword: z.string().trim().min(1, "Repeat the new password."),
  roles: z.array(z.string()).refine((value) => value.some((item) => item), {
    message: "You have to select at least one role.",
  }),
});

type DisplayFormValues = z.infer<typeof displayFormSchema>;

export default function UserForm({ user }: { user?: User }) {
  const form = useForm<DisplayFormValues>({
    resolver: zodResolver(displayFormSchema),
    defaultValues: {
      fullName: user?.fullName || "",
      email: user?.email || "",
      roles: [user?.role || "ROLE_USER"],
    },
  });

  function onSubmit(data: DisplayFormValues) {
    if (data.newPassword !== data.repeatPassword) {
      toast({
        variant: "destructive",
        title: "Password doesn't match!",
      });
      return;
    }

    toast({
      title: "You submitted the following values:",
      description: (
        <pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
          <code className="text-white">{JSON.stringify(data, null, 2)}</code>
        </pre>
      ),
    });
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        <FormField
          control={form.control}
          name="fullName"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Full Name</FormLabel>
              <FormControl>
                <Input placeholder="Enter fullName..." {...field} />
              </FormControl>
              {/* <FormDescription>
                This is your public display name. It can be your real name or a
                pseudonym. You can only change this once every 30 days.
              </FormDescription> */}
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Email</FormLabel>
              <FormControl>
                <Input type="email" placeholder="Enter email..." {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="newPassword"
          render={({ field }) => (
            <FormItem>
              <FormLabel>New Password</FormLabel>
              <FormControl>
                <Input
                  type="password"
                  placeholder="Enter new password..."
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="repeatPassword"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Repeat Password</FormLabel>
              <FormControl>
                <Input
                  type="password"
                  placeholder="Repeat the new password..."
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="roles"
          render={() => (
            <FormItem>
              <div className="mb-4">
                <FormLabel className="text-base">Roles</FormLabel>
                {/* <FormDescription>
                  Select the items you want to display in the sidebar.
                </FormDescription> */}
              </div>
              {roles.map((role) => (
                <FormField
                  key={role.id}
                  control={form.control}
                  name="roles"
                  render={({ field }) => {
                    return (
                      <FormItem
                        key={role.id}
                        className="flex flex-row items-start space-x-3 space-y-0"
                      >
                        <FormControl>
                          <Checkbox
                            checked={field.value?.includes(role.id)}
                            onCheckedChange={(checked) => {
                              return checked
                                ? field.onChange([...field.value, role.id])
                                : field.onChange(
                                    field.value?.filter(
                                      (value) => value !== role.id
                                    )
                                  );
                            }}
                          />
                        </FormControl>
                        <FormLabel className="font-normal">
                          {role.label}
                        </FormLabel>
                      </FormItem>
                    );
                  }}
                />
              ))}
              <FormMessage />
            </FormItem>
          )}
        />
        <div className="flex items-center gap-4 flex-col sm:flex-row">
          <Button className="w-full" size="lg">
            Create
          </Button>
          <Button variant="secondary" className="w-full" size="lg">
            Create and add another
          </Button>
        </div>
      </form>
    </Form>
  );
}
