import type { Dispatch, SetStateAction } from "react";
import { emptyPlayerForm, readPlayersAdminError, type PlayerFormState } from "@/components/players-admin-client-config";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

type PlayersAdminCreatePlayerSectionProps = {
  busy: boolean;
  message: string | null;
  playerForm: PlayerFormState;
  setPlayerForm: Dispatch<SetStateAction<PlayerFormState>>;
  cardClassName: string;
  runMutation: (task: () => Promise<void>, successMessage: string) => Promise<void>;
};

export function PlayersAdminCreatePlayerSection({
  busy,
  message,
  playerForm,
  setPlayerForm,
  cardClassName,
  runMutation,
}: PlayersAdminCreatePlayerSectionProps) {
  return (
    <section className={cardClassName}>
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <p className="text-xs uppercase tracking-[0.24em] text-primary">Players ops</p>
          <h2 className="mt-2 text-2xl font-semibold">Players + memberships</h2>
          <p className="mt-3 max-w-3xl text-sm leading-6 text-muted-foreground">
            Base admin para identities compartidas. Players ya vive en Ballbox y memberships se enlazan a clubs del network core.
          </p>
        </div>
        <div className="rounded-full border border-border/70 px-4 py-2 text-sm text-foreground">ballbox postgres</div>
      </div>

      <div className="mt-6 grid gap-3 md:grid-cols-3">
        <Input
          value={playerForm.name}
          onChange={(event) => setPlayerForm((current) => ({ ...current, name: event.target.value }))}
          placeholder="Player name"
          disabled={busy}
        />
        <Input
          value={playerForm.whatsappPhone}
          onChange={(event) => setPlayerForm((current) => ({ ...current, whatsappPhone: event.target.value }))}
          placeholder="WhatsApp"
          disabled={busy}
        />
        <Input
          value={playerForm.telegramHandle}
          onChange={(event) => setPlayerForm((current) => ({ ...current, telegramHandle: event.target.value }))}
          placeholder="Telegram"
          disabled={busy}
        />
      </div>

      <div className="mt-3 flex justify-end">
        <Button
          loading={busy}
          disabled={busy || playerForm.name.trim().length === 0}
          onClick={() =>
            runMutation(async () => {
              const response = await fetch("/api/admin/players", {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({
                  name: playerForm.name,
                  whatsappPhone: playerForm.whatsappPhone || undefined,
                  telegramHandle: playerForm.telegramHandle || undefined,
                }),
              });

              if (!response.ok) {
                throw new Error(await readPlayersAdminError(response));
              }

              setPlayerForm(emptyPlayerForm);
            }, "Player created")
          }
        >
          Add player
        </Button>
      </div>

      {message ? <p className="mt-4 text-sm text-muted-foreground">{message}</p> : null}
    </section>
  );
}
