import { useState } from "react";
import { Button, Dialog, Input, Select, useNavigate } from "@tailor-platform/app-shell";
import { useMutation, useQuery } from "urql";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { graphql } from "@/graphql";
import { useToast } from "@/hooks/use-toast";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";

const RolesForSelectQuery = graphql(`
  query RolesForSelect {
    roles {
      edges {
        node {
          id
          name
        }
      }
    }
  }
`);

const CreateUserMutation = graphql(`
  mutation CreateUser($name: String!, $email: String!, $roleIds: [String!]) {
    createUser(name: $name, email: $email, roleIds: $roleIds) {
      id
      name
      email
      status
      initialPassword
    }
  }
`);

const formSchema = z.object({
  name: z.string().min(1, "Name is required"),
  email: z.email("Invalid email address"),
  roleIds: z.array(z.string()),
});

type FormValues = z.infer<typeof formSchema>;

export const CreateUserForm = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const [, createUser] = useMutation(CreateUserMutation);
  const [{ data: rolesData }] = useQuery({ query: RolesForSelectQuery });
  const [initialPassword, setInitialPassword] = useState<string | null>(null);

  const roles = rolesData?.roles.edges.map((edge) => edge.node) ?? [];

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      email: "",
      roleIds: [],
    },
  });

  const onSubmit = (values: FormValues) => {
    void createUser(values, { additionalTypenames: ["User"] }).then((result) => {
      if (result.error) {
        toast.error(result.error);
        return;
      }
      setInitialPassword(result.data?.createUser.initialPassword ?? null);
    });
  };

  const onCancel = () => {
    void navigate("..");
  };

  return (
    <>
      <Form {...form}>
        <form onSubmit={(e) => void form.handleSubmit(onSubmit)(e)} className="max-w-md space-y-4">
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Name</FormLabel>
                <FormControl>
                  <Input placeholder="Enter name" {...field} />
                </FormControl>
                <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="roleIds"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Roles</FormLabel>
                <FormControl>
                  <Select
                    multiple
                    items={roles}
                    value={roles.filter((r) => field.value.includes(r.id))}
                    onValueChange={(selected) => field.onChange(selected.map((r) => r.id))}
                    mapItem={(role) => ({ label: role.name, key: role.id })}
                    placeholder="Select roles"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <div className="flex gap-2">
            <Button type="submit">Create</Button>
            <Button type="button" variant="outline" onClick={onCancel}>
              Cancel
            </Button>
          </div>
        </form>
      </Form>
      <Dialog.Root
        open={initialPassword !== null}
        onOpenChange={(open) => {
          if (!open) {
            setInitialPassword(null);
            void navigate("..");
          }
        }}
      >
        <Dialog.Content>
          <Dialog.Header>
            <Dialog.Title>User Created</Dialog.Title>
            <Dialog.Description>
              The user has been created. Please copy the initial password and share it with the
              user. This password will not be shown again.
            </Dialog.Description>
          </Dialog.Header>
          <div className="py-4">
            <Input readOnly value={initialPassword ?? ""} />
          </div>
          <Dialog.Footer>
            <Button
              onClick={() => {
                setInitialPassword(null);
                void navigate("..");
              }}
            >
              Done
            </Button>
          </Dialog.Footer>
        </Dialog.Content>
      </Dialog.Root>
    </>
  );
};
