"use client";

import { useState } from "react";
import { api } from "@/lib/api/client";
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 function MasterAssignPanel() {
  const [leagueId, setLeagueId] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  return (
    <GlassCard title="Assign league master">
      <p className="mb-4 text-sm text-[var(--color-muted)]">
        Grant another user master access to a league by their account email.
        Pick a league ID from the leagues page.
      </p>
      <div className="space-y-3">
        <div>
          <Label>League ID</Label>
          <Input
            value={leagueId}
            onChange={(e) => setLeagueId(e.target.value)}
            placeholder="uuid"
            className="mt-1 font-mono text-xs"
          />
        </div>
        <div>
          <Label>User email</Label>
          <Input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="mt-1"
          />
        </div>
        {message && (
          <p
            className={`text-sm ${message.startsWith("Assigned") ? "text-emerald-400" : "text-red-400"}`}
          >
            {message}
          </p>
        )}
        <Button
          disabled={loading || !leagueId || !email}
          onClick={async () => {
            setLoading(true);
            setMessage(null);
            try {
              await api.leagues.assignMaster(leagueId, email);
              setMessage("Assigned successfully");
            } catch (e) {
              setMessage(e instanceof Error ? e.message : "Failed");
            } finally {
              setLoading(false);
            }
          }}
        >
          Assign master
        </Button>
      </div>
    </GlassCard>
  );
}
