"use client";

import { type User } from "@/lib/api";
import { type Tenant } from "@/lib/api/tenants";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

interface UsersTabProps {
  isSuperAdmin: boolean;
  users: User[];
  tenants?: Tenant[];
  usersLoading: boolean;
  usersError: string;
  // Create dialog
  dialogOpen: boolean;
  setDialogOpen: (open: boolean) => void;
  newUsername: string;
  setNewUsername: (v: string) => void;
  newEmail: string;
  setNewEmail: (v: string) => void;
  newPassword: string;
  setNewPassword: (v: string) => void;
  newRole: string;
  setNewRole: (v: string) => void;
  createLoading: boolean;
  createError: string;
  onCreateUser: (e: React.FormEvent) => void;
  // User actions
  userActionLoading: number | null;
  onToggleActive: (u: User) => void;
  onOpenResetPassword: (userId: number) => void;
  onOpenDeleteDialog: (u: User) => void;
}

export function UsersTab({
  isSuperAdmin,
  users,
  tenants = [],
  usersLoading,
  usersError,
  dialogOpen,
  setDialogOpen,
  newUsername,
  setNewUsername,
  newEmail,
  setNewEmail,
  newPassword,
  setNewPassword,
  newRole,
  setNewRole,
  createLoading,
  createError,
  onCreateUser,
  userActionLoading,
  onToggleActive,
  onOpenResetPassword,
  onOpenDeleteDialog,
}: UsersTabProps) {
  return (
    <div className="mt-4">
      <div className="mb-4 flex items-center justify-between">
        <h2 className="text-lg font-semibold">Benutzerverwaltung</h2>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button>Benutzer anlegen</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Neuen Benutzer anlegen</DialogTitle>
              <DialogDescription>
                Erstellen Sie einen neuen Benutzer-Account.
              </DialogDescription>
            </DialogHeader>
            <form onSubmit={onCreateUser} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="new-username">Benutzername</Label>
                <Input
                  id="new-username"
                  value={newUsername}
                  onChange={(e) => setNewUsername(e.target.value)}
                  required
                  aria-label="Neuer Benutzername"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="new-email">E-Mail</Label>
                <Input
                  id="new-email"
                  type="email"
                  value={newEmail}
                  onChange={(e) => setNewEmail(e.target.value)}
                  required
                  aria-label="Neue E-Mail-Adresse"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="new-password">Passwort</Label>
                <Input
                  id="new-password"
                  type="password"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  required
                  aria-label="Neues Passwort"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="new-role">Rolle</Label>
                <Select value={newRole} onValueChange={setNewRole}>
                  <SelectTrigger id="new-role" aria-label="Rolle auswaehlen">
                    <SelectValue placeholder="Rolle waehlen" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="user">User</SelectItem>
                    <SelectItem value="auditor">Auditor</SelectItem>
                    <SelectItem value="domain_auditor">Domain Auditor</SelectItem>
                    <SelectItem value="domain_admin">Domain Admin</SelectItem>
                    {isSuperAdmin && <SelectItem value="superadmin">Superadmin</SelectItem>}
                  </SelectContent>
                </Select>
              </div>
              {createError && (
                <p className="text-sm text-destructive" role="alert">
                  {createError}
                </p>
              )}
              <DialogFooter>
                <Button type="submit" disabled={createLoading}>
                  {createLoading ? "Erstellen..." : "Erstellen"}
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      {usersLoading ? (
        <Card>
          <CardContent className="p-4 space-y-3">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-10 w-full" />
            ))}
          </CardContent>
        </Card>
      ) : usersError ? (
        <Card>
          <CardContent className="p-8 text-center text-destructive">
            {usersError}
          </CardContent>
        </Card>
      ) : users.length === 0 ? (
        <Card>
          <CardContent className="p-8 text-center text-muted-foreground">
            Keine Benutzer vorhanden.
          </CardContent>
        </Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Benutzername</TableHead>
                <TableHead>E-Mail</TableHead>
                <TableHead>Rolle</TableHead>
                {isSuperAdmin && <TableHead>Mandant</TableHead>}
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Aktionen</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {users.map((u) => (
                <TableRow key={u.id}>
                  <TableCell className="font-medium">{u.username}</TableCell>
                  <TableCell>{u.email}</TableCell>
                  <TableCell>
                    <Badge variant="secondary">{u.role}</Badge>
                  </TableCell>
                  {isSuperAdmin && (
                    <TableCell className="text-muted-foreground text-sm">
                      {u.tenant_id
                        ? (tenants.find((t) => t.id === u.tenant_id)?.name ?? `#${u.tenant_id}`)
                        : <span className="italic">–</span>}
                    </TableCell>
                  )}
                  <TableCell>
                    <Badge variant={u.active ? "default" : "destructive"}>
                      {u.active ? "Aktiv" : "Inaktiv"}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-1">
                      <Button
                        size="sm"
                        variant="outline"
                        disabled={userActionLoading === u.id}
                        onClick={() => onOpenResetPassword(u.id)}
                      >
                        Passwort
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        disabled={userActionLoading === u.id}
                        onClick={() => onToggleActive(u)}
                      >
                        {userActionLoading === u.id ? "..." : u.active ? "Sperren" : "Freischalten"}
                      </Button>
                      <Button
                        size="sm"
                        variant="destructive"
                        disabled={userActionLoading === u.id}
                        onClick={() => onOpenDeleteDialog(u)}
                      >
                        Löschen
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}
    </div>
  );
}
