"use client";
import { useState } from "react";
import { fetchClient } from "@/lib/api/api-client";

export default function BanUserCard() {
  const [telegramUserId, setTelegramUserId] = useState("");
  const [reason, setReason] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  async function handleBan(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setMessage(null);
    try {
      const userId = parseInt(telegramUserId);
      if (isNaN(userId)) {
        setMessage("Invalid Telegram User ID");
        return;
      }
      await fetchClient("/admin/ban", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ 
          telegramUserId: userId, 
          reason: reason || undefined 
        })
      });
      setMessage("User banned");
      setTelegramUserId("");
      setReason("");
    } catch (e: any) {
      setMessage(e?.message || "Failed to ban user");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="rounded-lg border border-border/60 bg-background p-4 h-full min-h-[200px]">
      <h2 className="font-medium">Ban User</h2>
      <p className="text-sm text-muted-foreground mt-1">Block abusive users by Telegram ID</p>
      <form onSubmit={handleBan} className="mt-4 space-y-3">
        <input
          className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
          placeholder="Telegram user ID"
          value={telegramUserId}
          onChange={(e) => setTelegramUserId(e.target.value)}
          required
        />
        <input
          className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
          placeholder="Reason (optional)"
          value={reason}
          onChange={(e) => setReason(e.target.value)}
        />
        <button
          type="submit"
          className="inline-flex items-center rounded-md bg-destructive px-3 py-2 text-sm text-destructive-foreground disabled:opacity-60"
          disabled={loading}
        >
          {loading ? "Banning..." : "Ban User"}
        </button>
        {message && <p className="text-xs text-muted-foreground">{message}</p>}
      </form>
    </div>
  );
}



