"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Lock, RotateCcw, Trash2, Unlock } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  deleteUser,
  lockUser,
  resetFailedLoginAttempts,
  unlockUser,
} from "../actions";

type UserActionResult = {
  ok: boolean;
  error?: string;
};

async function runSupportAction(
  action: () => Promise<UserActionResult>,
  successMessage: string,
  router: ReturnType<typeof useRouter>,
) {
  const result = await action();
  if (!result.ok) {
    toast.error(result.error ?? "Aktion konnte nicht ausgeführt werden.");
    return;
  }
  toast.success(successMessage);
  router.refresh();
}

export function UserSupportActions({
  user,
}: {
  user: {
    id: string;
    email: string;
    name: string;
    isLocked: boolean;
    failedLoginAttempts: number;
  };
}) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  return (
    <div className="flex flex-wrap justify-end gap-1">
      {user.isLocked ? (
        <Button
          type="button"
          variant="outline"
          size="sm"
          disabled={isPending}
          onClick={() =>
            startTransition(() =>
              runSupportAction(
                () => unlockUser(user.id),
                "Benutzer wurde entsperrt.",
                router,
              ),
            )
          }
        >
          <Unlock className="h-4 w-4" />
          Entsperren
        </Button>
      ) : (
        <Button
          type="button"
          variant="outline"
          size="sm"
          disabled={isPending}
          onClick={() =>
            startTransition(() =>
              runSupportAction(
                () => lockUser(user.id),
                "Benutzer wurde gesperrt.",
                router,
              ),
            )
          }
        >
          <Lock className="h-4 w-4" />
          Sperren
        </Button>
      )}

      <Button
        type="button"
        variant="outline"
        size="sm"
        disabled={isPending || user.failedLoginAttempts === 0}
        onClick={() =>
          startTransition(() =>
            runSupportAction(
              () => resetFailedLoginAttempts(user.id),
              "Fehlversuche wurden zurückgesetzt.",
              router,
            ),
          )
        }
      >
        <RotateCcw className="h-4 w-4" />
        Reset
      </Button>

      <UserDeleteDialog user={user} />
    </div>
  );
}

function UserDeleteDialog({
  user,
}: {
  user: {
    id: string;
    email: string;
    name: string;
  };
}) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [confirmationEmail, setConfirmationEmail] = useState("");
  const [isPending, startTransition] = useTransition();

  const canSubmit = confirmationEmail === user.email && !isPending;

  function onSubmit() {
    startTransition(async () => {
      const result = await deleteUser({
        userId: user.id,
        confirmationEmail,
      });
      if (!result.ok) {
        toast.error(result.error ?? "Benutzer konnte nicht gelöscht werden.");
        return;
      }

      toast.success("Benutzer wurde gelöscht.");
      setOpen(false);
      router.refresh();
    });
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button type="button" variant="destructive" size="sm">
          <Trash2 className="h-4 w-4" />
          Löschen
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Benutzer endgültig löschen</DialogTitle>
          <DialogDescription>
            Löscht nur das Benutzerkonto von {user.name}. Familie und Kinder
            bleiben erhalten.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-2">
          <Label htmlFor={`confirm-user-${user.id}`}>
            Zur Bestätigung E-Mail-Adresse eingeben
          </Label>
          <Input
            id={`confirm-user-${user.id}`}
            value={confirmationEmail}
            onChange={(event) => setConfirmationEmail(event.target.value)}
            placeholder={user.email}
            autoComplete="off"
          />
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => setOpen(false)}
            disabled={isPending}
          >
            Abbrechen
          </Button>
          <Button
            type="button"
            variant="destructive"
            onClick={onSubmit}
            disabled={!canSubmit}
          >
            {isPending ? "Lösche..." : "Endgültig löschen"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

