import React, { useEffect, useMemo, useState } from 'react';
import ReactDOM from 'react-dom/client';
import {
  Avatar,
  Button,
  Card,
  DatePicker,
  Layout,
  Nav,
  Pagination,
  Progress,
  Select,
  SideSheet,
  Space,
  Table,
  Tag,
  TagInput,
  Typography
} from '@douyinfe/semi-ui';
import {
  IconAlarm,
  IconBarChartHStroked,
  IconBox,
  IconDownload,
  IconFilter,
  IconHelpCircle,
  IconHome,
  IconMapPin,
  IconRefresh,
  IconSearch,
  IconSetting,
  IconUser
} from '@douyinfe/semi-icons';
import '@douyinfe/semi-theme-default/scss/index.scss';
import './prototype.css';

const { Header, Sider, Content } = Layout;
const { Title, Text } = Typography;

type MileageRow = {
  key: string;
  plate: string;
  vin: string;
  protocol: 'GB32960' | 'JT808' | 'YUTONG_MQTT';
  d1: number;
  d2: number;
  d3: number;
  d4: number;
  d5: number;
  d6: number;
  d7: number;
  total: number;
};

const mileageRows: MileageRow[] = [
  { key: '1', plate: '粤A·6K21F', vin: 'LHGCM82633A004352', protocol: 'GB32960', d1: 42.6, d2: 86.4, d3: 73.2, d4: 112.8, d5: 69.3, d6: 91.7, d7: 62.8, total: 538.8 },
  { key: '2', plate: '粤A·3M82Q', vin: 'LHGCM82633A004718', protocol: 'JT808', d1: 126.3, d2: 94.8, d3: 105.4, d4: 88.7, d5: 132.6, d6: 116.9, d7: 103.2, total: 767.9 },
  { key: '3', plate: '粤A·8P16D', vin: 'LHGCM82633A004966', protocol: 'YUTONG_MQTT', d1: 38.1, d2: 44.9, d3: 0, d4: 59.4, d5: 66.8, d6: 31.2, d7: 48.6, total: 289.0 },
  { key: '4', plate: '粤A·1T53L', vin: 'LHGCM82633A005104', protocol: 'GB32960', d1: 76.8, d2: 103.7, d3: 92.5, d4: 81.4, d5: 109.2, d6: 98.6, d7: 87.1, total: 649.3 },
  { key: '5', plate: '粤A·9R20H', vin: 'LHGCM82633A005339', protocol: 'JT808', d1: 54.4, d2: 61.8, d3: 48.9, d4: 70.6, d5: 83.4, d6: 77.3, d7: 65.7, total: 462.1 },
  { key: '6', plate: '粤A·5V79C', vin: 'LHGCM82633A005581', protocol: 'GB32960', d1: 144.2, d2: 118.4, d3: 136.5, d4: 129.7, d5: 152.3, d6: 97.8, d7: 121.6, total: 900.5 },
  { key: '7', plate: '粤A·2X41N', vin: 'LHGCM82633A005846', protocol: 'YUTONG_MQTT', d1: 21.5, d2: 35.2, d3: 40.6, d4: 28.3, d5: 51.7, d6: 46.4, d7: 37.9, total: 261.6 },
  { key: '8', plate: '粤A·7B66K', vin: 'LHGCM82633A006093', protocol: 'GB32960', d1: 89.7, d2: 97.6, d3: 84.3, d4: 110.5, d5: 101.9, d6: 93.8, d7: 108.4, total: 686.2 }
];

const navigation = [
  { itemKey: 'monitor', text: '全局监控', icon: <IconHome /> },
  { itemKey: 'vehicles', text: '车辆查询', icon: <IconSearch /> },
  { itemKey: 'tracks', text: '轨迹回放', icon: <IconMapPin /> },
  { itemKey: 'history', text: '历史数据', icon: <IconBarChartHStroked /> },
  { itemKey: 'statistics', text: '里程查询', icon: <IconBarChartHStroked /> },
  { itemKey: 'alerts', text: '告警中心', icon: <IconAlarm /> },
  { itemKey: 'access', text: '接入管理', icon: <IconBox /> },
  { itemKey: 'users', text: '账号管理', icon: <IconUser /> }
];

function useMobile() {
  const [mobile, setMobile] = useState(() => window.matchMedia('(max-width: 767px)').matches);
  useEffect(() => {
    const media = window.matchMedia('(max-width: 767px)');
    const update = () => setMobile(media.matches);
    media.addEventListener('change', update);
    return () => media.removeEventListener('change', update);
  }, []);
  return mobile;
}

