import { Card, Row, Col, Statistic, Progress, Table } from 'antd';
import ReactECharts from 'echarts-for-react';
import { useMetricsStore } from '../../store/metricsStore';

function formatBytes(bytes: number): string {
  if (!bytes) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let i = 0, val = bytes;
  while (val >= 1024 && i < units.length - 1) { val /= 1024; i++; }
  return `${val.toFixed(1)} ${units[i]}`;
}

function formatSpeed(bytesPerSec: number): string {
  if (!bytesPerSec) return '0 B/s';
  const units = ['B/s', 'KB/s', 'MB/s', 'GB/s'];
  let i = 0, val = bytesPerSec;
  while (val >= 1024 && i < units.length - 1) { val /= 1024; i++; }
  return `${val.toFixed(1)} ${units[i]}`;
}

export default function DiskDetail() {
  const overview = useMetricsStore((s) => s.overview);
  const disk = overview?.disk;

  if (!disk?.partitions?.length) {
    return <Card>正在加载磁盘数据...</Card>;
  }

  const pieChartOption = {
    tooltip: { trigger: 'item' },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      label: { formatter: '{b}\n{d}%' },
      data: disk.partitions.map((p) => ({
        name: p.name,
        value: p.totalBytes,
      })),
    }],
  };

  const columns = [
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '型号', dataIndex: 'model', key: 'model' },
    { title: '总容量', dataIndex: 'totalBytes', key: 'totalBytes', render: (v: number) => formatBytes(v) },
    { title: '已用', dataIndex: 'usedBytes', key: 'usedBytes', render: (v: number) => formatBytes(v) },
    { title: '可用', dataIndex: 'availableBytes', key: 'availableBytes', render: (v: number) => formatBytes(v) },
    {
      title: '使用率', dataIndex: 'usagePercent', key: 'usagePercent',
      render: (v: number) => (
        <Progress percent={v} size="small" status={v > 90 ? 'exception' : 'normal'} />
      ),
    },
    {
      title: '读速率', dataIndex: 'readBytesPerSec', key: 'readBytesPerSec',
      render: (v: number) => formatSpeed(v),
    },
    {
      title: '写速率', dataIndex: 'writeBytesPerSec', key: 'writeBytesPerSec',
      render: (v: number) => formatSpeed(v),
    },
  ];

  return (
    <Row gutter={[16, 16]}>
      <Col span={24}>
        <Card title="磁盘容量分布">
          <ReactECharts option={pieChartOption} style={{ height: 350 }} />
        </Card>
      </Col>
      <Col span={24}>
        <Card title="磁盘分区详情">
          <Table
            dataSource={disk.partitions.map((p, i) => ({ ...p, key: i }))}
            columns={columns}
            pagination={false}
            size="small"
            scroll={{ x: 900 }}
          />
        </Card>
      </Col>
    </Row>
  );
}