import * as React from 'react';
import {
  Card,
  Statistic,
  Row,
  Col,
  Progress,
  Badge,
  Avatar,
  Tag,
  Button,
  Tooltip,
  Spin,
} from 'antd';
import {
  UserOutlined,
  ShoppingCartOutlined,
  DollarOutlined,
  TrophyOutlined,
  FireOutlined,
  ThunderboltOutlined,
  StarOutlined,
  HeartOutlined,
  EyeOutlined,
  LikeOutlined,
} from '@ant-design/icons';
import './style.scss';

interface DataDashboardProps {
  title: string;
  theme: 'dark' | 'light' | 'gradient';
  showAnimations: boolean;
  data?: any;
}

interface MockData {
  totalUsers: number;
  totalOrders: number;
  totalRevenue: number;
  conversionRate: number;
  activeUsers: number;
  topProducts: Array<{
    name: string;
    sales: number;
    growth: number;
    color: string;
  }>;
  recentActivities: Array<{
    id: string;
    user: string;
    action: string;
    time: string;
    avatar: string;
  }>;
  performanceMetrics: Array<{
    name: string;
    value: number;
    target: number;
    color: string;
  }>;
}

export default class DataDashboard extends React.PureComponent<DataDashboardProps> {
  private animationTimer: NodeJS.Timeout | null = null;

  private dataUpdateTimer: NodeJS.Timeout | null = null;

  constructor(props: DataDashboardProps) {
    super(props);
    this.state = {
      currentData: this.generateMockData(),
      isAnimating: false,
      loading: false,
    };
  }

  componentDidMount() {
    if (this.props.showAnimations) {
      this.startDataAnimation();
    }
  }

  componentWillUnmount() {
    if (this.animationTimer) {
      clearInterval(this.animationTimer);
    }
    if (this.dataUpdateTimer) {
      clearInterval(this.dataUpdateTimer);
    }
  }

  generateMockData = (): MockData => ({
    totalUsers: Math.floor(Math.random() * 50000) + 10000,
    totalOrders: Math.floor(Math.random() * 10000) + 2000,
    totalRevenue: Math.floor(Math.random() * 1000000) + 500000,
    conversionRate: Math.floor(Math.random() * 30) + 5,
    activeUsers: Math.floor(Math.random() * 5000) + 1000,
    topProducts: [
      { name: '智能手表', sales: 1250, growth: 15.6, color: '#1890ff' },
      { name: '无线耳机', sales: 980, growth: 8.2, color: '#52c41a' },
      { name: '智能音箱', sales: 756, growth: -2.1, color: '#faad14' },
      { name: '平板电脑', sales: 634, growth: 12.8, color: '#f5222d' },
      { name: '智能手环', sales: 520, growth: 25.3, color: '#722ed1' },
    ],
    recentActivities: [
      {
        id: '1',
        user: '张三',
        action: '购买了智能手表',
        time: '2分钟前',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=1',
      },
      {
        id: '2',
        user: '李四',
        action: '完成了订单支付',
        time: '5分钟前',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=2',
      },
      {
        id: '3',
        user: '王五',
        action: '添加了商品到购物车',
        time: '8分钟前',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=3',
      },
      {
        id: '4',
        user: '赵六',
        action: '发表了产品评价',
        time: '12分钟前',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=4',
      },
      {
        id: '5',
        user: '钱七',
        action: '分享了产品链接',
        time: '15分钟前',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=5',
      },
    ],
    performanceMetrics: [
      { name: '页面加载速度', value: 85, target: 90, color: '#1890ff' },
      { name: '用户满意度', value: 92, target: 95, color: '#52c41a' },
      { name: '系统稳定性', value: 98, target: 99, color: '#faad14' },
      { name: '数据准确性', value: 96, target: 98, color: '#f5222d' },
    ],
  });

  startDataAnimation = () => {
    this.dataUpdateTimer = setInterval(() => {
      this.setState({ loading: true });
      setTimeout(() => {
        this.setState({
          currentData: this.generateMockData(),
          loading: false,
          isAnimating: true,
        });
        setTimeout(() => {
          this.setState({ isAnimating: false });
        }, 1000);
      }, 500);
    }, 10000);
  };

