'use client'

import { useState } 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 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { deleteUser, resetPassword, updateUserRole } 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 handleDelete = async (id: string) => {
    if (confirm('Möchten Sie diesen Benutzer wirklich löschen?')) {
      setLoadingId(id)
      await deleteUser(id)
      setLoadingId(null)
      router.refresh()
    }
  }

  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')
    }
  }

  return (
    <Card className="glass-dark border-white/10 shadow-2xl overflow-hidden">
      <CardHeader>
        <CardTitle>Benutzerverwaltung</CardTitle>
        <CardDescription className="text-slate-400">
          Rollen, Firmenzuweisungen, Passwörter und Benutzerkonten verwalten.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow className="border-white/10 hover:bg-white/5">
              <TableHead className="text-slate-200">E-Mail</TableHead>
              <TableHead className="text-slate-200">Rolle</TableHead>
              <TableHead className="text-slate-200">Firma</TableHead>
              <TableHead className="text-slate-200">Zuletzt angemeldet</TableHead>
              <TableHead className="text-right text-slate-200">Aktionen</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {initialUsers.map((user) => {
              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

              return (
                <TableRow key={user.id} className="border-white/5 hover:bg-white/5 transition-colors">
                  <TableCell className="font-medium text-white">
                    <div className="flex items-center gap-2">
                      <Mail className="w-4 h-4 text-slate-500" />
                      {user.email}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Badge className={ROLE_BADGE_CLASSES[role]}>
                        {ROLE_LABELS[role]}
                      </Badge>
                      {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="ml-1 text-xs bg-white/5 border border-white/10 rounded px-2 py-1 text-slate-300 hover:bg-white/10 cursor-pointer focus:outline-none focus:ring-1 focus:ring-primary/50"
                        >
                          <option value="admin">Admin</option>
                          <option value="partner">Partner</option>
                          <option value="gesperrt">Gesperrt</option>
                        </select>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <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" />
                      ) : (
                        <select
                          value={user.company_id || ''}
                          onChange={(e) => handleCompanyChange(user.id, e.target.value)}
                          className="text-xs bg-white/5 border border-white/10 rounded px-2 py-1 text-slate-300 hover:bg-white/10 cursor-pointer focus:outline-none focus:ring-1 focus:ring-primary/50 max-w-[150px]"
                        >
                          <option value="">Keine Firma</option>
                          {companies.map((c) => (
                            <option key={c.id} value={c.id}>{c.name}</option>
                          ))}
                        </select>
                      )}
                    </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>
              )
            })}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  )
}
