'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Plus } from 'lucide-react'
import { createUser } from '@/app/actions/admin'
import { toast } from 'sonner'
import { useLanguage } from '@/lib/i18n'

export function CreateUserDialog() {
  const [open, setOpen] = useState(false)
  const { t } = useLanguage()
  
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button>
          <Plus className="mr-2 h-4 w-4" /> {t('admin.users.addUser')}
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{t('admin.users.createUser')}</DialogTitle>
          <DialogDescription>
            {t('admin.users.createUserDescription')}
          </DialogDescription>
        </DialogHeader>
        <form
          action={async (formData) => {
            const result = await createUser(formData)
            if (result?.error) {
              toast.error(t('admin.users.createFailed'))
            } else {
              toast.success(t('admin.users.createSuccess'))
              setOpen(false)
            }
          }}
          className="grid gap-4 py-4"
        >
          <div className="grid gap-2">
            <label htmlFor="name">{t('admin.users.name')}</label>
            <Input id="name" name="name" required />
          </div>
          <div className="grid gap-2">
            <label htmlFor="email">{t('admin.users.email')}</label>
            <Input id="email" name="email" type="email" required />
          </div>
          <div className="grid gap-2">
            <label htmlFor="password">{t('admin.users.password')}</label>
            <Input id="password" name="password" type="password" required minLength={6} />
          </div>
          <div className="grid gap-2">
            <label htmlFor="role">{t('admin.users.role')}</label>
            <select
              id="role"
              name="role"
              className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
            >
              <option value="USER">{t('admin.users.roles.user')}</option>
              <option value="ADMIN">{t('admin.users.roles.admin')}</option>
            </select>
          </div>
          <DialogFooter>
            <Button type="submit">{t('admin.users.createUser')}</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