  formatNumber = (num: number): string => {
    if (num >= 1000000) {
      return `${(num / 1000000).toFixed(1)}M`;
    }
    if (num >= 1000) {
      return `${(num / 1000).toFixed(1)}K`;
    }
    return num.toString();
  };

  render() {
    const { title, theme, showAnimations } = this.props;
    const { currentData, isAnimating, loading } = this.state as any;
    const curAmisData = this.props.data || {};

    const userInfo = curAmisData.__AmisCurrentUser;
    const systemInfo = curAmisData.__AmisSystemInfo || {};

    return (
      <div
        className={`data-dashboard-container ${theme} ${
          isAnimating ? 'animating' : ''
        }`}
      >
        <div className="dashboard-header">
          <h2 className="dashboard-title">
            {title || '数据仪表板'}
            {systemInfo.tenantName && (
              <Tag color="blue">【{systemInfo.tenantName}】</Tag>
            )}
          </h2>
          {userInfo && (
            <div className="user-info">
              <Avatar size={40} src={userInfo.icon} icon={<UserOutlined />} />
              <span className="user-name">{userInfo.name}</span>
            </div>
          )}
        </div>

        <Spin spinning={loading} tip="数据更新中...">
          <div className="dashboard-content">
            {/* 核心指标卡片 */}
            <Row gutter={[16, 16]} className="metrics-row">
              <Col xs={24} sm={12} lg={6}>
                <Card className="metric-card users-card" hoverable>
                  <Statistic
                    title="总用户数"
                    value={currentData.totalUsers}
                    formatter={(value) => this.formatNumber(value as number)}
                    prefix={<UserOutlined className="metric-icon" />}
                    valueStyle={{ color: '#1890ff' }}
                  />
                  <div className="metric-trend">
                    <Badge count="+12.5%" color="#52c41a" />
                    <span className="trend-text">较上月</span>
                  </div>
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Card className="metric-card orders-card" hoverable>
                  <Statistic
                    title="总订单数"
                    value={currentData.totalOrders}
                    formatter={(value) => this.formatNumber(value as number)}
                    prefix={<ShoppingCartOutlined className="metric-icon" />}
                    valueStyle={{ color: '#52c41a' }}
                  />
                  <div className="metric-trend">
                    <Badge count="+8.3%" color="#52c41a" />
                    <span className="trend-text">较上月</span>
                  </div>
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Card className="metric-card revenue-card" hoverable>
                  <Statistic
                    title="总收入"
                    value={currentData.totalRevenue}
                    formatter={(value) =>
                      `¥${this.formatNumber(value as number)}`
                    }
                    prefix={<DollarOutlined className="metric-icon" />}
                    valueStyle={{ color: '#faad14' }}
                  />
                  <div className="metric-trend">
                    <Badge count="+15.2%" color="#52c41a" />
                    <span className="trend-text">较上月</span>
                  </div>
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Card className="metric-card conversion-card" hoverable>
                  <Statistic
                    title="转化率"
                    value={currentData.conversionRate}
                    suffix="%"
                    prefix={<TrophyOutlined className="metric-icon" />}
                    valueStyle={{ color: '#f5222d' }}
                  />
                  <div className="metric-trend">
                    <Badge count="+2.1%" color="#52c41a" />
                    <span className="trend-text">较上月</span>
                  </div>
                </Card>
              </Col>
            </Row>

            {/* 热门产品和活动动态 */}
            <Row gutter={[16, 16]} className="content-row">
              <Col xs={24} lg={12}>
                <Card
                  title={
                    <span>
                      <FireOutlined className="section-icon" />
                      热门产品
                    </span>
                  }
                  className="products-card"
                  extra={<Button type="link">查看全部</Button>}
                >
                  <div className="products-list">
                    {currentData.topProducts.map(
                      (product: any, index: number) => (
                        <div key={index} className="product-item">
                          <div className="product-info">
                            <div className="product-name">{product.name}</div>
                            <div className="product-sales">
                              {product.sales} 销量
                            </div>
                          </div>
                          <div className="product-growth">
                            <Tag color={product.growth > 0 ? 'green' : 'red'}>
                              {product.growth > 0 ? '+' : ''}
                              {product.growth}%
                            </Tag>
                          </div>
                          <div className="product-progress">
                            <Progress
                              percent={Math.min(
                                (product.sales / 1500) * 100,
                                100,
                              )}
                              strokeColor={product.color}
                              showInfo={false}
                              size="small"
                            />
                          </div>
                        </div>
                      ),
                    )}
                  </div>
                </Card>
              </Col>
              <Col xs={24} lg={12}>
                <Card
                  title={
                    <span>
                      <ThunderboltOutlined className="section-icon" />
                      实时动态
                    </span>
                  }
                  className="activities-card"
                  extra={<Button type="link">查看全部</Button>}
                >
                  <div className="activities-list">
                    {currentData.recentActivities.map((activity: any) => (
                      <div key={activity.id} className="activity-item">
                        <Avatar
                          size={32}
                          src={activity.avatar}
                          icon={<UserOutlined />}
                        />
                        <div className="activity-content">
                          <div className="activity-text">
                            <span className="user-name">{activity.user}</span>
                            <span className="action">{activity.action}</span>
                          </div>
                          <div className="activity-time">{activity.time}</div>
                        </div>
                        <div className="activity-actions">
                          <Tooltip title="点赞">
                            <Button
                              type="text"
                              icon={<LikeOutlined />}
                              size="small"
                            />
                          </Tooltip>
                          <Tooltip title="查看">
                            <Button
                              type="text"
                              icon={<EyeOutlined />}
                              size="small"
                            />
                          </Tooltip>
                        </div>
                      </div>
                    ))}
                  </div>
                </Card>
              </Col>
            </Row>

            {/* 性能指标 */}
            <Row gutter={[16, 16]} className="performance-row">
              <Col xs={24}>
                <Card
                  title={
                    <span>
                      <StarOutlined className="section-icon" />
                      性能指标
                    </span>
                  }
                  className="performance-card"
                >
                  <Row gutter={[16, 16]}>
                    {currentData.performanceMetrics.map(
                      (metric: any, index: number) => (
                        <Col xs={24} sm={12} lg={6} key={index}>
                          <div className="performance-item">
                            <div className="performance-header">
                              <span className="metric-name">{metric.name}</span>
                              <span className="metric-value">
                                {metric.value}%
                              </span>
                            </div>
                            <Progress
                              percent={metric.value}
                              strokeColor={metric.color}
                              trailColor="#f0f0f0"
                              strokeWidth={8}
                            />
                            <div className="performance-target">
                              目标: {metric.target}%
                            </div>
                          </div>
                        </Col>
                      ),
                    )}
                  </Row>
                </Card>
              </Col>
            </Row>

            {/* 活跃用户统计 */}
            <Row gutter={[16, 16]} className="active-users-row">
              <Col xs={24}>
                <Card
                  title={
                    <span>
                      <HeartOutlined className="section-icon" />
                      活跃用户统计
                    </span>
                  }
                  className="active-users-card"
                >
                  <div className="active-users-content">
                    <div className="active-users-main">
                      <div className="active-users-number">
                        <span className="number">
                          {this.formatNumber(currentData.activeUsers)}
                        </span>
                        <span className="unit">活跃用户</span>
                      </div>
                      <div className="active-users-description">
                        当前在线用户数量，实时更新
                      </div>
                    </div>
                    <div className="active-users-visual">
                      <div className="user-avatars">
                        {Array.from({ length: 8 }, (_, i) => (
                          <Avatar
                            key={i}
                            size={80}
                            src={`https://api.dicebear.com/7.x/avataaars/svg?seed=${
                              i + 10
                            }`}
                            className="user-avatar"
                            style={{
                              animationDelay: `${i * 0.1}s`,
                              transform: `rotate(${
                                i * 45
                              }deg) translateY(-60px) rotate(-${i * 45}deg)`,
                            }}
                          />
                        ))}
                      </div>
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>
          </div>
        </Spin>
      </div>
    );
  }
}
