import { useEffect, useState } from "react";
import { api } from "../api.js";

interface Flag {
  key: string;
  enabled: boolean;
  rolloutPercent: number;
  descriptionSv: string | null;
}

export function FlagsPage() {
  const [flags, setFlags] = useState<Flag[]>([]);
  const [error, setError] = useState<string | null>(null);

  const load = () => {
    api<{ flags: Flag[] }>("/admin/v1/flags")
      .then((r) => setFlags(r.flags))
      .catch((e) => setError(String(e.message)));
  };
  useEffect(load, []);

  const toggle = async (flag: Flag) => {
    await api(`/admin/v1/flags/${flag.key}`, {
      method: "PUT",
      body: {
        enabled: !flag.enabled,
        rolloutPercent: flag.rolloutPercent,
        descriptionSv: flag.descriptionSv ?? undefined,
      },
    });
    load();
  };

  const setRollout = async (flag: Flag, percent: number) => {
    await api(`/admin/v1/flags/${flag.key}`, {
      method: "PUT",
      body: {
        enabled: flag.enabled,
        rolloutPercent: percent,
        descriptionSv: flag.descriptionSv ?? undefined,
      },
    });
    load();
  };

  return (
    <div>
      <h2>Feature flags</h2>
      <p className="muted">
        Launch Advanced-funktioner rullas ut gradvis härifrån (spec §1, Del 3).
      </p>
      {error && <div className="error-text">{error}</div>}
      <div className="panel">
        <table>
          <thead>
            <tr>
              <th>Flagga</th>
              <th>Beskrivning</th>
              <th>Rollout</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {flags.map((flag) => (
              <tr key={flag.key}>
                <td>
                  <code>{flag.key}</code>
                </td>
                <td>{flag.descriptionSv}</td>
                <td>
                  <select
                    value={flag.rolloutPercent}
                    onChange={(e) => void setRollout(flag, Number(e.target.value))}
                  >
                    {[0, 5, 10, 25, 50, 75, 100].map((p) => (
                      <option key={p} value={p}>
                        {p} %
                      </option>
                    ))}
                  </select>
                </td>
                <td>
                  <span className={`badge ${flag.enabled ? "ok" : ""}`}>
                    {flag.enabled ? "PÅ" : "AV"}
                  </span>
                </td>
                <td>
                  <button className="ghost" onClick={() => void toggle(flag)}>
                    {flag.enabled ? "Stäng av" : "Slå på"}
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
