import {
  useState,
  useEffect,
  Card,
  Row,
  Col,
  DatePicker,
  Statistic,
  Button,
  Select,
  message,
  ArrowUpOutlined,
  ArrowDownOutlined,
  ReloadOutlined,
  DownloadOutlined,
  SettingOutlined,
  DollarOutlined,
  OrderedListOutlined,
  LineChartOutlined,
  ShoppingOutlined,
  RechartsArea,
  AreaChart,
  CartesianGrid,
  ResponsiveContainer,
  RechartsTooltip,
  XAxis,
  YAxis,
  RangePicker,
  Option,
  Table,
  Typography,
  dashboardDataSource,
  FC,
} from '@/imports';
import { useLocale } from '../contexts/LocaleContext';

const DashboardPage: FC = () => {
  const [timeRange, setTimeRange] = useState<any>(null);
  const [shop, setShop] = useState<string>('all');
  const [kpiData, setKpiData] = useState<any[]>([]);
  const [trendData, setTrendData] = useState<any[]>([]);
  const [topProducts, setTopProducts] = useState<any[]>([]);
  const [recentOrders, setRecentOrders] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [productsLoading, setProductsLoading] = useState(false);
  const [ordersLoading, setOrdersLoading] = useState(false);
  const { t } = useLocale();

  useEffect(() => {
    loadDashboardData();
    loadTopProducts();
    loadRecentOrders();
  }, [shop, timeRange]);

  const loadDashboardData = async () => {
    setLoading(true);
    try {
      const response = await dashboardDataSource.getDashboardData({
        shop,
        startDate: timeRange?.[0]?.format('YYYY-MM-DD'),
        endDate: timeRange?.[1]?.format('YYYY-MM-DD'),
      });
      
      // 为KPI数据添加图标
      const kpiDataWithIcons = response.kpiData.map((kpi, index) => {
        const icons = [
          <DollarOutlined key="dollar" />,
          <OrderedListOutlined key="orders" />,
          <LineChartOutlined key="conversion" />,
          <ShoppingOutlined key="avg" />,
        ];
        return {
          ...kpi,
          title: t(`dashboard.${['totalSales', 'orders', 'conversion', 'avgOrderValue'][index]}`),
          icon: icons[index],
        };
      });
      
      setKpiData(kpiDataWithIcons);
      setTrendData(response.trendData);
    } catch (error) {
      console.error('Failed to load dashboard data:', error);
      message.error(t('common.error'));
      // 错误时使用默认数据
      setKpiData([
        {
          title: t('dashboard.totalSales'),
          value: '¥128,500',
          change: 12.5,
          status: 'up',
          icon: <DollarOutlined />,
        },
        {
          title: t('dashboard.orders'),
          value: '2,850',
          change: 8.2,
          status: 'up',
          icon: <OrderedListOutlined />,
        },
        {
          title: t('dashboard.conversion'),
          value: '4.8%',
          change: -1.2,
          status: 'down',
          icon: <LineChartOutlined />,
        },
        {
          title: t('dashboard.avgOrderValue'),
          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 loadTopProducts = async () => {
    setProductsLoading(true);
    try {
      const products = await dashboardDataSource.getTopProducts(5);
      setTopProducts(products);
    } catch (error) {
      console.error('Failed to load top products:', error);
      setTopProducts([]);
    } finally {
      setProductsLoading(false);
    }
  };

  const loadRecentOrders = async () => {
    setOrdersLoading(true);
    try {
      const orders = await dashboardDataSource.getRecentOrders(5);
      setRecentOrders(orders);
    } catch (error) {
      console.error('Failed to load recent orders:', error);
      setRecentOrders([]);
    } finally {
      setOrdersLoading(false);
    }
  };

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

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

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

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

  const productColumns = [
    {
      title: t('dashboard.productName'),
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: t('dashboard.sales'),
      dataIndex: 'sales',
      key: 'sales',
      render: (text: number) => `¥${text.toLocaleString()}`,
    },
    {
      title: t('dashboard.quantity'),
      dataIndex: 'quantity',
      key: 'quantity',
    },
  ];

  const orderColumns = [
    {
      title: t('dashboard.orderId'),
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: t('dashboard.customer'),
      dataIndex: 'customer',
      key: 'customer',
    },
    {
      title: t('dashboard.amount'),
      dataIndex: 'amount',
      key: 'amount',
      render: (text: number) => `¥${text.toLocaleString()}`,
    },
    {
      title: t('dashboard.status'),
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: t('dashboard.date'),
      dataIndex: 'date',
      key: 'date',
    },
  ];

  return (
    <div className="dashboard-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>
          {t('dashboard.title')}
        </h1>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
          <Select 
            value={shop} 
            style={{ width: 150 }} 
            onChange={handleShopChange}
          >
            <Option value="all">
              {t('dashboard.allShops')}
            </Option>
            <Option value="shop1">Shop 1</Option>
            <Option value="shop2">Shop 2</Option>
          </Select>
          <RangePicker onChange={handleTimeRangeChange} />
          <Button icon={<ReloadOutlined />} onClick={handleRefresh}>
            {t('dashboard.refresh')}
          </Button>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>
            {t('dashboard.export')}
          </Button>
          <Button icon={<SettingOutlined />}>
            {t('dashboard.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={t('dashboard.salesTrend')} 
        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" />
              <RechartsTooltip />
              <RechartsArea yAxisId="left" type="monotone" dataKey="sales" stroke="#1890ff" fill="#e6f7ff" />
              <RechartsArea yAxisId="right" type="monotone" dataKey="orders" stroke="#52c41a" fill="#f6ffed" />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </Card>

      <Row gutter={[16, 16]}>
        <Col span={12}>
          <Card title={t('dashboard.topProducts')} loading={productsLoading}>
            {topProducts.length > 0 ? (
              <Table 
                columns={productColumns} 
                dataSource={topProducts} 
                rowKey="id" 
                pagination={false}
                size="small"
              />
            ) : (
              <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <p>{t('common.noData')}</p>
              </div>
            )}
          </Card>
        </Col>
        <Col span={12}>
          <Card title={t('dashboard.recentOrders')} loading={ordersLoading}>
            {recentOrders.length > 0 ? (
              <Table 
                columns={orderColumns} 
                dataSource={recentOrders} 
                rowKey="id" 
                pagination={false}
                size="small"
              />
            ) : (
              <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <p>{t('common.noData')}</p>
              </div>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default DashboardPage;
