'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 { UserX, ShieldAlert, Key, Trash2, Mail } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { deleteUser, updateUserStatus, resetPassword } from '@/lib/actions/users'
import { Badge } from '@/components/ui/badge'

export function UserList({ initialUsers }: { initialUsers: any[] }) {
  const router = useRouter()

  const handleDelete = async (id: string) => {
    if (confirm('Möchten Sie diesen Benutzer wirklich löschen?')) {
      await deleteUser(id)
      router.refresh()
    }
  }

  const handleToggleBan = async (id: string, isBanned: boolean) => {
    await updateUserStatus(id, !isBanned)
    router.refresh()
  }

  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">
          Hier können Sie Benutzer neu anlegen, sperren oder Passwörter zurücksetzen.
        </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">Status</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 isBanned = !!user.banned_until
              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>
                    <Badge variant={isBanned ? "destructive" : "default"} className={isBanned ? "" : "bg-green-500/20 text-green-500 border-green-500/30"}>
                      {isBanned ? "Gesperrt" : "Aktiv"}
                    </Badge>
                  </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={`h-8 w-8 ${isBanned ? 'text-green-500 hover:text-green-400 hover:bg-green-500/10' : 'text-orange-500 hover:text-orange-400 hover:bg-orange-500/10'}`}
                        title={isBanned ? "Entsperren" : "Sperren"}
                        onClick={() => handleToggleBan(user.id, isBanned)}
                      >
                        {isBanned ? <ShieldAlert className="h-4 w-4" /> : <UserX 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)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  )
}
