'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { createUser } from '@/lib/actions/users'
import { Plus } from 'lucide-react'

const userSchema = z.object({
  email: z.string().email('Ungültige E-Mail-Adresse'),
  password: z.string().min(6, 'Passwort muss mindestens 6 Zeichen lang sein').optional().or(z.literal('')),
  role: z.enum(['admin', 'partner']),
})

type UserFormValues = z.infer<typeof userSchema>

export function UserDialog() {
  const [open, setOpen] = useState(false)
  const router = useRouter()

  const form = useForm<UserFormValues>({
    resolver: zodResolver(userSchema) as any,
    defaultValues: {
      email: '',
      password: '',
      role: 'partner',
    },
  })

  async function onSubmit(values: UserFormValues) {
    try {
      // If password is empty string, omit it
      const payload = {
        email: values.email,
        role: values.role,
        ...(values.password ? { password: values.password } : {})
      }
      await createUser(payload)
      setOpen(false)
      form.reset()
      router.refresh()
    } catch (error) {
      console.error('Error creating user:', error)
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button className="bg-primary hover:bg-primary/90">
          <Plus className="mr-2 h-4 w-4" /> Benutzer neu anlegen
        </Button>
      </DialogTrigger>
      <DialogContent className="glass-dark border-white/10 text-white shadow-2xl">
        <DialogHeader>
          <DialogTitle>Neuen Benutzer anlegen</DialogTitle>
          <DialogDescription className="text-slate-300">
            Geben Sie die E-Mail, die Rolle und optional ein Passwort für den neuen Benutzer ein.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-white">E-Mail</FormLabel>
                  <FormControl>
                    <Input placeholder="user@example.com" className="bg-white/5 border-white/10 text-white" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="role"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-white">Rolle</FormLabel>
                  <FormControl>
                    <select
                      className="flex h-10 w-full rounded-md border border-white/10 bg-slate-950/80 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
                      {...field}
                    >
                      <option value="partner">Partner</option>
                      <option value="admin">Admin</option>
                    </select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-white">Passwort (optional)</FormLabel>
                  <FormControl>
                    <Input type="password" placeholder="Passwort leer lassen für Zufall" className="bg-white/5 border-white/10 text-white" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <DialogFooter>
              <Button type="submit" className="w-full bg-primary hover:bg-primary/90">
                Benutzer erstellen
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
