import { useEffect, useState, useRef } from 'react'
import {
  Table, Tag, Space, Card, Row, Col, Select, Input, Button,
  Statistic, Modal, Descriptions, Spin, Empty, Tooltip
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import {
  DatabaseOutlined, GlobalOutlined, CloudServerOutlined,
  AppstoreOutlined, EyeOutlined, SearchOutlined
} from '@ant-design/icons'
import axios from 'axios'
import AppLayout from '../../components/AppLayout/AppLayout'

interface CollectedData {
  id: number
  source: string
  source_id: string
  data_type: string
  name: string
  title: string | null
  description: string | null
  country: string | null
  city: string | null
  latitude: string | null
  longitude: string | null
  value: string | null
  unit: string | null
  metadata: Record<string, any> | null
  collected_at: string
  reference_date: string | null
  is_valid: number
}

interface Summary {
  total_records: number
  by_source: Record<string, Record<string, number>>
  source_totals: Array<{ source: string; count: number }>
}

function DataList() {
  const [data, setData] = useState<CollectedData[]>([])
  const [loading, setLoading] = useState(false)
  const [summary, setSummary] = useState<Summary | null>(null)
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  const [sourceFilter, setSourceFilter] = useState<string | undefined>()
  const [typeFilter, setTypeFilter] = useState<string | undefined>()
  const [countryFilter, setCountryFilter] = useState<string | undefined>()
  const [searchText, setSearchText] = useState('')
  const [sources, setSources] = useState<string[]>([])
  const [types, setTypes] = useState<string[]>([])
  const [countries, setCountries] = useState<string[]>([])
  const [detailVisible, setDetailVisible] = useState(false)
  const [detailData, setDetailData] = useState<CollectedData | null>(null)
  const [detailLoading, setDetailLoading] = useState(false)

  const fetchData = async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
      })
      if (sourceFilter) params.append('source', sourceFilter)
      if (typeFilter) params.append('data_type', typeFilter)
      if (countryFilter) params.append('country', countryFilter)
      if (searchText) params.append('search', searchText)

      const res = await axios.get(`/api/v1/collected?${params}`)
      setData(res.data.data)
      setTotal(res.data.total)
    } catch (error) {
      console.error('Failed to fetch data:', error)
    } finally {
      setLoading(false)
    }
  }

  const fetchSummary = async () => {
    try {
      const res = await axios.get('/api/v1/collected/summary')
      setSummary(res.data)
    } catch (error) {
      console.error('Failed to fetch summary:', error)
    }
  }

  const fetchFilters = async () => {
    try {
      const [sourcesRes, typesRes, countriesRes] = await Promise.all([
        axios.get('/api/v1/collected/sources'),
        axios.get('/api/v1/collected/types'),
        axios.get('/api/v1/collected/countries'),
      ])
      setSources(sourcesRes.data.sources || [])
      setTypes(typesRes.data.data_types || [])
      setCountries(countriesRes.data.countries || [])
    } catch (error) {
      console.error('Failed to fetch filters:', error)
    }
  }

  useEffect(() => {
    fetchSummary()
    fetchFilters()
  }, [])

  useEffect(() => {
    fetchData()
  }, [page, pageSize, sourceFilter, typeFilter, countryFilter])

  const handleSearch = () => {
    setPage(1)
    fetchData()
  }

  const handleViewDetail = async (id: number) => {
    setDetailVisible(true)
    setDetailLoading(true)
    try {
      const res = await axios.get(`/api/v1/collected/${id}`)
      setDetailData(res.data)
    } catch (error) {
      console.error('Failed to fetch detail:', error)
    } finally {
      setDetailLoading(false)
    }
  }

  const getSourceIcon = (source: string) => {
    const iconMap: Record<string, React.ReactNode> = {
      'top500': <CloudServerOutlined />,
      'huggingface_models': <AppstoreOutlined />,
      'huggingface_datasets': <DatabaseOutlined />,
      'huggingface_spaces': <AppstoreOutlined />,
      'telegeography_cables': <GlobalOutlined />,
      'epoch_ai_gpu': <CloudServerOutlined />,
    }
    return iconMap[source] || <DatabaseOutlined />
  }

  const getTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      'supercomputer': 'red',
      'model': 'blue',
      'dataset': 'green',
      'space': 'purple',
      'submarine_cable': 'cyan',
      'gpu_cluster': 'orange',
      'ixp': 'magenta',
      'network': 'gold',
      'facility': 'lime',
    }
    return colors[type] || 'default'
  }

  const [columnsWidth, setColumnsWidth] = useState<Record<string, number>>({
    id: 60,
    name: 300,
    source: 150,
    data_type: 100,
    country: 100,
    value: 100,
    collected_at: 160,
    action: 80,
  })

  const resizeRef = useRef<{ startX: number; startWidth: number; key: string } | null>(null)

  const handleResizeStart = (key: string) => (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    resizeRef.current = {
      startX: e.clientX,
      startWidth: columnsWidth[key],
      key,
    }
    document.addEventListener('mousemove', handleResizeMove)
    document.addEventListener('mouseup', handleResizeEnd)
  }

  const handleResizeMove = (e: MouseEvent) => {
    if (!resizeRef.current) return
    const diff = e.clientX - resizeRef.current.startX
    const newWidth = Math.max(50, resizeRef.current.startWidth + diff)
    setColumnsWidth((prev) => ({
      ...prev,
      [resizeRef.current!.key]: newWidth,
    }))
  }

  const handleResizeEnd = () => {
    resizeRef.current = null
    document.removeEventListener('mousemove', handleResizeMove)
    document.removeEventListener('mouseup', handleResizeEnd)
  }

  const columns: ColumnsType<CollectedData> = [
    {
      title: () => (
        <div style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
          <span>ID</span>
          <div
            className="resize-handle"
            onMouseDown={handleResizeStart('id')}
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      ),
      dataIndex: 'id',
      key: 'id',
      width: columnsWidth.id,
    },
    {
      title: () => (
        <div style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
          <span>名称</span>
          <div
            className="resize-handle"
            onMouseDown={handleResizeStart('name')}
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      ),
      dataIndex: 'name',
      key: 'name',
      width: columnsWidth.name,
      ellipsis: true,
      render: (name: string, record: CollectedData) => (
        <Tooltip title={name}>
          <Button type="link" onClick={() => handleViewDetail(record.id)}>
            {name}
          </Button>
        </Tooltip>
      ),
    },
    {
      title: () => (
        <div style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
          <span>数据源</span>
          <div
            className="resize-handle"
            onMouseDown={handleResizeStart('source')}
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      ),
      dataIndex: 'source',
      key: 'source',
      width: columnsWidth.source,
      render: (source: string) => (
        <Tag icon={getSourceIcon(source)}>{source}</Tag>
      ),
    },
    {
      title: () => (
        <div style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
          <span>类型</span>
          <div
            className="resize-handle"
            onMouseDown={handleResizeStart('data_type')}
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      ),
      dataIndex: 'data_type',
      key: 'data_type',
      width: columnsWidth.data_type,
      render: (type: string) => (
        <Tag color={getTypeColor(type)}>{type}</Tag>
      ),
    },
    {
      title: () => (
        <div style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
          <span>国家/地区</span>
          <div
            className="resize-handle"
            onMouseDown={handleResizeStart('country')}
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      ),
      dataIndex: 'country',
      key: 'country',
      width: columnsWidth.country,
      ellipsis: true,
    },
    {
      title: () => (
        <div style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
          <span>数值</span>
          <div
            className="resize-handle"
            onMouseDown={handleResizeStart('value')}
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      ),
      dataIndex: 'value',
      key: 'value',
      width: columnsWidth.value,
      render: (value: string | null, record: CollectedData) => (
        value ? `${value} ${record.unit || ''}` : '-'
      ),
    },
    {
      title: () => (
        <div style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
          <span>采集时间</span>
          <div
            className="resize-handle"
            onMouseDown={handleResizeStart('collected_at')}
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      ),
      dataIndex: 'collected_at',
      key: 'collected_at',
      width: columnsWidth.collected_at,
      render: (time: string) => new Date(time).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      width: columnsWidth.action,
      render: (_: unknown, record: CollectedData) => (
        <Button
          type="link"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetail(record.id)}
        >
          详情
        </Button>
      ),
    },
  ]

  return (
    <AppLayout>
      <h2>采集数据管理</h2>

      {/* Summary Cards */}
      {summary && (
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总记录数"
                value={summary.total_records}
                prefix={<DatabaseOutlined />}
              />
            </Card>
          </Col>
          {summary.source_totals.slice(0, 4).map((item) => (
            <Col span={6} key={item.source}>
              <Card>
                <Statistic
                  title={item.source}
                  value={item.count}
                  prefix={getSourceIcon(item.source)}
                />
              </Card>
            </Col>
          ))}
        </Row>
      )}

      {/* Filters */}
      <Card style={{ marginBottom: 16 }}>
        <Space wrap>
          <Select
            placeholder="数据源"
            allowClear
            style={{ width: 180 }}
            value={sourceFilter}
            onChange={(v) => { setSourceFilter(v); setPage(1); }}
            options={sources.map(s => ({ label: s, value: s }))}
          />
          <Select
            placeholder="数据类型"
            allowClear
            style={{ width: 150 }}
            value={typeFilter}
            onChange={(v) => { setTypeFilter(v); setPage(1); }}
            options={types.map(t => ({ label: t, value: t }))}
          />
          <Select
            placeholder="国家"
            allowClear
            style={{ width: 150 }}
            value={countryFilter}
            onChange={(v) => { setCountryFilter(v); setPage(1); }}
            options={countries.map(c => ({ label: c, value: c }))}
          />
          <Input
            placeholder="搜索名称"
            style={{ width: 200 }}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            onPressEnter={handleSearch}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
            搜索
          </Button>
        </Space>
      </Card>

      {/* Data Table */}
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        scroll={{ x: 'max-content' }}
        tableLayout="fixed"
        pagination={{
          current: page,
          pageSize,
          total,
          onChange: (p, ps) => { setPage(p); setPageSize(ps); },
          showSizeChanger: true,
          showTotal: (t) => `共 ${t} 条`,
        }}
      />

      {/* Detail Modal */}
      <Modal
        title="数据详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>
            关闭
          </Button>,
        ]}
        width={700}
      >
        {detailLoading ? (
          <div style={{ textAlign: 'center', padding: 40 }}>
            <Spin size="large" />
          </div>
        ) : detailData ? (
          <Descriptions column={2} bordered>
            <Descriptions.Item label="ID">{detailData.id}</Descriptions.Item>
            <Descriptions.Item label="数据源">{detailData.source}</Descriptions.Item>
            <Descriptions.Item label="数据类型">{detailData.data_type}</Descriptions.Item>
            <Descriptions.Item label="原始ID">{detailData.source_id || '-'}</Descriptions.Item>
            <Descriptions.Item label="名称" span={2}>{detailData.name}</Descriptions.Item>
            <Descriptions.Item label="标题" span={2}>{detailData.title || '-'}</Descriptions.Item>
            <Descriptions.Item label="描述" span={2}>{detailData.description || '-'}</Descriptions.Item>
            <Descriptions.Item label="国家">{detailData.country || '-'}</Descriptions.Item>
            <Descriptions.Item label="城市">{detailData.city || '-'}</Descriptions.Item>
            <Descriptions.Item label="经度">{detailData.longitude || '-'}</Descriptions.Item>
            <Descriptions.Item label="纬度">{detailData.latitude || '-'}</Descriptions.Item>
            <Descriptions.Item label="数值">{detailData.value} {detailData.unit || ''}</Descriptions.Item>
            <Descriptions.Item label="采集时间">
              {new Date(detailData.collected_at).toLocaleString('zh-CN')}
            </Descriptions.Item>
            <Descriptions.Item label="参考日期">
              {detailData.reference_date ? new Date(detailData.reference_date).toLocaleDateString('zh-CN') : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="元数据" span={2}>
              <pre style={{ margin: 0, maxHeight: 200, overflow: 'auto' }}>
                {JSON.stringify(detailData.metadata || {}, null, 2)}
              </pre>
            </Descriptions.Item>
          </Descriptions>
        ) : (
          <Empty description="暂无数据" />
        )}
      </Modal>
    </AppLayout>
  )
}

export default DataList
