import { createClient } from "@/lib/supabase/server";
import { createPlayer, togglePlayerStatus } from "@/actions/players";
import { GlassCard } from "@/components/ui/glass-card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export default async function PlayersPage() {
  const supabase = await createClient();
  const { data: players } = await supabase
    .from("players")
    .select("*")
    .order("display_name");

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Player registry</h1>
        <p className="text-sm text-[var(--color-muted)]">
          Load players before roster adds or transfers
        </p>
      </div>

      <GlassCard title="Add player">
        <form action={createPlayer} className="flex flex-wrap items-end gap-4">
          <div>
            <Label htmlFor="display_name">Name</Label>
            <Input id="display_name" name="display_name" required className="mt-1" />
          </div>
          <div>
            <Label htmlFor="external_id">External ID</Label>
            <Input id="external_id" name="external_id" className="mt-1" />
          </div>
          <Button type="submit">Add player</Button>
        </form>
      </GlassCard>

      <GlassCard title="All players">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-white/10 text-left text-[var(--color-muted)]">
                <th className="pb-3 pr-4">Name</th>
                <th className="pb-3 pr-4">External ID</th>
                <th className="pb-3 pr-4">Status</th>
                <th className="pb-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {players?.map((p) => (
                <tr key={p.id} className="border-b border-white/5">
                  <td className="py-3 pr-4 font-medium">{p.display_name}</td>
                  <td className="py-3 pr-4 text-[var(--color-muted)]">
                    {p.external_id || "—"}
                  </td>
                  <td className="py-3 pr-4">
                    <span
                      className={
                        p.status === "active"
                          ? "text-emerald-400"
                          : "text-[var(--color-muted)]"
                      }
                    >
                      {p.status}
                    </span>
                  </td>
                  <td className="py-3">
                    <form action={togglePlayerStatus.bind(null, p.id, p.status)}>
                      <Button type="submit" variant="ghost" size="sm">
                        Toggle status
                      </Button>
                    </form>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </GlassCard>
    </div>
  );
}
