import React, { useState, useEffect } from 'react';
import { Card, Row, Col, DatePicker, Statistic, Button, Select, message } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, ReloadOutlined, DownloadOutlined, SettingOutlined } from '@ant-design/icons';
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import { dashboardApi } from '../services/ApiService';

const { RangePicker } = DatePicker;
const { Option } = Select;

const DashboardPage: React.FC = () => {
  const [timeRange, setTimeRange] = useState<any>(null);
  const [shop, setShop] = useState<string>('all');
  const [kpiData, setKpiData] = useState<any[]>([]);
  const [trendData, setTrendData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  // 加载Dashboard数据
  useEffect(() => {
    loadDashboardData();
  }, [shop, timeRange]);

  const loadDashboardData = async () => {
    setLoading(true);
    try {
      const response = await dashboardApi.getDashboardData({
        shop,
        startDate: timeRange?.[0]?.format('YYYY-MM-DD'),
        endDate: timeRange?.[1]?.format('YYYY-MM-DD'),
      });
      
      if (response.kpiData) {
        setKpiData(response.kpiData);
      } else {
        // 使用默认KPI数据
        setKpiData([
          {
            title: '总销售额',
            value: '¥128,500',
            change: 12.5,
            status: 'up',
            icon: <DollarOutlined />,
          },
          {
            title: '订单数',
            value: '2,850',
            change: 8.2,
            status: 'up',
            icon: <OrderedListOutlined />,
          },
          {
            title: '转化率',
            value: '4.8%',
            change: -1.2,
            status: 'down',
            icon: <LineChartOutlined />,
          },
          {
            title: '平均订单价值',
            value: '¥45.1',
            change: 3.5,
            status: 'up',
            icon: <ShoppingOutlined />,
          },
        ]);
      }
      
      if (response.trendData) {
        setTrendData(response.trendData);
      } else {
        // 使用默认趋势数据
        setTrendData([
          { date: '1/1', sales: 12000, orders: 350 },
          { date: '1/2', sales: 15000, orders: 420 },
          { date: '1/3', sales: 18000, orders: 480 },
          { date: '1/4', sales: 16000, orders: 430 },
          { date: '1/5', sales: 20000, orders: 520 },
          { date: '1/6', sales: 22000, orders: 550 },
          { date: '1/7', sales: 25000, orders: 600 },
        ]);
      }
    } catch (error) {
      console.error('Failed to load dashboard data:', error);
      message.error('Failed to load dashboard data');
      // 使用默认数据
      setKpiData([
        {
          title: '总销售额',
          value: '¥128,500',
          change: 12.5,
          status: 'up',
          icon: <DollarOutlined />,
        },
        {
          title: '订单数',
          value: '2,850',
          change: 8.2,
          status: 'up',
          icon: <OrderedListOutlined />,
        },
        {
          title: '转化率',
          value: '4.8%',
          change: -1.2,
          status: 'down',
          icon: <LineChartOutlined />,
        },
        {
          title: '平均订单价值',
          value: '¥45.1',
          change: 3.5,
          status: 'up',
          icon: <ShoppingOutlined />,
        },
      ]);
      setTrendData([
        { date: '1/1', sales: 12000, orders: 350 },
        { date: '1/2', sales: 15000, orders: 420 },
        { date: '1/3', sales: 18000, orders: 480 },
        { date: '1/4', sales: 16000, orders: 430 },
        { date: '1/5', sales: 20000, orders: 520 },
        { date: '1/6', sales: 22000, orders: 550 },
        { date: '1/7', sales: 25000, orders: 600 },
      ]);
    } finally {
      setLoading(false);
    }
  };

  const handleTimeRangeChange = (dates: any) => {
    setTimeRange(dates);
  };

  const handleShopChange = (value: string) => {
    setShop(value);
  };

  const handleRefresh = () => {
    loadDashboardData();
  };

  const handleExport = async () => {
    try {
      await dashboardApi.getDashboardData({
        shop,
        startDate: timeRange?.[0]?.format('YYYY-MM-DD'),
        endDate: timeRange?.[1]?.format('YYYY-MM-DD'),
        export: true,
      });
      message.success('Report exported successfully');
    } catch (error) {
      console.error('Failed to export report:', error);
      message.error('Failed to export report');
    }
  };

  return (
    <div className="dashboard-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>Dashboard</h1>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
          <Select defaultValue="all" style={{ width: 120 }} onChange={handleShopChange}>
            <Option value="all">All Shops</Option>
            <Option value="shop1">Shop 1</Option>
            <Option value="shop2">Shop 2</Option>
          </Select>
          <RangePicker onChange={handleTimeRangeChange} />
          <Button icon={<ReloadOutlined />} onClick={handleRefresh}>Refresh</Button>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>Export</Button>
          <Button icon={<SettingOutlined />}>Customize</Button>
        </div>
      </div>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        {kpiData.map((kpi, index) => (
          <Col span={6} key={index}>
            <Card>
              <Statistic
                title={kpi.title}
                value={kpi.value}
                prefix={kpi.icon}
                suffix={
                  <span style={{ color: kpi.status === 'up' ? '#52c41a' : '#f5222d' }}>
                    {kpi.status === 'up' ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                    {Math.abs(kpi.change)}%
                  </span>
                }
              />
            </Card>
          </Col>
        ))}
      </Row>

      <Card title="Sales and Orders Trend" style={{ marginBottom: 24 }} loading={loading}>
        <div style={{ height: 400 }}>
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart
              data={trendData}
              margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
            >
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="date" />
              <YAxis yAxisId="left" />
              <YAxis yAxisId="right" orientation="right" />
              <Tooltip />
              <Area yAxisId="left" type="monotone" dataKey="sales" stroke="#1890ff" fill="#e6f7ff" />
              <Area yAxisId="right" type="monotone" dataKey="orders" stroke="#52c41a" fill="#f6ffed" />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </Card>

      <Row gutter={[16, 16]}>
        <Col span={12}>
          <Card title="Top Performing Products">
            <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <p>Product performance data will be displayed here</p>
            </div>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="Recent Orders">
            <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <p>Recent orders data will be displayed here</p>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

// 导入缺失的图标
import { DollarOutlined, OrderedListOutlined, LineChartOutlined, ShoppingOutlined } from '@ant-design/icons';

export default DashboardPage;