import { useState, useRef, useEffect } 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, Building2 } from 'lucide-react'

const userSchema = z.object({
  email: z.string().email('Ungültige E-Mail-Adresse'),
  role: z.enum(['admin', 'partner']),
  company_id: z.string().optional().or(z.literal('')),
})

type UserFormValues = z.infer<typeof userSchema>

interface UserDialogProps {
  companies: { id: string; name: string }[]
}

export function UserDialog({ companies }: UserDialogProps) {
  const [open, setOpen] = useState(false)
  const [dropdownOpen, setDropdownOpen] = useState(false)
  const [search, setSearch] = useState('')
  const dropdownRef = useRef<HTMLDivElement>(null)
  const router = useRouter()

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setDropdownOpen(false)
        setSearch('')
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

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

  async function onSubmit(values: UserFormValues) {
    try {
      const payload = {
        email: values.email,
        role: values.role,
        company_id: values.company_id || undefined,
      }
      await createUser(payload)
      setOpen(false)
      form.reset()
      router.refresh()
    } catch (error) {
      console.error('Error creating user:', error)
    }
  }

  return (
    <Dialog open={open} onOpenChange={(val) => {
      setOpen(val)
      if (!val) {
        form.reset()
        setDropdownOpen(false)
        setSearch('')
      }
    }}>
      <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 die Firma für den neuen Benutzer ein. Nach der Erstellung erhält der Benutzer eine E-Mail zum Festlegen seines Passworts.
          </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="company_id"
              render={({ field }) => {
                const selectedCompany = companies.find((c) => c.id === field.value)
                return (
                  <FormItem className="flex flex-col">
                    <FormLabel className="text-white">Firma (optional)</FormLabel>
                    <FormControl>
                      <div className="relative" ref={dropdownRef}>
                        <div className="flex items-center gap-2">
                          <Building2 className="w-4 h-4 text-slate-500 shrink-0" />
                          <button
                            type="button"
                            onClick={() => {
                              setDropdownOpen(!dropdownOpen)
                              setSearch('')
                            }}
                            className="w-full text-left text-sm bg-white/5 border border-white/10 rounded-md px-3 py-2 text-slate-300 hover:bg-white/10 cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 max-w-full truncate"
                          >
                            {selectedCompany ? selectedCompany.name : 'Keine Firma'}
                          </button>
                        </div>
                        {dropdownOpen && (
                          <div className="absolute z-50 mt-1 left-0 w-full bg-slate-900 border border-white/10 rounded-lg shadow-xl overflow-hidden">
                            <div className="p-2 border-b border-white/10">
                              <input
                                type="text"
                                placeholder="Firma suchen..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                className="w-full text-xs bg-white/5 border border-white/10 rounded px-2 py-1.5 text-slate-200 placeholder-slate-500 focus:outline-none focus:ring-1 focus:ring-primary/50"
                                autoFocus
                              />
                            </div>
                            <div className="max-h-40 overflow-y-auto">
                              <button
                                type="button"
                                onClick={() => {
                                  field.onChange('')
                                  setDropdownOpen(false)
                                  setSearch('')
                                }}
                                className={`w-full text-left text-xs px-3 py-2 hover:bg-white/10 transition-colors ${
                                  !field.value ? 'text-primary font-semibold' : 'text-slate-300'
                                }`}
                              >
                                Keine Firma
                              </button>
                              {companies
                                .filter((c) => c.name.toLowerCase().includes(search.toLowerCase()))
                                .map((c) => (
                                  <button
                                    key={c.id}
                                    type="button"
                                    onClick={() => {
                                      field.onChange(c.id)
                                      setDropdownOpen(false)
                                      setSearch('')
                                    }}
                                    className={`w-full text-left text-xs px-3 py-2 hover:bg-white/10 transition-colors ${
                                      field.value === c.id ? 'text-primary font-semibold' : 'text-slate-300'
                                    }`}
                                  >
                                    {c.name}
                                  </button>
                                ))}
                            </div>
                          </div>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )
              }}
            />
            <DialogFooter>
              <Button type="submit" className="w-full bg-primary hover:bg-primary/90">
                Benutzer erstellen
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
