'use client'

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 { createCompany } from '@/lib/actions/companies'
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('')),
  first_name: z.string().optional().or(z.literal('')),
  last_name: z.string().optional().or(z.literal('')),
}).refine((data) => {
  if (data.role === 'partner' && !data.company_id) {
    return false
  }
  return true
}, {
  message: 'Für Partner-Benutzer ist eine Firmenauswahl erforderlich.',
  path: ['company_id'],
})

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 [localCompanies, setLocalCompanies] = useState<{ id: string; name: string }[]>(companies)
  const [showNewCompanyInput, setShowNewCompanyInput] = useState(false)
  const [newCompanyName, setNewCompanyName] = useState('')
  const [isCreatingCompany, setIsCreatingCompany] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)
  const router = useRouter()

  useEffect(() => {
    setLocalCompanies(companies)
  }, [companies])

  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: '',
      first_name: '',
      last_name: '',
    },
  })

  async function onSubmit(values: UserFormValues) {
    try {
      const payload = {
        email: values.email,
        role: values.role,
        company_id: values.company_id || undefined,
        first_name: values.first_name || undefined,
        last_name: values.last_name || 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('')
        setShowNewCompanyInput(false)
        setNewCompanyName('')
      }
    }}>
      <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="bg-white dark:bg-slate-950 border-slate-200 dark:border-white/10 text-slate-900 dark:text-white shadow-2xl">
        <DialogHeader>
          <DialogTitle>Neuen Benutzer anlegen</DialogTitle>
          <DialogDescription className="text-slate-500 dark:text-slate-400">
            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-slate-900 dark:text-white">E-Mail</FormLabel>
                  <FormControl>
                    <Input placeholder="user@example.com" className="bg-slate-50 dark:bg-white/5 border-slate-200 dark:border-white/10 text-slate-900 dark:text-white placeholder:text-slate-500" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="first_name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-slate-900 dark:text-white">Vorname</FormLabel>
                    <FormControl>
                      <Input placeholder="Vorname" className="bg-slate-50 dark:bg-white/5 border-slate-200 dark:border-white/10 text-slate-900 dark:text-white placeholder:text-slate-500" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="last_name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-slate-900 dark:text-white">Nachname</FormLabel>
                    <FormControl>
                      <Input placeholder="Nachname" className="bg-slate-50 dark:bg-white/5 border-slate-200 dark:border-white/10 text-slate-900 dark:text-white placeholder:text-slate-500" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <FormField
              control={form.control}
              name="role"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-slate-900 dark:text-white">Rolle</FormLabel>
                  <FormControl>
                    <select
                      className="flex h-10 w-full rounded-md border border-slate-200 dark:border-white/10 bg-slate-50 dark:bg-slate-950/80 px-3 py-2 text-sm text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
                      {...field}
                    >
                      <option value="partner" className="bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100">Partner</option>
                      <option value="admin" className="bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100">Admin</option>
                    </select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="company_id"
              render={({ field }) => {
                const selectedCompany = localCompanies.find((c) => c.id === field.value)
                return (
                  <FormItem className="flex flex-col">
                    <FormLabel className="text-slate-900 dark:text-white">Firma</FormLabel>
                    <FormControl>
                      <div className="flex flex-col gap-2">
                        <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-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-md px-3 py-2 text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark: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-white dark:bg-slate-900 border border-slate-200 dark:border-white/10 rounded-lg shadow-xl overflow-hidden">
                              <div className="p-2 border-b border-slate-200 dark:border-white/10">
                                <input
                                  type="text"
                                  placeholder="Firma suchen..."
                                  value={search}
                                  onChange={(e) => setSearch(e.target.value)}
                                  className="w-full text-xs bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded px-2 py-1.5 text-slate-900 dark: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-slate-100 dark:hover:bg-white/10 transition-colors ${
                                    !field.value ? 'text-primary font-semibold' : 'text-slate-700 dark:text-slate-300'
                                  }`}
                                >
                                  Keine Firma
                                </button>
                                {localCompanies
                                  .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-slate-100 dark:hover:bg-white/10 transition-colors ${
                                        field.value === c.id ? 'text-primary font-semibold' : 'text-slate-700 dark:text-slate-300'
                                      }`}
                                    >
                                      {c.name}
                                    </button>
                                  ))}
                              </div>
                            </div>
                          )}
                        </div>

                        {showNewCompanyInput ? (
                          <div className="flex gap-2 mt-1">
                            <Input
                              placeholder="Name der neuen Firma"
                              value={newCompanyName}
                              onChange={(e) => setNewCompanyName(e.target.value)}
                              className="bg-slate-50 dark:bg-white/5 border-slate-200 dark:border-white/10 text-slate-900 dark:text-white text-xs h-8"
                            />
                            <Button
                              type="button"
                              size="sm"
                              onClick={async () => {
                                const trimmed = newCompanyName.trim()
                                if (trimmed) {
                                  setIsCreatingCompany(true)
                                  try {
                                    const created = await createCompany({ name: trimmed })
                                    if (created) {
                                      setLocalCompanies((prev) => [...prev, created])
                                      field.onChange(created.id)
                                      setShowNewCompanyInput(false)
                                      setNewCompanyName('')
                                      router.refresh()
                                    }
                                  } catch (err) {
                                    console.error('Failed to create company:', err)
                                  } finally {
                                    setIsCreatingCompany(false)
                                  }
                                }
                              }}
                              disabled={isCreatingCompany}
                              className="bg-primary text-xs h-8"
                            >
                              {isCreatingCompany ? 'Erstellt...' : 'Speichern'}
                            </Button>
                            <Button
                              type="button"
                              size="sm"
                              variant="ghost"
                              onClick={() => {
                                setShowNewCompanyInput(false)
                                setNewCompanyName('')
                              }}
                              className="text-xs h-8 text-slate-500 dark:text-slate-400"
                            >
                              Abbrechen
                            </Button>
                          </div>
                        ) : (
                          <button
                            type="button"
                            onClick={() => setShowNewCompanyInput(true)}
                            className="text-xs text-primary hover:underline mt-1 self-start font-medium"
                          >
                            + Neue Firma anlegen
                          </button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )
              }}
            />
            <DialogFooter>
              <Button type="submit" className="w-full bg-primary hover:bg-primary/90 text-white">
                Benutzer erstellen
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
