/**
 * KRA - 服务器状态页面
 * 对应 GVA: view/system/state.vue
 */
import React, { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Row, Col, Progress, Spin } from 'antd';
import { getServerInfo } from '@/services/kratos/system';

interface DiskInfo {
  mountPoint: string;
  totalMb: number;
  usedMb: number;
  totalGb: number;
  usedGb: number;
  usedPercent: number;
}

interface ServerState {
  os?: {
    goos: string;
    numCpu: number;
    compiler: string;
    goVersion: string;
    numGoroutine: number;
  };
  cpu?: {
    cores: number;
    cpus: number[];
  };
  ram?: {
    totalMb: number;
    usedMb: number;
    usedPercent: number;
  };
  disk?: DiskInfo[];
}

const getProgressColor = (percent: number) => {
  if (percent < 20) return '#5cb87a';
  if (percent < 40) return '#e6a23c';
  return '#f56c6c';
};

const State: React.FC = () => {
  const [state, setState] = useState<ServerState>({});
  const [loading, setLoading] = useState(true);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  const reload = async () => {
    try {
      const res = await getServerInfo();
      if (res.code === 0) {
        setState(res.data?.server || res.data || {});
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    reload();
    timerRef.current = setInterval(reload, 10000); // 10秒刷新一次
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  if (loading) {
    return (
      <PageContainer>
        <div style={{ textAlign: 'center', padding: 100 }}>
          <Spin size="large" />
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      <Row gutter={[16, 16]}>
        {/* Runtime */}
        <Col xs={24} md={12}>
          {state.os && (
            <Card title="Runtime" style={{ height: 320 }}>
              <Row gutter={[8, 8]}>
                <Col span={12}>os:</Col>
                <Col span={12}>{state.os.goos}</Col>
              </Row>
              <Row gutter={[8, 8]}>
                <Col span={12}>cpu nums:</Col>
                <Col span={12}>{state.os.numCpu}</Col>
              </Row>
              <Row gutter={[8, 8]}>
                <Col span={12}>compiler:</Col>
                <Col span={12}>{state.os.compiler}</Col>
              </Row>
              <Row gutter={[8, 8]}>
                <Col span={12}>go version:</Col>
                <Col span={12}>{state.os.goVersion}</Col>
              </Row>
              <Row gutter={[8, 8]}>
                <Col span={12}>goroutine nums:</Col>
                <Col span={12}>{state.os.numGoroutine}</Col>
              </Row>
            </Card>
          )}
        </Col>

        {/* Disk */}
        <Col xs={24} md={12}>
          {state.disk && (
            <Card title="Disk" style={{ height: 320, overflow: 'auto' }}>
              {state.disk.map((item, index) => (
                <Row key={index} gutter={[8, 8]} style={{ marginBottom: 24 }}>
                  <Col span={12}>
                    <Row gutter={[8, 4]}>
                      <Col span={12}>MountPoint</Col>
                      <Col span={12}>{item.mountPoint}</Col>
                    </Row>
                    <Row gutter={[8, 4]}>
                      <Col span={12}>total (MB)</Col>
                      <Col span={12}>{item.totalMb}</Col>
                    </Row>
                    <Row gutter={[8, 4]}>
                      <Col span={12}>used (MB)</Col>
                      <Col span={12}>{item.usedMb}</Col>
                    </Row>
                    <Row gutter={[8, 4]}>
                      <Col span={12}>total (GB)</Col>
                      <Col span={12}>{item.totalGb}</Col>
                    </Row>
                    <Row gutter={[8, 4]}>
                      <Col span={12}>used (GB)</Col>
                      <Col span={12}>{item.usedGb}</Col>
                    </Row>
                  </Col>
                  <Col span={12}>
                    <Progress
                      type="dashboard"
                      percent={Math.round(item.usedPercent)}
                      strokeColor={getProgressColor(item.usedPercent)}
                    />
                  </Col>
                </Row>
              ))}
            </Card>
          )}
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* CPU */}
        <Col xs={24} md={12}>
          {state.cpu && (
            <Card title="CPU" style={{ height: 320, overflow: 'auto' }}>
              <Row gutter={[8, 8]}>
                <Col span={12}>physical number of cores:</Col>
                <Col span={12}>{state.cpu.cores}</Col>
              </Row>
              {state.cpu.cpus?.map((item, index) => (
                <Row key={index} gutter={[8, 8]}>
                  <Col span={12}>core {index}:</Col>
                  <Col span={12}>
                    <Progress
                      percent={Math.round(item)}
                      strokeColor={getProgressColor(item)}
                      size="small"
                    />
                  </Col>
                </Row>
              ))}
            </Card>
          )}
        </Col>

        {/* Ram */}
        <Col xs={24} md={12}>
          {state.ram && (
            <Card title="Ram" style={{ height: 320 }}>
              <Row gutter={[8, 8]}>
                <Col span={12}>
                  <Row gutter={[8, 4]}>
                    <Col span={12}>total (MB)</Col>
                    <Col span={12}>{state.ram.totalMb}</Col>
                  </Row>
                  <Row gutter={[8, 4]}>
                    <Col span={12}>used (MB)</Col>
                    <Col span={12}>{state.ram.usedMb}</Col>
                  </Row>
                  <Row gutter={[8, 4]}>
                    <Col span={12}>total (GB)</Col>
                    <Col span={12}>{(state.ram.totalMb / 1024).toFixed(2)}</Col>
                  </Row>
                  <Row gutter={[8, 4]}>
                    <Col span={12}>used (GB)</Col>
                    <Col span={12}>{(state.ram.usedMb / 1024).toFixed(2)}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Progress
                    type="dashboard"
                    percent={Math.round(state.ram.usedPercent)}
                    strokeColor={getProgressColor(state.ram.usedPercent)}
                  />
                </Col>
              </Row>
            </Card>
          )}
        </Col>
      </Row>
    </PageContainer>
  );
};

export default State;
