import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { Button, Card, Col, Row, Tag } from "antd";
import { getAdminSummary } from "../api/adminApi";

const GAUGE_CIRC = 2 * Math.PI * 47;

interface GaugeItem {
  key: string;
  title: string;
  detail: string;
  value: number;
}

export function AdminStats(): JSX.Element {
  const { data, isLoading, isError } = useQuery({
    queryKey: ["admin-summary"],
    queryFn: getAdminSummary
  });

  const summary = data ?? {
    users_count: 0,
    registrations_day: 0,
    admins_count: 0,
    superusers_count: 0
  };

  const stats = [
    { title: "users", value: summary.users_count },
    { title: "registrations today", value: summary.registrations_day },
    { title: "admins", value: summary.admins_count },
    { title: "superusers", value: summary.superusers_count }
  ];

  const gauges = useMemo<GaugeItem[]>(
    () => [
      {
        key: "cpu",
        title: "CPU",
        detail: `${Math.min(100, 18 + summary.admins_count * 7)}% load`,
        value: Math.min(100, 18 + summary.admins_count * 7)
      },
      {
        key: "ram",
        title: "RAM",
        detail: `${Math.min(100, 32 + summary.users_count * 3)}% used`,
        value: Math.min(100, 32 + summary.users_count * 3)
      },
      {
        key: "swap",
        title: "Swap",
        detail: `${Math.min(100, 4 + summary.registrations_day * 5)}% used`,
        value: Math.min(100, 4 + summary.registrations_day * 5)
      },
      {
        key: "disk",
        title: "Disk",
        detail: `${Math.min(100, 42 + summary.superusers_count * 8)}% used`,
        value: Math.min(100, 42 + summary.superusers_count * 8)
      }
    ],
    [summary.admins_count, summary.registrations_day, summary.superusers_count, summary.users_count]
  );

  return (
    <div className="wesp-admin-dashboard">
      {isLoading ? <p className="wesp-admin-block">Loading metrics...</p> : null}
      {isError ? <p className="wesp-admin-block">Summary unavailable, showing fallback values.</p> : null}
      <Card className="wesp-dashboard-sticky">
        <div className="wesp-admin-gauges-grid">
          {gauges.map((gauge) => {
            const strokeDashoffset = GAUGE_CIRC * (1 - gauge.value / 100);
            return (
              <div key={gauge.key} className="wesp-gauge">
                <div className="wesp-gauge-ring wesp-gauge-ring--adm">
                  <svg className="wesp-gauge-svg" viewBox="0 0 100 100" aria-hidden="true">
                    <circle className="wesp-gauge-track" cx="50" cy="50" r="47" fill="none" strokeWidth="6" />
                    <circle
                      className="wesp-gauge-fill wesp-gauge-fill--adm"
                      cx="50"
                      cy="50"
                      r="47"
                      fill="none"
                      strokeWidth="6"
                      strokeLinecap="round"
                      transform="rotate(-90 50 50)"
                      style={{ strokeDasharray: GAUGE_CIRC, strokeDashoffset }}
                    />
                  </svg>
                  <div className="wesp-gauge-center">
                    <span className="wesp-gauge-pct">{gauge.value}</span>
                    <span className="wesp-gauge-pct-suffix">%</span>
                  </div>
                </div>
                <div className="wesp-gauge-caption">
                  <b>{gauge.title}</b> <span data-gauge-detail>{gauge.detail}</span>
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      <Row gutter={[16, 16]} className="wesp-dash-service-row">
        <Col xs={24} xl={12}>
          <Card className="wesp-dash-service-card" title="WESP" extra={<span className="wesp-dash-status"><span className="wesp-status-dot wesp-status-dot--ok" />OK</span>}>
            <div className="wesp-dash-wesp-meta">
              <div className="wesp-dash-wesp-row">
                <span className="wesp-dash-wesp-label">version</span>
                <Tag className="wesp-tag wesp-tag--ok">v1.0.0</Tag>
              </div>
              <div className="wesp-dash-wesp-row">
                <span className="wesp-dash-wesp-label">users</span>
                <span className="wesp-dash-wesp-value">{summary.users_count}</span>
              </div>
              <div className="wesp-dash-wesp-row">
                <span className="wesp-dash-wesp-label">admins</span>
                <span className="wesp-dash-wesp-value">{summary.admins_count}</span>
              </div>
              <div className="wesp-dash-wesp-row">
                <span className="wesp-dash-wesp-label">superusers</span>
                <span className="wesp-dash-wesp-value">{summary.superusers_count}</span>
              </div>
            </div>
          </Card>
        </Col>
        <Col xs={24} xl={12}>
          <Card className="wesp-dash-service-card" title="Ops">
            <div className="wesp-dash-manage-list">
              <div className="wesp-dash-manage-row">
                <div className="wesp-dash-manage-info">
                  <span className="wesp-dash-manage-title">log</span>
                  <span className="wesp-dash-manage-hint">tail; activity feed</span>
                </div>
                <div className="wesp-dash-manage-actions">
                  <Button size="small" type="primary">open</Button>
                  <Button size="small">download</Button>
                </div>
              </div>
              <div className="wesp-dash-manage-row">
                <div className="wesp-dash-manage-info">
                  <span className="wesp-dash-manage-title">config</span>
                  <span className="wesp-dash-manage-hint">go to content/settings</span>
                </div>
                <div className="wesp-dash-manage-actions">
                  <Button size="small">go</Button>
                </div>
              </div>
              <div className="wesp-dash-manage-row wesp-dash-manage-row--service">
                <div className="wesp-dash-manage-info">
                  <span className="wesp-dash-manage-title">service</span>
                  <span className="wesp-dash-manage-hint">stop / restart</span>
                </div>
                <div className="wesp-dash-manage-actions">
                  <Button size="small" danger>stop</Button>
                  <Button size="small" type="primary">restart</Button>
                </div>
              </div>
            </div>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card className="wesp-traffic-card" title="nx throughput (instant)">
            <div className="wesp-traffic-two-col">
              <div className="wesp-traffic-col">
                <div className="wesp-traffic-label">tx</div>
                <div className="wesp-traffic-value"><span className="wesp-traffic-arrow">↑</span>{Math.max(1, summary.registrations_day)} mb/s</div>
              </div>
              <div className="wesp-traffic-col">
                <div className="wesp-traffic-label">rx</div>
                <div className="wesp-traffic-value"><span className="wesp-traffic-arrow">↓</span>{Math.max(2, summary.users_count)} mb/s</div>
              </div>
            </div>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card className="wesp-traffic-card" title="nx cumulative">
            <div className="wesp-traffic-two-col">
              <div className="wesp-traffic-col">
                <div className="wesp-traffic-label">bytes tx</div>
                <div className="wesp-traffic-value"><span className="wesp-traffic-icon">☁↑</span>{summary.users_count * 120} mb</div>
              </div>
              <div className="wesp-traffic-col">
                <div className="wesp-traffic-label">bytes rx</div>
                <div className="wesp-traffic-value"><span className="wesp-traffic-icon">☁↓</span>{summary.users_count * 180} mb</div>
              </div>
            </div>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} className="wesp-admin-stats-row">
        {stats.map((stat) => (
          <Col key={stat.title} xs={24} sm={12} lg={6}>
            <Card size="small" className="wesp-admin-stat-card">
              <div className="wesp-admin-stat-label">{stat.title}</div>
              <div className="wesp-admin-stat-value">{stat.value}</div>
            </Card>
          </Col>
        ))}
      </Row>
    </div>
  );
}
