'use client'

import * as React from 'react'
import { createUser } from '@admin/actions/users'
import { Button } from '@admin/components/ui/button'
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@admin/components/ui/dialog'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@admin/components/ui/form'
import { Input } from '@admin/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@admin/components/ui/select'
import { Spinner } from '@admin/components/ui/spinner'
import { UserRole } from '@admin/types/auth'
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod/v3'

const createUserSchema = z.object({
  email: z.string().trim().min(1, 'Email is required').email('Enter a valid email address'),
  name: z
    .string()
    .trim()
    .min(1, 'Name is required')
    .max(100, 'Name must be 100 characters or fewer'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
  role: z.nativeEnum(UserRole, {
    errorMap: () => ({ message: 'Role is required' })
  })
})

type CreateUserFormValues = z.infer<typeof createUserSchema>

const defaultValues: CreateUserFormValues = {
  email: '',
  name: '',
  password: '',
  role: UserRole.MEMBER
}

export function CreateUserDialog() {
  const [open, setOpen] = React.useState(false)
  const queryClient = useQueryClient()

  const form = useForm<CreateUserFormValues>({
    resolver: standardSchemaResolver(createUserSchema),
    defaultValues,
    mode: 'onChange',
    reValidateMode: 'onChange'
  })

  const mutation = useMutation({
    mutationFn: async (values: CreateUserFormValues) => {
      const result = await createUser(values)
      if (!result.success) {
        throw new Error(result.error || 'Failed to create user')
      }

      return result
    },
    onSuccess: async () => {
      toast.success('User created successfully')
      await queryClient.invalidateQueries({ queryKey: ['users'] })
      resetFormState()
      setOpen(false)
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to create this user')
    }
  })

  const isPending = mutation.isPending

  function resetFormState() {
    form.reset(defaultValues)
    mutation.reset()
  }

  function handleOpenChange(nextOpen: boolean) {
    setOpen(nextOpen)

    if (!nextOpen) {
      resetFormState()
    }
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger render={<Button />}>Create User</DialogTrigger>
      <DialogContent className="max-w-135">
        <Form {...form}>
          <form
            autoComplete="off"
            onSubmit={form.handleSubmit((values) => mutation.mutate(values))}
          >
            <DialogHeader>
              <DialogTitle>Create User</DialogTitle>
              <DialogDescription>Add a new user to the system</DialogDescription>
            </DialogHeader>

            <DialogBody>
              <div className="space-y-4">
                <FormField
                  control={form.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Email</FormLabel>
                      <FormControl>
                        <Input
                          type="email"
                          placeholder="user@example.com"
                          autoComplete="off"
                          disabled={isPending}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Name</FormLabel>
                      <FormControl>
                        <Input
                          type="text"
                          placeholder="Full name"
                          autoComplete="off"
                          disabled={isPending}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Password</FormLabel>
                      <FormControl>
                        <Input
                          type="password"
                          placeholder="Min 8 characters"
                          autoComplete="off"
                          disabled={isPending}
                          {...field}
                        />
                      </FormControl>
                      <FormDescription>
                        Use at least 8 characters for the temporary password.
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="role"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Role</FormLabel>
                      <Select
                        value={field.value}
                        onValueChange={field.onChange}
                        disabled={isPending}
                      >
                        <FormControl>
                          <SelectTrigger className="w-full">
                            <SelectValue placeholder="Select a role" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value={UserRole.ADMIN}>Admin</SelectItem>
                          <SelectItem value={UserRole.EDITOR}>Editor</SelectItem>
                          <SelectItem value={UserRole.MEMBER}>Member</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormDescription>
                        Choose the access level the new user should start with.
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </DialogBody>

            <DialogFooter showCloseButton={true}>
              <Button type="submit" disabled={isPending} aria-busy={isPending} size="lg">
                {isPending && <Spinner />}
                {isPending ? 'Creating…' : 'Create'}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