function Filters({ mobile, onDone }: { mobile: boolean; onDone?: () => void }) {
  return (
    <div className={mobile ? 'semi-prototype-filter-mobile' : 'semi-prototype-filter-grid'}>
      <div className="semi-prototype-field is-vehicle">
        <Text type="secondary">车辆范围</Text>
        <TagInput
          maxTagCount={mobile ? 1 : 2}
          showClear
          placeholder="车牌多选；未选择时查询全部授权车辆"
          defaultValue={['粤A·6K21F', '粤A·3M82Q']}
        />
      </div>
      <div className="semi-prototype-field">
        <Text type="secondary">开始日期</Text>
        <DatePicker type="date" defaultValue="2026-07-11" style={{ width: '100%' }} />
      </div>
      <div className="semi-prototype-field">
        <Text type="secondary">结束日期</Text>
        <DatePicker type="date" defaultValue="2026-07-17" style={{ width: '100%' }} />
      </div>
      <div className="semi-prototype-field">
        <Text type="secondary">数据源策略</Text>
        <Select
          defaultValue="all"
          style={{ width: '100%' }}
          optionList={[
            { value: 'all', label: '全部启用 · 自动择优' },
            { value: 'meter', label: '仪表盘里程优先' },
            { value: 'gps', label: 'GPS 里程优先' }
          ]}
        />
      </div>
      <Space className="semi-prototype-filter-actions" spacing={8}>
        <Button theme="solid" type="primary" icon={<IconSearch />} onClick={onDone}>查询</Button>
        <Button icon={<IconRefresh />}>重置</Button>
      </Space>
      <div className="semi-prototype-quick-ranges">
        <Text type="tertiary">快捷日期</Text>
        <Button size="small" theme="borderless">今天</Button>
        <Button size="small" theme="borderless">昨天</Button>
        <Button size="small" theme="light" type="primary">近 7 天</Button>
        <Button size="small" theme="borderless">近 30 天</Button>
      </div>
    </div>
  );
}

function StatCard({ label, value, note, tone, percent }: { label: string; value: string; note: string; tone?: string; percent?: number }) {
  return (
    <Card className={`semi-prototype-stat ${tone ? `is-${tone}` : ''}`} shadows="hover">
      <Text type="tertiary">{label}</Text>
      <strong>{value}</strong>
      <div>
        <Text type="secondary" size="small">{note}</Text>
        {percent != null ? <Progress percent={percent} showInfo={false} stroke="var(--prototype-primary)" /> : null}
      </div>
    </Card>
  );
}

function MileageMatrix({ mobile }: { mobile: boolean }) {
  const dateColumns = [
    ['d1', '7/11'], ['d2', '7/12'], ['d3', '7/13'], ['d4', '7/14'],
    ['d5', '7/15'], ['d6', '7/16'], ['d7', '7/17']
  ] as const;
  const columns = useMemo(() => [
    {
      title: '车辆',
      dataIndex: 'plate',
      fixed: 'left' as const,
      width: mobile ? 128 : 190,
      render: (_: string, row: MileageRow) => (
        <div className="semi-prototype-vehicle-cell">
          <strong>{row.plate}</strong>
          <Text type="tertiary" size="small" ellipsis={{ showTooltip: true }}>{row.vin}</Text>
        </div>
      )
    },
    ...dateColumns.map(([key, label]) => ({
      title: label,
      dataIndex: key,
      align: 'right' as const,
      width: 112,
      render: (value: number) => (
        <span className={`semi-prototype-mileage${value === 0 ? ' is-zero' : ''}`}>
          {value.toFixed(1)} <small>km</small>
        </span>
      )
    })),
    {
      title: '区间总里程',
      dataIndex: 'total',
      fixed: 'right' as const,
      align: 'right' as const,
      width: mobile ? 126 : 150,
      render: (value: number, row: MileageRow) => (
        <div className="semi-prototype-total-cell">
          <strong>{value.toFixed(1)} km</strong>
          <Tag size="small" color={row.protocol === 'JT808' ? 'cyan' : row.protocol === 'GB32960' ? 'blue' : 'violet'}>
            {row.protocol}
          </Tag>
        </div>
      )
    }
  ], [mobile]);

  return (
    <Card className="semi-prototype-results" bodyStyle={{ padding: 0 }}>
      <div className="semi-prototype-results-head">
        <div>
          <Title heading={4}>车辆每日里程</Title>
          <Text type="secondary">固定车辆与总里程列，中间日期区域横向滚动</Text>
        </div>
        <Space spacing={8}>
          <Button icon={<IconRefresh />}>{mobile ? null : '刷新'}</Button>
          <Button theme="solid" type="primary" icon={<IconDownload />}>{mobile ? '导出' : '导出 Excel'}</Button>
        </Space>
      </div>
      <Table
        className="semi-prototype-table"
        columns={columns}
        dataSource={mileageRows}
        pagination={false}
        rowKey="key"
        size="middle"
        scroll={{ x: mobile ? 1038 : 1124, y: mobile ? 440 : 430 }}
      />
      <div className="semi-prototype-results-footer">
        <Text type="tertiary">当前 8 辆 / 共 1,024 辆</Text>
        <Pagination total={1024} pageSize={20} showSizeChanger={false} size={mobile ? 'small' : 'default'} />
      </div>
    </Card>
  );
}

