'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { getDeveloperUsage, type DeveloperUsage } from '@/features/developer/api.client';
import { errorText } from '@/lib/api/errors';
import { ago } from '../legacy-apps/data';
import { DevHead, KIND_LABEL } from './shared';
import './development.css';

/**
 * Development › Monitoring › API Call Usage (HUB-745, QA #729; design settings-api-call-usage.php):
 * today's calls against the account's daily limit (the account's day, reset at its midnight),
 * by app and key, and the last 7 days.
 */

const SHOWN = 5;

/** Normal, then warning from 80 %, danger from 95 % (design). */
const toneOf = (percent: number) =>
  percent >= 95 ? 'danger' : percent >= 80 ? 'warning' : 'normal';

function percentText(p: number) {
  if (p === 0) return '0%';
  if (p < 0.01) return '<0.01%';
  return `${p < 10 ? p.toFixed(2).replace(/\.?0+$/, '') : Math.round(p)}%`;
}

export function ApiUsageView() {
  const [usage, setUsage] = useState<DeveloperUsage | null>(null);
  const [loadedAt, setLoadedAt] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [expanded, setExpanded] = useState(false);
  const [, tick] = useState(0);

  const load = () =>
    getDeveloperUsage().then(
      (res) => {
        setUsage(res);
        setLoadedAt(new Date().toISOString());
        setError(null);
      },
      (err: unknown) => setError(errorText(err)),
    );

  useEffect(() => {
    void load();
    // Fresh numbers every minute; the "updated" text follows.
    const id = window.setInterval(() => {
      void load();
      tick((n) => n + 1);
    }, 60_000);
    return () => window.clearInterval(id);
  }, []);

  const head = (
    <DevHead
      title="API Call Usage"
      intro="API calls made today by apps and keys of this account, against its daily limit. The count starts again at midnight in the account's time zone."
    />
  );
  if (error && !usage) {
    return (
      <div className="dv-page">
        {head}
        <p className="sk-muted">{error}</p>
      </div>
    );
  }
  if (!usage) {
    return (
      <div className="dv-page">
        {head}
        <p className="sk-muted">Loading usage…</p>
      </div>
    );
  }

  const tone = toneOf(usage.utilizationPercent);
  const apps = usage.breakdown.builtHere.apps;
  const shownApps = expanded ? apps : apps.slice(0, SHOWN);
  const maxDay = Math.max(1, ...usage.days.map((d) => d.succeeded + d.failed));

  return (
    <div className="dv-page">
      {head}

      <section className="sk-detail-card dv-meter-card" aria-label="Today's API calls">
        <div className="dv-meter-top">
          <p className="dv-meter-count">
            <strong>{usage.totalCalls.toLocaleString()}</strong> /{' '}
            {usage.dailyLimit.toLocaleString()} calls
          </p>
          <span className={`badge ${tone === 'normal' ? '' : `badge--${tone}`}`}>
            {percentText(usage.utilizationPercent)}
          </span>
        </div>
        <div
          className={`dv-meter dv-meter--${tone}`}
          role="progressbar"
          aria-valuemin={0}
          aria-valuemax={usage.dailyLimit}
          aria-valuenow={usage.totalCalls}
          aria-label="Daily API calls used"
        >
          <span
            style={{
              width: `${Math.min(100, Math.max(usage.totalCalls ? 0.5 : 0, usage.utilizationPercent))}%`,
            }}
          />
        </div>
        <p className="dv-meter-foot">
          <svg viewBox="0 0 24 24" aria-hidden="true">
            <circle cx="12" cy="12" r="9" />
            <path d="M12 7v5l3 2" />
          </svg>
          API call counts reset at midnight (
          {new Date(usage.resetsAt).toLocaleString(undefined, {
            dateStyle: 'medium',
            timeStyle: 'short',
          })}
          ) · Last updated {ago(loadedAt, 'just now')}
        </p>
        <dl className="dv-meter-stats">
          <div>
            <dt>Errors today</dt>
            <dd>{usage.errors.toLocaleString()}</dd>
          </div>
          <div>
            <dt>Rate limited today</dt>
            <dd>{usage.rateLimited.toLocaleString()}</dd>
          </div>
          <div>
            <dt>Per app or key</dt>
            <dd>
              {usage.rateLimits.burstLimit} calls / {usage.rateLimits.burstWindowSeconds} s
            </dd>
          </div>
        </dl>
      </section>

      <div className="dv-cards">
        <section className="sk-detail-card">
          <div className="sk-detail-card-heading">
            <h2>Apps &amp; Service Keys Built Here</h2>
            <span className="sk-count">
              {usage.breakdown.builtHere.calls.toLocaleString()} calls
            </span>
          </div>
          {apps.length ? (
            <>
              <ul className="dv-app-list">
                {shownApps.map((a) => (
                  <li key={a.id}>
                    <span>
                      {a.name}
                      <small>{KIND_LABEL[a.kind]}</small>
                    </span>
                    <strong>{a.calls.toLocaleString()}</strong>
                  </li>
                ))}
              </ul>
              {apps.length > SHOWN ? (
                <button
                  type="button"
                  className="sk-text-btn"
                  onClick={() => setExpanded((v) => !v)}
                >
                  {expanded ? 'Show less' : `Show more (${apps.length - SHOWN})`}
                </button>
              ) : null}
            </>
          ) : (
            <p className="sk-muted">
              No calls today. Calls made with a <Link href="/settings/legacy-apps">legacy app</Link>{' '}
              or a <Link href="/settings/service-keys">service key</Link> count here.
            </p>
          )}
        </section>
        <section className="sk-detail-card">
          <div className="sk-detail-card-heading">
            <h2>Third Party Apps</h2>
            <span className="sk-count">
              {usage.breakdown.thirdParty.calls.toLocaleString()} calls
            </span>
          </div>
          <p className="sk-muted">
            No third-party apps call this account&apos;s API. Marketplace apps will show here when
            they can.
          </p>
        </section>
      </div>

      <section className="sk-detail-card">
        <div className="sk-detail-card-heading">
          <h2>Last 7 days</h2>
          <span className="dv-legend">
            <i className="dv-ok" /> Succeeded <i className="dv-fail" /> Failed
          </span>
        </div>
        <div className="dv-chart" role="img" aria-label="Calls per day for the last 7 days">
          {usage.days.map((d) => (
            <div
              key={d.date}
              className="dv-chart-day"
              title={`${d.date}: ${d.succeeded} succeeded, ${d.failed} failed`}
            >
              <div className="dv-chart-bar">
                <span className="dv-fail" style={{ height: `${(d.failed / maxDay) * 100}%` }} />
                <span className="dv-ok" style={{ height: `${(d.succeeded / maxDay) * 100}%` }} />
              </div>
              <small>
                {new Date(`${d.date}T12:00:00`).toLocaleDateString(undefined, { weekday: 'short' })}
              </small>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}
