import type { Dispatch, SetStateAction } from "react";
import {
  emptyCoachForm,
  readSportsAdminError,
  updateCoachDraft,
  type CoachFormState,
} from "@/components/sports-admin-client-config";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { BallboxStoreSportsCoach } from "@/lib/sports-backend-coaches";
import type { BallboxStoreSportsAdminData } from "@/lib/sports-backend-events";

type SportsAdminCoachesSectionProps = {
  clubs: BallboxStoreSportsAdminData["clubs"];
  coaches: BallboxStoreSportsCoach[];
  setCoaches: Dispatch<SetStateAction<BallboxStoreSportsCoach[]>>;
  busy: boolean;
  coachForm: CoachFormState;
  setCoachForm: Dispatch<SetStateAction<CoachFormState>>;
  selectClassName: string;
  runMutation: (task: () => Promise<void>, successMessage: string) => Promise<void>;
};

export function SportsAdminCoachesSection({
  clubs,
  coaches,
  setCoaches,
  busy,
  coachForm,
  setCoachForm,
  selectClassName,
  runMutation,
}: SportsAdminCoachesSectionProps) {
  return (
    <section className="rounded-3xl border border-border/70 bg-card/90 p-6">
      <p className="text-xs uppercase tracking-[0.24em] text-primary">Roster</p>
      <h3 className="mt-2 text-xl font-semibold">Coaches</h3>

      <div className="mt-5 grid gap-3 md:grid-cols-[1.1fr_1fr_auto]">
        <Input
          value={coachForm.name}
          onChange={(event) => setCoachForm((current) => ({ ...current, name: event.target.value }))}
          placeholder="Coach name"
          disabled={busy}
        />
        <select
          value={coachForm.clubId}
          onChange={(event) => setCoachForm((current) => ({ ...current, clubId: event.target.value }))}
          disabled={busy}
          className={selectClassName}
        >
          <option value="">No club</option>
          {clubs.map((club) => (
            <option key={club.id} value={club.id}>
              {club.name ?? "ATC no disponible"}
            </option>
          ))}
        </select>
        <Button
          loading={busy}
          disabled={busy || coachForm.name.trim().length === 0}
          onClick={() =>
            runMutation(async () => {
              const response = await fetch("/api/admin/sports/coaches", {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({
                  name: coachForm.name,
                  clubId: coachForm.clubId || undefined,
                }),
              });
              if (!response.ok) throw new Error(await readSportsAdminError(response));
              setCoachForm(emptyCoachForm);
            }, "Coach created")
          }
        >
          Add coach
        </Button>
      </div>

      <div className="mt-5 space-y-3">
        {coaches.map((coach) => (
          <div key={coach.id} className="rounded-2xl border border-border/70 bg-background/40 p-4">
            <div className="grid gap-3 md:grid-cols-[1.1fr_1fr_auto_auto]">
              <Input
                value={coach.name}
                onChange={(event) =>
                  setCoaches((current) => updateCoachDraft(current, coach.id, { name: event.target.value }))
                }
                disabled={busy}
              />
              <select
                value={coach.clubId ?? ""}
                onChange={(event) =>
                  setCoaches((current) =>
                    updateCoachDraft(current, coach.id, {
                      clubId: event.target.value || null,
                      clubName: clubs.find((club) => club.id === event.target.value)?.name ?? null,
                    })
                  )
                }
                disabled={busy}
                className={selectClassName}
              >
                <option value="">No club</option>
                {clubs.map((club) => (
                  <option key={club.id} value={club.id}>
                    {club.name ?? "ATC no disponible"}
                  </option>
                ))}
              </select>
              <Button
                loading={busy}
                variant="outline"
                disabled={busy}
                onClick={() =>
                  runMutation(async () => {
                    const response = await fetch(`/api/admin/sports/coaches/${coach.id}`, {
                      method: "PATCH",
                      headers: { "content-type": "application/json" },
                      body: JSON.stringify({
                        name: coach.name,
                        clubId: coach.clubId,
                      }),
                    });
                    if (!response.ok) throw new Error(await readSportsAdminError(response));
                  }, "Coach updated")
                }
              >
                Save
              </Button>
              <Button
                loading={busy}
                variant="destructive"
                disabled={busy}
                onClick={() =>
                  runMutation(async () => {
                    const response = await fetch(`/api/admin/sports/coaches/${coach.id}`, { method: "DELETE" });
                    if (!response.ok) throw new Error(await readSportsAdminError(response));
                  }, "Coach deleted")
                }
              >
                Delete
              </Button>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}
