import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Card, Row, Col, Statistic, Button, Select, Tag, Spin, Alert, Modal, Form, InputNumber, Switch, Checkbox } from 'antd';
import { message } from 'antd';
import { ReloadOutlined, ArrowUpOutlined, ArrowDownOutlined, FireOutlined, AlertOutlined, RobotOutlined, BellOutlined } from '@ant-design/icons';
import { fetchFuturesOverview, fetchRiskAlerts, fetchAIMarketAnalysis, toggleWatchlist } from '../../store/futuresSlice';
import { useNavigate } from 'react-router-dom';
import './Dashboard.css';

const { Option } = Select;
const { Item } = Form;

const Dashboard = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { overview, riskAlerts, aiAnalysis, loading } = useSelector(state => state.futures);
  const [filterType, setFilterType] = useState('all');
  const [sortBy, setSortBy] = useState('winRate');
  const [pushModalVisible, setPushModalVisible] = useState(false);
  const [currentFuture, setCurrentFuture] = useState(null);
  const [pushForm] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  
  // 添加ref来避免在开发模式下的重复API请求
  const fetchingRef = React.useRef(false);

  useEffect(() => {
    if (!fetchingRef.current) {
      fetchingRef.current = true;
      dispatch(fetchFuturesOverview());
      dispatch(fetchRiskAlerts());
      dispatch(fetchAIMarketAnalysis());
    }
  }, [dispatch]);

  const handleRefresh = () => {
    fetchingRef.current = false;
    dispatch(fetchFuturesOverview());
    dispatch(fetchRiskAlerts());
    dispatch(fetchAIMarketAnalysis());
    messageApi.success('数据已刷新');
  };

  const handleFutureClick = (future) => {
    navigate(`/detail/${future.code}`);
  };

  const handleToggleWatchlist = (future, e) => {
    e.stopPropagation();
    dispatch(toggleWatchlist(future.code));
    messageApi.success(future.isInWatchlist ? '已从自选移除' : '已添加到自选');
  };

  const openPushConfig = (future, e) => {
    e.stopPropagation();
    setCurrentFuture(future);
    setPushModalVisible(true);
  };

  const savePushConfig = (values) => {
    console.log('消息推送配置保存:', values);
    // 模拟保存操作
    setPushModalVisible(false);
    messageApi.success('消息推送配置已保存');
  };

  const getChangeColor = (changePercent) => {
    return changePercent >= 0 ? '#52c41a' : '#ff4d4f';
  };

  const getChangeIcon = (changePercent) => {
    return changePercent >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />;
  };

  const getTrendColor = (direction) => {
    if (direction === '看多') return '#52c41a';
    if (direction === '看空') return '#ff4d4f';
    return '#faad14';
  };

  const getRiskLevelColor = (level) => {
    if (level === '高') return '#ff4d4f';
    if (level === '中等') return '#faad14';
    return '#52c41a';
  };

  const filteredAndSortedData = () => {
    let data = [...overview];
    
    // 筛选
    if (filterType !== 'all') {
      data = data.filter(item => {
        // 简化处理，实际应该根据品种类型映射
        return true;
      });
    }
    
    // 排序
    data.sort((a, b) => {
      if (sortBy === 'winRate') {
        return b.winRate - a.winRate;
      } else if (sortBy === 'changePercent') {
        return b.changePercent - a.changePercent;
      } else if (sortBy === 'atr') {
        return b.atr - a.atr;
      }
      return 0;
    });
    
    return data;
  };

  if (loading && overview.length === 0) {
    return (
      <div className="loading-container">
        <Spin size="large" tip="加载数据中..." />
      </div>
    );
  }

  return (
    <>
      {contextHolder}
      <div className="dashboard">
      {/* 页面头部 */}
      <div className="dashboard-header">
        <h2>市场概览</h2>
        <div className="dashboard-header-actions">
          <Select 
            defaultValue="all" 
            style={{ width: 120, marginRight: 16 }} 
            onChange={setFilterType}
          >
            <Option value="all">全部类型</Option>
            <Option value="metal">金属</Option>
            <Option value="building">建材</Option>
            <Option value="energy">能源化工</Option>
          </Select>
          <Select 
            defaultValue="winRate" 
            style={{ width: 120, marginRight: 16 }} 
            onChange={setSortBy}
          >
            <Option value="winRate">胜率</Option>
            <Option value="changePercent">涨跌幅</Option>
            <Option value="atr">波动率</Option>
          </Select>
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
          >
            刷新数据
          </Button>
        </div>
      </div>

      {/* 市场热点和风险预警 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        {/* 市场热点 */}
        <Col span={12}>
          <Card 
            title={<span><FireOutlined /> 市场热点</span>} 
            className="dashboard-card"
          >
            <div className="market-hotspots">
              {filteredAndSortedData().slice(0, 5).map((item, index) => (
                <div key={item.code} className="hotspot-item">
                  <div className="hotspot-rank">{index + 1}</div>
                  <div className="hotspot-info">
                    <div className="hotspot-name">{item.name} ({item.code})</div>
                    <div className="hotspot-change" style={{ color: getChangeColor(item.changePercent) }}>
                      {getChangeIcon(item.changePercent)} {Math.abs(item.changePercent)}%
                    </div>
                  </div>
                  <div className="hotspot-winrate">
                    <Tag color={item.winRate > 60 ? 'green' : item.winRate > 40 ? 'orange' : 'red'}>
                      胜率 {item.winRate}%
                    </Tag>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </Col>

        {/* 风险预警 */}
        <Col span={12}>
          <Card 
            title={<span><AlertOutlined /> 风险预警</span>} 
            className="dashboard-card"
          >
            <div className="risk-alerts">
              {riskAlerts.map(alert => (
                <Alert 
                  key={alert.id}
                  message={alert.title}
                  description={alert.message}
                  type={alert.level === '高' ? 'error' : alert.level === '中等' ? 'warning' : 'info'}
                  showIcon
                  style={{ marginBottom: 12 }}
                />
              ))}
            </div>
          </Card>
        </Col>
      </Row>

      {/* AI研判 */}
      <Card 
        title={<span><RobotOutlined /> AI市场研判</span>} 
        className="dashboard-card"
        style={{ marginBottom: 24 }}
      >
        <div className="ai-analysis">
          <div className="ai-overall">
            <Statistic 
              title="整体趋势" 
              value={aiAnalysis?.overallTrend || '分析中'} 
              valueStyle={{ color: '#1890ff' }}
            />
            <Statistic 
              title="置信度" 
              value={aiAnalysis?.confidence || 0} 
              suffix="%" 
              valueStyle={{ color: '#1890ff' }}
            />
          </div>
          <div className="ai-factors">
            <h4>关键因素</h4>
            <div className="factor-tags">
              {aiAnalysis?.keyFactors?.map((factor, index) => (
                <Tag key={index} color="blue">{factor}</Tag>
              ))}
            </div>
          </div>
          <div className="ai-recommendations">
            <h4>操作建议</h4>
            <ul>
              {aiAnalysis?.recommendations?.map((recommendation, index) => (
                <li key={index}>{recommendation}</li>
              ))}
            </ul>
          </div>
        </div>
      </Card>

      {/* 品种概览 */}
      <h3 className="section-title">品种概览</h3>
      <Row gutter={[16, 16]}>
        {filteredAndSortedData().map(item => (
          <Col xs={24} sm={12} md={8} lg={6} key={item.code}>
            <Card 
              className="future-card" 
              hoverable
              onClick={() => handleFutureClick(item)}
            >
              {/* 品种名称和胜率 */}
              <div className="future-header-new">
                <div className="future-name-new">
                  <h3>{item.name}-{item.code}</h3>
                </div>
                <div className="future-winrate-new">
                  胜率: {item.winRate}%
                </div>
              </div>
              
              {/* ATR/ADX和涨跌幅 */}
              <div className="future-info-new">
                <div className="future-indicators-new">
                  ATR: {item.atr} | ADX: {item.adx}
                </div>
                <div className="future-change-new" style={{ color: getChangeColor(item.changePercent) }}>
                  ● {Math.abs(item.changePercent)}%
                </div>
              </div>
              
              {/* 当前价格和支撑压力位 */}
              <div className="future-price-container-new">
                <div className="future-price-new" style={{ color: getChangeColor(item.changePercent) }}>
                  {item.currentPrice.toFixed(2)}
                </div>
                <div className="future-levels-new">
                  <span className="level-label-new">支撑: {item.tradingAdvice?.support?.toFixed(2) || '-'}</span>
                  <span className="level-label-new">压力: {item.tradingAdvice?.resistance?.toFixed(2) || '-'}</span>
                </div>
              </div>
              
              {/* 多周期趋势 */}
              <div className="future-trend-title-new">
                多周期趋势:
              </div>
              <div className="future-trends-new">
                {Object.entries(item.trends).map(([period, trend]) => (
                  <div key={period} className="trend-item-new">
                    <div className="trend-period-new">{period.replace('MIN', 'min').replace('HOUR', 'min')}</div>
                    <div className="trend-direction-new" style={{ color: getTrendColor(trend.direction) }}>
                      {trend.direction}
                    </div>
                    <div className="trend-status-new">
                      {trend.status}
                    </div>
                    <div className="trend-rsi-new">
                      RSI: {trend.rsi}
                    </div>
                  </div>
                ))}
              </div>
              
              {/* 整体预判 */}
              <div className="future-overview-new">
                <span className="overview-label-new">整体预判:</span>
                <Tag color={item.overallView === '多头排列' ? 'green' : item.overallView === '空头排列' ? 'red' : 'orange'}>
                  {item.overallView}
                </Tag>
              </div>
              
              {/* AI分析 */}
              <div className="future-ai-analysis-new">
                <h4 className="ai-title-new">AI分析:</h4>
                <div className="ai-content-new">
                  {item.aiAnalysis?.split(' | ').map((item, index) => (
                    <div key={index}>{item}</div>
                  ))}
                </div>
              </div>
              
              {/* 操作按钮 */}
              <div className="future-actions-new">
                <Button type="primary" className="detail-button-new" onClick={() => handleFutureClick(item)}>
                  查看详细分析
                </Button>
                <Button 
                  type={item.isInWatchlist ? "default" : "dashed"} 
                  className="watchlist-button-new" 
                  onClick={(e) => handleToggleWatchlist(item, e)}
                  disabled={item.isInWatchlist}
                >
                  {item.isInWatchlist ? '已添加' : '添加自选'}
                </Button>
                <Button 
                  type="default" 
                  className="push-button-new" 
                  icon={<BellOutlined />}
                  onClick={(e) => openPushConfig(item, e)}
                >
                  消息推送
                </Button>
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 消息推送配置模态框 */}
      <Modal
        title={`${currentFuture?.name || '合约'}消息推送配置`}
        open={pushModalVisible}
        onCancel={() => setPushModalVisible(false)}
        width={800}
        footer={[
          <Button key="cancel" onClick={() => setPushModalVisible(false)}>
            取消
          </Button>,
          <Button key="save" type="primary" onClick={() => pushForm.submit()}>
            保存配置
          </Button>
        ]}
      >
        <Form
          form={pushForm}
          layout="vertical"
          onFinish={savePushConfig}
          initialValues={{
            pushMethods: ['email'],
            alertTiming: 'price',
            priceAlert: true,
            priceLevel: 0,
            trendChange: true,
            riskAlert: true,
            aiSignal: true
          }}
        >
          {/* 推送方式 */}
          <Card title="推送方式" style={{ marginBottom: 16 }}>
            <Row gutter={[16, 16]}>
              <Col span={8}>
                <Item label="邮箱" name="emailPush" valuePropName="checked">
                  <Switch />
                </Item>
              </Col>
              <Col span={8}>
                <Item label="微信" name="wechatPush" valuePropName="checked">
                  <Switch />
                </Item>
              </Col>
              <Col span={8}>
                <Item label="钉钉" name="dingtalkPush" valuePropName="checked">
                  <Switch />
                </Item>
              </Col>
            </Row>
          </Card>

          {/* 提醒时机 */}
          <Card title="提醒时机" style={{ marginBottom: 16 }}>
            <Row gutter={[16, 16]}>
              <Col span={24}>
                <Item label="提醒类型" name="alertTiming">
                  <Select>
                    <Option value="price">价格点位提醒</Option>
                    <Option value="trend">趋势变化提醒</Option>
                    <Option value="risk">风险预警提醒</Option>
                    <Option value="ai">AI信号提醒</Option>
                  </Select>
                </Item>
              </Col>
              <Col span={12}>
                <Item label="价格点位" name="priceLevel">
                  <InputNumber 
                    min={0} 
                    step={10} 
                    placeholder="请输入价格点位" 
                  />
                </Item>
              </Col>
              <Col span={12}>
                <Item label="波动幅度(%)" name="priceChange">
                  <InputNumber 
                    min={0.1} 
                    max={10} 
                    step={0.1} 
                    placeholder="请输入波动幅度" 
                  />
                </Item>
              </Col>
            </Row>
          </Card>

          {/* 推送内容 */}
          <Card title="推送内容" style={{ marginBottom: 16 }}>
            <Row gutter={[16, 8]}>
              <Col span={12}>
                <Item label="价格变动" name="priceAlert" valuePropName="checked">
                  <Switch defaultChecked />
                </Item>
              </Col>
              <Col span={12}>
                <Item label="趋势变化" name="trendChange" valuePropName="checked">
                  <Switch defaultChecked />
                </Item>
              </Col>
              <Col span={12}>
                <Item label="风险预警" name="riskAlert" valuePropName="checked">
                  <Switch defaultChecked />
                </Item>
              </Col>
              <Col span={12}>
                <Item label="AI信号" name="aiSignal" valuePropName="checked">
                  <Switch defaultChecked />
                </Item>
              </Col>
            </Row>
          </Card>

          {/* 高级配置 */}
          <Card title="高级配置" style={{ marginBottom: 16 }}>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Item label="推送频率限制(分钟)" name="pushInterval">
                  <InputNumber min={1} max={60} step={1} defaultValue={5} />
                </Item>
              </Col>
              <Col span={12}>
                <Item label="静默时间(小时)" name="quietHours">
                  <InputNumber min={0} max={24} step={1} defaultValue={0} />
                </Item>
              </Col>
            </Row>
          </Card>
        </Form>
      </Modal>
      </div>
    </>
  );
};

export default Dashboard;