'use client'

import { useState, useRef, useEffect, Fragment } from 'react'
import { useRouter } from 'next/navigation'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Key, Trash2, Mail, Loader2, Building2, Ban, Unlock, Search } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { deleteUser, resetPassword, updateUserRole, updateUserProfile } from '@/lib/actions/users'
import { assignCompanyToUser } from '@/lib/actions/companies'
import { Badge } from '@/components/ui/badge'

type Role = 'admin' | 'partner' | 'gesperrt'

const ROLE_LABELS: Record<Role, string> = {
  admin: 'Admin',
  partner: 'Partner',
  gesperrt: 'Gesperrt',
}

const ROLE_BADGE_CLASSES: Record<Role, string> = {
  admin: 'bg-purple-500/20 text-purple-400 border border-purple-500/30',
  partner: 'bg-blue-500/20 text-blue-400 border border-blue-500/30',
  gesperrt: 'bg-red-500/20 text-red-400 border border-red-500/30',
}

interface UserListProps {
  initialUsers: any[]
  companies: { id: string; name: string }[]
}

export function UserList({ initialUsers, companies }: UserListProps) {
  const router = useRouter()
  const [loadingId, setLoadingId] = useState<string | null>(null)
  const [companyDropdownOpen, setCompanyDropdownOpen] = useState<string | null>(null)
  const [companySearch, setCompanySearch] = useState('')
  const [searchQuery, setSearchQuery] = useState('')
  const [groupByCompany, setGroupByCompany] = useState(false)
  const [hideLocked, setHideLocked] = useState(true)
  const dropdownRef = useRef<HTMLDivElement>(null)

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

  const handleDelete = async (id: string) => {
    if (confirm('Möchten Sie diesen Benutzer wirklich löschen?')) {
      setLoadingId(id)
      try {
        await deleteUser(id)
        router.refresh()
      } catch (e: any) {
        console.error('Fehler beim Löschen des Benutzers:', e)
        if (e.message?.includes('Belege')) {
          if (confirm('Löschen nicht möglich! Auf diesen User existieren bereits Belege. Möchten Sie diesen Benutzer stattdessen sperren?')) {
            await handleRoleChange(id, 'gesperrt')
          }
        } else {
          alert('Fehler beim Löschen: ' + (e.message || JSON.stringify(e)))
        }
      } finally {
        setLoadingId(null)
      }
    }
  }

  const handleRoleChange = async (id: string, newRole: Role) => {
    setLoadingId(id + '-role')
    try {
      await updateUserRole(id, newRole)
      router.refresh()
    } catch (e) {
      console.error('Fehler beim Ändern der Rolle:', e)
    } finally {
      setLoadingId(null)
    }
  }

  const handleToggleLock = async (id: string, currentRole: Role) => {
    const newRole = currentRole === 'gesperrt' ? 'partner' : 'gesperrt'
    setLoadingId(id + '-lock')
    try {
      await updateUserRole(id, newRole)
      router.refresh()
    } catch (e) {
      console.error('Fehler beim Sperren/Entsperren:', e)
    } finally {
      setLoadingId(null)
    }
  }

  const handleCompanyChange = async (userId: string, companyId: string) => {
    setLoadingId(userId + '-company')
    try {
      await assignCompanyToUser(userId, companyId === '' ? null : companyId)
      router.refresh()
    } catch (e) {
      console.error('Fehler beim Zuweisen der Firma:', e)
    } finally {
      setLoadingId(null)
    }
  }

  const handleResetPassword = async (email: string) => {
    try {
      await resetPassword(email)
      alert('Password-Reset Link generiert (siehe Mailpit/Supabase Log)')
    } catch (error) {
      alert('Fehler beim Passwort-Reset')
    }
  }

  const filteredUsers = initialUsers.filter((user) => {
    if (hideLocked && user.role === 'gesperrt') return false

    const emailMatch = user.email?.toLowerCase().includes(searchQuery.toLowerCase())
    const companyMatch = user.company_name?.toLowerCase().includes(searchQuery.toLowerCase())
    const roleMatch = user.role?.toLowerCase().includes(searchQuery.toLowerCase())
    return emailMatch || companyMatch || roleMatch
  })

  const displayUsers = groupByCompany
    ? [...filteredUsers].sort((a, b) => {
        const nameA = a.company_name || 'Keine Firma'
        const nameB = b.company_name || 'Keine Firma'
        if (!a.company_name && b.company_name) return 1
        if (a.company_name && !b.company_name) return -1
        return nameA.localeCompare(nameB)
      })
    : filteredUsers

  console.log('COMPANIES IN USERLIST:', companies)
  let lastCompanyName: string | null = null

  return (
    <Card className="bg-white dark:bg-slate-900/50 border border-slate-200 dark:border-white/10 shadow-sm overflow-visible text-slate-900 dark:text-white">
      <CardHeader>
        <CardTitle>Benutzerverwaltung</CardTitle>
        <CardDescription className="text-slate-500 dark:text-slate-400">
          Rollen, Firmenzuweisungen, Passwörter und Benutzerkonten verwalten.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
          <div className="relative w-full max-w-sm">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
            <input
              type="text"
              placeholder="Benutzer suchen (E-Mail, Firma, Rolle)..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-9 pr-4 py-2 text-sm bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-md text-slate-900 dark:text-slate-200 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 focus:ring-offset-slate-50 dark:focus:ring-offset-slate-950 transition-all"
            />
          </div>
          <div className="flex flex-wrap items-center gap-3">
            <div className="flex items-center gap-2 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-md px-3 py-2 cursor-pointer hover:bg-slate-100 dark:hover:bg-white/10 transition-colors">
              <input
                type="checkbox"
                id="hideLocked"
                checked={hideLocked}
                onChange={(e) => setHideLocked(e.target.checked)}
                className="h-4 w-4 rounded border-slate-200 dark:border-white/10 bg-white dark:bg-slate-950 text-primary focus:ring-primary focus:ring-offset-slate-50 dark:focus:ring-offset-slate-950 accent-primary cursor-pointer"
              />
              <label htmlFor="hideLocked" className="text-xs text-slate-700 dark:text-slate-300 font-medium cursor-pointer select-none">
                Gesperrte ausblenden
              </label>
            </div>
            <div className="flex items-center gap-2 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-md px-3 py-2 cursor-pointer hover:bg-slate-100 dark:hover:bg-white/10 transition-colors">
              <input
                type="checkbox"
                id="groupByCompany"
                checked={groupByCompany}
                onChange={(e) => setGroupByCompany(e.target.checked)}
                className="h-4 w-4 rounded border-slate-200 dark:border-white/10 bg-white dark:bg-slate-950 text-primary focus:ring-primary focus:ring-offset-slate-50 dark:focus:ring-offset-slate-950 accent-primary cursor-pointer"
              />
              <label htmlFor="groupByCompany" className="text-xs text-slate-700 dark:text-slate-300 font-medium cursor-pointer select-none">
                Nach Firma gruppieren
              </label>
            </div>
          </div>
        </div>
        <Table containerClassName="overflow-visible">
          <TableHeader>
            <TableRow className="border-slate-200 dark:border-white/10 hover:bg-slate-50 dark:hover:bg-white/5">
              <TableHead className="text-slate-700 dark:text-slate-200">E-Mail</TableHead>
              <TableHead className="text-slate-700 dark:text-slate-200">Rolle</TableHead>
              <TableHead className="text-slate-700 dark:text-slate-200">Firma</TableHead>
              <TableHead className="text-slate-700 dark:text-slate-200">Zuletzt angemeldet</TableHead>
              <TableHead className="text-right text-slate-700 dark:text-slate-200">Aktionen</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {displayUsers.map((user: any) => {
              const role: Role = (['admin', 'partner', 'gesperrt'].includes(user.role) ? user.role : 'partner') as Role
              const isLoadingRole = loadingId === user.id + '-role'
              const isLoadingCompany = loadingId === user.id + '-company'
              const isLoadingDelete = loadingId === user.id

              const currentCompanyName = user.company_name || 'Keine Firma'
              const showGroupHeader = groupByCompany && currentCompanyName !== lastCompanyName
              lastCompanyName = currentCompanyName

              return (
                <Fragment key={user.id}>
                  {showGroupHeader && (
                    <TableRow className="bg-slate-50 dark:bg-white/5 border-y border-slate-200 dark:border-white/10 hover:bg-slate-100 dark:hover:bg-white/5">
                      <TableCell colSpan={5} className="font-semibold text-primary py-2 px-4 text-xs tracking-wider uppercase">
                        Firma: {currentCompanyName}
                      </TableCell>
                    </TableRow>
                  )}
                  <TableRow className="border-slate-150 dark:border-white/5 hover:bg-slate-50 dark:hover:bg-white/5 transition-colors">
                    <TableCell className="font-medium text-slate-900 dark:text-white">
                      <div className="flex flex-col">
                        <div className="flex items-center gap-2">
                          <Mail className="w-4 h-4 text-slate-500" />
                          <span>{user.email}</span>
                        </div>
                        <div className="flex gap-2 mt-1 pl-6">
                          <input
                            type="text"
                            defaultValue={user.first_name || ''}
                            placeholder="Vorname"
                            onBlur={async (e) => {
                              const val = e.target.value.trim()
                              if (val !== (user.first_name || '')) {
                                try {
                                  await updateUserProfile(user.id, { first_name: val || null, last_name: user.last_name })
                                  router.refresh()
                                } catch (err) {
                                  console.error('Failed to update first name:', err)
                                }
                              }
                            }}
                            onKeyDown={async (e) => {
                              if (e.key === 'Enter') {
                                (e.target as HTMLInputElement).blur()
                              }
                            }}
                            className="bg-transparent border-b border-transparent hover:border-slate-300 dark:hover:border-white/20 focus:border-primary focus:outline-none text-xs text-slate-600 dark:text-slate-400 w-20 px-1 py-0.5 transition-all placeholder:text-slate-500 placeholder:italic"
                          />
                          <input
                            type="text"
                            defaultValue={user.last_name || ''}
                            placeholder="Nachname"
                            onBlur={async (e) => {
                              const val = e.target.value.trim()
                              if (val !== (user.last_name || '')) {
                                try {
                                  await updateUserProfile(user.id, { first_name: user.first_name, last_name: val || null })
                                  router.refresh()
                                } catch (err) {
                                  console.error('Failed to update last name:', err)
                                }
                              }
                            }}
                            onKeyDown={async (e) => {
                              if (e.key === 'Enter') {
                                (e.target as HTMLInputElement).blur()
                              }
                            }}
                            className="bg-transparent border-b border-transparent hover:border-slate-300 dark:hover:border-white/20 focus:border-primary focus:outline-none text-xs text-slate-600 dark:text-slate-400 w-24 px-1 py-0.5 transition-all placeholder:text-slate-500 placeholder:italic"
                          />
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        {isLoadingRole ? (
                          <Loader2 className="h-4 w-4 animate-spin text-slate-400" />
                        ) : (
                          <select
                            value={role}
                            onChange={(e) => handleRoleChange(user.id, e.target.value as Role)}
                            className={`text-xs font-semibold rounded px-3 py-1.5 cursor-pointer focus:outline-none focus:ring-2 transition-colors bg-white dark:bg-slate-950/80 ${
                              role === 'admin'
                                ? 'text-purple-600 dark:text-purple-300 border border-purple-500/40 focus:ring-purple-500/50'
                                : role === 'gesperrt'
                                ? 'text-red-600 dark:text-red-300 border border-red-500/40 focus:ring-red-500/50'
                                : 'text-blue-600 dark:text-blue-300 border border-blue-500/40 focus:ring-blue-500/50'
                            }`}
                            style={{ appearance: 'auto' }}
                          >
                            <option value="admin" className="bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100">Admin</option>
                            <option value="partner" className="bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100">Partner</option>
                            <option value="gesperrt" className="bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100">Gesperrt</option>
                          </select>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="relative" ref={companyDropdownOpen === user.id ? dropdownRef : undefined}>
                        <div className="flex items-center gap-2">
                          <Building2 className="w-4 h-4 text-slate-500 shrink-0" />
                          {isLoadingCompany ? (
                            <Loader2 className="h-4 w-4 animate-spin text-slate-400" />
                          ) : (
                            <button
                              type="button"
                              onClick={() => {
                                setCompanyDropdownOpen(companyDropdownOpen === user.id ? null : user.id)
                                setCompanySearch('')
                              }}
                              className="text-xs bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded px-3 py-1.5 text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-white/10 cursor-pointer focus:outline-none focus:ring-1 focus:ring-primary/50 max-w-[180px] truncate text-left"
                            >
                              {user.company_name || 'Keine Firma'}
                            </button>
                          )}
                        </div>
                        {companyDropdownOpen === user.id && (
                          <div className="absolute z-50 mt-1 left-0 w-56 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={companySearch}
                                onChange={(e) => setCompanySearch(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={() => { handleCompanyChange(user.id, ''); setCompanyDropdownOpen(null); setCompanySearch(''); }}
                                className={`w-full text-left text-xs px-3 py-2 hover:bg-slate-100 dark:hover:bg-white/10 transition-colors ${
                                  !user.company_id ? 'text-primary font-semibold' : 'text-slate-700 dark:text-slate-300'
                                }`}
                              >
                                Keine Firma
                              </button>
                              {companies
                                .filter((c) => c.name.toLowerCase().includes(companySearch.toLowerCase()))
                                .map((c) => (
                                  <button
                                    key={c.id}
                                    type="button"
                                    onClick={() => { handleCompanyChange(user.id, c.id); setCompanyDropdownOpen(null); setCompanySearch(''); }}
                                    className={`w-full text-left text-xs px-3 py-2 hover:bg-slate-100 dark:hover:bg-white/10 transition-colors ${
                                      user.company_id === c.id ? 'text-primary font-semibold' : 'text-slate-700 dark:text-slate-300'
                                    }`}
                                  >
                                    {c.name}
                                  </button>
                                ))}
                            </div>
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="text-slate-400 text-sm">
                      {user.last_sign_in_at ? new Date(user.last_sign_in_at).toLocaleString('de-DE') : 'Noch nie'}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                         <Button
                           variant="ghost"
                           size="icon"
                           className="h-8 w-8 text-yellow-500 hover:text-yellow-400 hover:bg-yellow-500/10"
                           title="Passwort zurücksetzen"
                           onClick={() => handleResetPassword(user.email)}
                         >
                           <Key className="h-4 w-4" />
                         </Button>
                         <Button
                           variant="ghost"
                           size="icon"
                           className={role === 'gesperrt' ? 'h-8 w-8 text-green-500 hover:text-green-400 hover:bg-green-500/10' : 'h-8 w-8 text-red-500 hover:text-red-400 hover:bg-red-500/10'}
                           title={role === 'gesperrt' ? 'Entsperren' : 'Sperren'}
                           onClick={() => handleToggleLock(user.id, role)}
                           disabled={loadingId === user.id + '-lock'}
                         >
                           {loadingId === user.id + '-lock' ? <Loader2 className="h-4 w-4 animate-spin" /> : role === 'gesperrt' ? <Unlock className="h-4 w-4" /> : <Ban className="h-4 w-4" />}
                         </Button>
                         <Button
                           variant="ghost"
                           size="icon"
                           className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
                           title="Löschen"
                           onClick={() => handleDelete(user.id)}
                           disabled={isLoadingDelete}
                         >
                           {isLoadingDelete ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
                         </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                </Fragment>
              )
            })}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  )
}