function MobileNavigation() {
  const items = [
    ['监控', IconHome], ['车辆', IconSearch], ['轨迹', IconMapPin], ['里程', IconBarChartHStroked], ['更多', IconSetting]
  ] as const;
  return (
    <nav className="semi-prototype-mobile-nav" aria-label="移动端主导航">
      {items.map(([label, Icon]) => (
        <button key={label} className={label === '里程' ? 'is-active' : ''} type="button">
          <Icon size="large" />
          <span>{label}</span>
        </button>
      ))}
    </nav>
  );
}

function App() {
  const mobile = useMobile();
  const [filterOpen, setFilterOpen] = useState(false);
  return (
    <Layout className="semi-prototype-shell">
      {!mobile ? (
        <Sider className="semi-prototype-sider" aria-label="主导航">
          <div className="semi-prototype-brand">
            <img src="/brand-logo.svg" alt="羚牛智能" />
            <Tag color="blue" size="small">Semi UI</Tag>
          </div>
          <Nav
            className="semi-prototype-nav"
            selectedKeys={['statistics']}
            items={navigation}
            footer={{ collapseButton: true }}
          />
          <div className="semi-prototype-sider-foot">
            <IconHelpCircle />
            <span>帮助与使用说明</span>
          </div>
        </Sider>
      ) : null}
      <Layout className="semi-prototype-main">
        <Header className="semi-prototype-header">
          <div>
            {mobile ? <img src="/brand-mark.svg" alt="" /> : null}
            <div>
              <Text type="tertiary" size="small">数据分析 / 里程</Text>
              <Title heading={3}>里程查询</Title>
            </div>
          </div>
          <Space spacing={8}>
            {mobile ? <Button icon={<IconFilter />} onClick={() => setFilterOpen(true)}>筛选</Button> : null}
            <Avatar size="small" color="blue">管</Avatar>
          </Space>
        </Header>
        <Content className="semi-prototype-content">
          <div className="semi-prototype-page-intro">
            <div>
              <Tag color="light-blue">交互原型</Tag>
              <Title heading={2}>把复杂数据变成清晰的工作台</Title>
              <Text type="secondary">
                默认近 7 天，车牌多选；未选择车辆时分页查询全部授权车辆。
              </Text>
            </div>
            <Text type="tertiary">数据更新时间 14:32:18</Text>
          </div>

          {!mobile ? <Card className="semi-prototype-filter-card"><Filters mobile={false} /></Card> : null}

          <section className="semi-prototype-stats" aria-label="统计概览">
            <StatCard label="区间总里程" value="6,842.7 km" note="较前 7 天 +8.4%" tone="primary" percent={68} />
            <StatCard label="有里程车辆" value="986 辆" note="车队覆盖率 96.3%" percent={96} />
            <StatCard label="日均里程" value="142.6 km" note="按有效车辆日计算" />
            <StatCard label="数据异常" value="12 辆" note="可下钻查看差异明细" tone="warning" />
          </section>

          <MileageMatrix mobile={mobile} />
        </Content>
      </Layout>
      {mobile ? <MobileNavigation /> : null}
      <SideSheet
        visible={filterOpen}
        placement="bottom"
        height="min(78vh, 620px)"
        title="查询条件"
        onCancel={() => setFilterOpen(false)}
        footer={<Button block theme="solid" type="primary" onClick={() => setFilterOpen(false)}>应用筛选</Button>}
        bodyStyle={{ paddingBottom: 20 }}
      >
        <Filters mobile onDone={() => setFilterOpen(false)} />
      </SideSheet>
    </Layout>
  );
}

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
