import { useCallback, useMemo, useState } from 'react';
import { Table, Select, Tabs, Card, Typography } from 'antd';
import { deviceReadingApi } from '../../../api/health/deviceReadings';
import type { DeviceReading, HourlyReading } from '../../../api/health/deviceReadings';
import { usePaginatedData } from '../../../hooks/usePaginatedData';
import { DEVICE_TYPE_OPTIONS } from '../../../constants/health';

const { Text } = Typography;

/* ---------- 常量 ---------- */

const TIME_RANGE_OPTIONS = [
  { value: 1, label: '最近 1 小时' },
  { value: 6, label: '最近 6 小时' },
  { value: 24, label: '最近 24 小时' },
  { value: 168, label: '最近 7 天' },
] as const;

const DAYS_RANGE_OPTIONS = [
  { value: 1, label: '1 天' },
  { value: 3, label: '3 天' },
  { value: 7, label: '7 天' },
  { value: 30, label: '30 天' },
] as const;

const DEVICE_TYPE_MAP: Record<string, string> = Object.fromEntries(
  DEVICE_TYPE_OPTIONS.map((o) => [o.value, o.label]),
);

const PAGE_SIZE = 10;

/* ---------- Props ---------- */

interface Props {
  patientId: string;
}

/* ---------- 原始数据 Tab ---------- */

function RawDataTab({ patientId }: Props) {
  const [deviceType, setDeviceType] = useState<string | undefined>(undefined);
  const [hours, setHours] = useState<number>(24);

  const fetcher = useCallback(
    async (page: number, pageSize: number) => {
      return deviceReadingApi.query({
        patient_id: patientId,
        device_type: deviceType,
        hours,
        page,
        page_size: pageSize,
      });
    },
    [patientId, deviceType, hours],
  );

  const { data, total, page, loading, refresh } = usePaginatedData<DeviceReading>(
    fetcher,
    PAGE_SIZE,
    false,
  );

  const columns = useMemo(
    () => [
      {
        title: '测量时间',
        dataIndex: 'measured_at',
        key: 'measured_at',
        width: 180,
        render: (v: string) => v ?? '-',
      },
      {
        title: '设备类型',
        dataIndex: 'device_type',
        key: 'device_type',
        width: 100,
        render: (v: string) => DEVICE_TYPE_MAP[v] ?? v,
      },
      {
        title: '指标',
        dataIndex: 'raw_value',
        key: 'metric',
        width: 120,
        render: (v: Record<string, unknown>) => {
          const keys = Object.keys(v);
          return keys.length > 0 ? keys.join(', ') : '-';
        },
      },
      {
        title: '原始值',
        dataIndex: 'raw_value',
        key: 'raw_value',
        render: (v: Record<string, unknown>) => JSON.stringify(v),
      },
      {
        title: '设备型号',
        dataIndex: 'device_model',
        key: 'device_model',
        width: 120,
        render: (v?: string) => v ?? '-',
      },
    ],
    [],
  );

  return (
    <>
      <div style={{ display: 'flex', gap: 12, marginBottom: 12 }}>
        <Select
          placeholder="设备类型"
          allowClear
          style={{ width: 140 }}
          options={[...DEVICE_TYPE_OPTIONS]}
          value={deviceType}
          onChange={(v) => {
            setDeviceType(v);
            refresh(1);
          }}
        />
        <Select
          style={{ width: 140 }}
          options={[...TIME_RANGE_OPTIONS]}
          value={hours}
          onChange={(v) => {
            setHours(v);
            refresh(1);
          }}
        />
      </div>

      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        size="small"
        pagination={{
          current: page,
          total,
          pageSize: PAGE_SIZE,
          onChange: (p) => refresh(p),
          showTotal: (t) => `共 ${t} 条`,
          size: 'small',
        }}
      />
    </>
  );
}

/* ---------- 小时聚合 Tab ---------- */

function HourlyAggTab({ patientId }: Props) {
  const [deviceType, setDeviceType] = useState<string | undefined>(undefined);
  const [days, setDays] = useState<number>(7);

  const fetcher = useCallback(
    async (page: number, pageSize: number) => {
      if (!deviceType) {
        return { data: [] as HourlyReading[], total: 0 };
      }
      return deviceReadingApi.queryHourly({
        patient_id: patientId,
        device_type: deviceType,
        days,
        page,
        page_size: pageSize,
      });
    },
    [patientId, deviceType, days],
  );

  const { data, total, page, loading, refresh } = usePaginatedData<HourlyReading>(
    fetcher,
    PAGE_SIZE,
    false,
  );

  const columns = useMemo(
    () => [
      {
        title: '小时起始时间',
        dataIndex: 'hour_start',
        key: 'hour_start',
        width: 180,
        render: (v: string) => v ?? '-',
      },
      {
        title: '设备类型',
        dataIndex: 'device_type',
        key: 'device_type',
        width: 100,
        render: (v: string) => DEVICE_TYPE_MAP[v] ?? v,
      },
      {
        title: '最小值',
        dataIndex: 'min_val',
        key: 'min_val',
        width: 100,
        render: (v?: number) => (v != null ? v.toFixed(2) : '-'),
      },
      {
        title: '最大值',
        dataIndex: 'max_val',
        key: 'max_val',
        width: 100,
        render: (v?: number) => (v != null ? v.toFixed(2) : '-'),
      },
      {
        title: '平均值',
        dataIndex: 'avg_val',
        key: 'avg_val',
        width: 100,
        render: (v: number) => v.toFixed(2),
      },
      {
        title: '采样数',
        dataIndex: 'sample_count',
        key: 'sample_count',
        width: 80,
      },
    ],
    [],
  );

  return (
    <>
      <div style={{ display: 'flex', gap: 12, marginBottom: 12 }}>
        <Select
          placeholder="设备类型"
          allowClear
          style={{ width: 140 }}
          options={[...DEVICE_TYPE_OPTIONS]}
          value={deviceType}
          onChange={(v) => {
            setDeviceType(v);
            refresh(1);
          }}
        />
        <Select
          style={{ width: 140 }}
          options={[...DAYS_RANGE_OPTIONS]}
          value={days}
          onChange={(v) => {
            setDays(v);
            refresh(1);
          }}
        />
      </div>

      {!deviceType ? (
        <Text type="secondary">请先选择设备类型</Text>
      ) : (
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          size="small"
          pagination={{
            current: page,
            total,
            pageSize: PAGE_SIZE,
            onChange: (p) => refresh(p),
            showTotal: (t) => `共 ${t} 条`,
            size: 'small',
          }}
        />
      )}
    </>
  );
}

/* ---------- 主组件 ---------- */

export function DeviceReadingsTab({ patientId }: Props) {
  return (
    <Card size="small">
      <Tabs
        items={[
          {
            key: 'raw',
            label: '原始数据',
            children: <RawDataTab patientId={patientId} />,
          },
          {
            key: 'hourly',
            label: '小时聚合',
            children: <HourlyAggTab patientId={patientId} />,
          },
        ]}
      />
    </Card>
  );
}
