"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { ConfirmDialogTrigger } from "@/components/admin/ConfirmDialog";
import { toast } from "@/components/admin/Toast";
import { apiDelete, apiPost } from "@/lib/client-api";

export function UserControls({
  userId,
  email,
  status,
}: {
  userId: string;
  email: string;
  status: string;
}) {
  const router = useRouter();
  const [pending, setPending] = useState(false);

  const refresh = async () => router.refresh();

  const action = async (
    url: string,
    method: "post" | "delete",
    msg: string,
  ) => {
    try {
      setPending(true);
      if (method === "post") await apiPost(url);
      else await apiDelete(url);
      toast(msg, "success");
      await refresh();
    } catch (err) {
      toast(err instanceof Error ? err.message : "Action failed.", "error");
    } finally {
      setPending(false);
    }
  };

  return (
    <section className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
      <h2 className="text-sm font-semibold text-foreground">Account controls</h2>
      <p className="mt-1 text-xs text-muted">
        Destructive actions cannot be undone without an explicit confirmation.
      </p>

      <div className="mt-4 flex flex-wrap gap-2">
        {status === "active" ? (
          <ConfirmDialogTrigger
            title="Suspend user?"
            description={`${email} will not be able to sign in. Their subscription will be paused.`}
            confirmLabel="Suspend"
            tone="danger"
            onConfirm={() =>
              action(
                `/api/admin/users/${userId}/suspend`,
                "post",
                "User suspended.",
              )
            }
            trigger={(open) => (
              <Button
                variant="secondary"
                size="sm"
                onClick={open}
                disabled={pending}
              >
                Suspend
              </Button>
            )}
          />
        ) : null}
        {status === "suspended" || status === "deleted" ? (
          <ConfirmDialogTrigger
            title="Reactivate user?"
            description={`${email} will regain access to their account.`}
            confirmLabel="Reactivate"
            onConfirm={() =>
              action(
                `/api/admin/users/${userId}/suspend`,
                "delete",
                "User reactivated.",
              )
            }
            trigger={(open) => (
              <Button
                variant="secondary"
                size="sm"
                onClick={open}
                disabled={pending}
              >
                Reactivate
              </Button>
            )}
          />
        ) : null}
        {status !== "suspended" ? (
          <ConfirmDialogTrigger
            title="Ban user?"
            description={`${email} will be suspended and any active subscription cancelled.`}
            confirmLabel="Ban"
            tone="danger"
            onConfirm={() =>
              action(
                `/api/admin/users/${userId}/ban`,
                "post",
                "User banned.",
              )
            }
            trigger={(open) => (
              <Button
                variant="secondary"
                size="sm"
                onClick={open}
                disabled={pending}
              >
                Ban
              </Button>
           )}
          />
        ) : null}
        {status !== "deleted" ? (
          <ConfirmDialogTrigger
            title="Soft-delete user?"
            description={`${email} will be marked as deleted. Data is preserved for audit purposes.`}
            confirmLabel="Soft delete"
            tone="danger"
            onConfirm={() =>
              action(
                `/api/admin/users/${userId}/delete`,
                "post",
                "User soft-deleted.",
              )
            }
            trigger={(open) => (
              <Button
                variant="danger"
                size="sm"
                onClick={open}
                disabled={pending}
              >
                Soft delete
              </Button>
            )}
          />
        ) : null}
        <ConfirmDialogTrigger
          title="Restore deleted user?"
          description={`${email} will be restored to active state.`}
          confirmLabel="Restore"
          onConfirm={async () => {
            try {
              setPending(true);
              await apiDelete(`/api/admin/users/${userId}/suspend`);
              toast("User restored.", "success");
              await refresh();
            } catch (err) {
              toast(
                err instanceof Error ? err.message : "Restore failed.",
                "error",
              );
            } finally {
              setPending(false);
            }
          }}
          trigger={(open) => (
            <Button
              variant="secondary"
              size="sm"
              onClick={open}
              disabled={pending}
            >
              Restore
            </Button>
          )}
        />
      </div>
    </section>
  );
}