import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  InputNumber,
  Descriptions,
  Divider,
  message,
  Tag,
  Tabs,
  Row,
  Col,
  Statistic,
  Alert,
  Tooltip,
  Badge,
  Spin,
} from 'antd';
import {
  BarChartOutlined,
  LineChartOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  DownloadOutlined,
  FilterOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { returnDataSource, ReturnData, ReturnTrend } from '@/services/returnDataSource';
import { Bar, Line, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, Legend, ResponsiveContainer } from 'recharts';

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

interface ReturnStatistics {
  return_rate: number;
  total_orders: number;
  total_returns: number;
  return_amount: number;
  avg_processing_time: number;
  return_reasons: string[];
  status: 'NORMAL' | 'WARNING' | 'HIGH_RISK';
  last_return_date: string;
  created_at: string;
  updated_at: string;
}

interface ReturnTrend {
  date: string;
  return_rate: number;
  order_count: number;
  return_count: number;
}

const RETURN_STATUS: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  NORMAL: { color: 'green', text: '正常', icon: <CheckCircleOutlined /> },
  WARNING: { color: 'orange', text: '警告', icon: <WarningOutlined /> },
  HIGH_RISK: { color: 'red', text: '高风险', icon: <ExclamationCircleOutlined /> },
};

const RETURN_REASONS = [
  '产品质量问题',
  '尺寸不符',
  '描述不符',
  '物流问题',
  '客户改变主意',
  '重复订单',
  '其他原因',
];

const PLATFORMS = [
  'Amazon',
  'eBay',
  'Shopify',
  'Walmart',
  'TikTok Shop',
  'Temu',
  'Alibaba',
  'Other',
];

const MOCK_RETURN_DATA: ReturnData[] = [
  {
    id: '1',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-001',
    sku_name: 'Wireless Bluetooth Headphones',
    product_name: 'Premium Wireless Headphones',
    return_rate: 0.35,
    total_orders: 120,
    total_returns: 42,
    return_amount: 8400.00,
    avg_processing_time: 3.5,
    return_reasons: ['产品质量问题', '描述不符'],
    status: 'HIGH_RISK',
    last_return_date: '2026-03-17',
    created_at: '2026-03-01',
    updated_at: '2026-03-17',
  },
  {
    id: '2',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-002',
    sku_name: 'Smart Fitness Tracker',
    product_name: 'Fitness Tracker Pro',
    return_rate: 0.15,
    total_orders: 85,
    total_returns: 13,
    return_amount: 2600.00,
    avg_processing_time: 2.8,
    return_reasons: ['尺寸不符', '客户改变主意'],
    status: 'WARNING',
    last_return_date: '2026-03-16',
    created_at: '2026-03-01',
    updated_at: '2026-03-16',
  },
  {
    id: '3',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-003',
    sku_name: 'Portable Power Bank',
    product_name: '10000mAh Power Bank',
    return_rate: 0.08,
    total_orders: 200,
    total_returns: 16,
    return_amount: 1600.00,
    avg_processing_time: 2.2,
    return_reasons: ['物流问题', '其他原因'],
    status: 'NORMAL',
    last_return_date: '2026-03-15',
    created_at: '2026-03-01',
    updated_at: '2026-03-15',
  },
  {
    id: '4',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-004',
    sku_name: 'Bluetooth Speaker',
    product_name: 'Portable Bluetooth Speaker',
    return_rate: 0.22,
    total_orders: 95,
    total_returns: 21,
    return_amount: 4200.00,
    avg_processing_time: 3.1,
    return_reasons: ['产品质量问题', '描述不符', '客户改变主意'],
    status: 'WARNING',
    last_return_date: '2026-03-17',
    created_at: '2026-03-01',
    updated_at: '2026-03-17',
  },
  {
    id: '5',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-005',
    sku_name: 'USB-C Cable',
    product_name: 'Fast Charging USB-C Cable',
    return_rate: 0.05,
    total_orders: 300,
    total_returns: 15,
    return_amount: 750.00,
    avg_processing_time: 1.8,
    return_reasons: ['物流问题', '其他原因'],
    status: 'NORMAL',
    last_return_date: '2026-03-14',
    created_at: '2026-03-01',
    updated_at: '2026-03-14',
  },
];

const MOCK_RETURN_TRENDS: ReturnTrend[] = [
  { date: '2026-03-01', return_rate: 0.12, order_count: 45, return_count: 5 },
  { date: '2026-03-02', return_rate: 0.15, order_count: 52, return_count: 8 },
  { date: '2026-03-03', return_rate: 0.18, order_count: 48, return_count: 9 },
  { date: '2026-03-04', return_rate: 0.14, order_count: 55, return_count: 8 },
  { date: '2026-03-05', return_rate: 0.20, order_count: 42, return_count: 8 },
  { date: '2026-03-06', return_rate: 0.22, order_count: 38, return_count: 8 },
  { date: '2026-03-07', return_rate: 0.19, order_count: 40, return_count: 8 },
  { date: '2026-03-08', return_rate: 0.25, order_count: 45, return_count: 11 },
  { date: '2026-03-09', return_rate: 0.28, order_count: 50, return_count: 14 },
  { date: '2026-03-10', return_rate: 0.30, order_count: 48, return_count: 14 },
  { date: '2026-03-11', return_rate: 0.27, order_count: 52, return_count: 14 },
  { date: '2026-03-12', return_rate: 0.32, order_count: 45, return_count: 14 },
  { date: '2026-03-13', return_rate: 0.35, order_count: 40, return_count: 14 },
  { date: '2026-03-14', return_rate: 0.33, order_count: 42, return_count: 14 },
  { date: '2026-03-15', return_rate: 0.30, order_count: 48, return_count: 14 },
  { date: '2026-03-16', return_rate: 0.32, order_count: 50, return_count: 16 },
  { date: '2026-03-17', return_rate: 0.35, order_count: 55, return_count: 19 },
];

const ReturnMonitor: React.FC = () => {
  const [returnData, setReturnData] = useState<ReturnData[]>(MOCK_RETURN_DATA);
  const [loading, setLoading] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<ReturnData | null>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [filters, setFilters] = useState({
    platform: '',
    status: '',
    dateRange: null as any,
    minReturnRate: 0,
    maxReturnRate: 100,
  });

  const columns: ColumnsType<ReturnData> = [
    {
      title: 'SKU ID',
      dataIndex: 'sku_id',
      key: 'sku_id',
      width: 120,
    },
    {
      title: 'SKU Name',
      dataIndex: 'sku_name',
      key: 'sku_name',
      width: 200,
      render: (name: string, record: ReturnData) => (
        <a onClick={() => handleViewDetail(record)}>{name}</a>
      ),
    },
    {
      title: 'Product Name',
      dataIndex: 'product_name',
      key: 'product_name',
      width: 200,
    },
    {
      title: 'Return Rate',
      dataIndex: 'return_rate',
      key: 'return_rate',
      width: 120,
      render: (rate: number) => (
        <div>
          <span style={{ color: rate > 0.2 ? 'red' : rate > 0.1 ? 'orange' : 'green' }}>
            {((rate) * 100).toFixed(1)}%
          </span>
        </div>
      ),
    },
    {
      title: 'Total Orders',
      dataIndex: 'total_orders',
      key: 'total_orders',
      width: 100,
    },
    {
      title: 'Total Returns',
      dataIndex: 'total_returns',
      key: 'total_returns',
      width: 100,
    },
    {
      title: 'Return Amount',
      dataIndex: 'return_amount',
      key: 'return_amount',
      width: 120,
      render: (amount: number) => `$${amount.toFixed(2)}`,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = RETURN_STATUS[status as keyof typeof RETURN_STATUS];
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: 'Last Return',
      dataIndex: 'last_return_date',
      key: 'last_return_date',
      width: 120,
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 100,
      render: (_: any, record: ReturnData) => (
        <Space size="middle">
          <Button type="link" icon={<ExclamationCircleOutlined />} onClick={() => handleViewDetail(record)}>
            Details
          </Button>
        </Space>
      ),
    },
  ];

  const handleViewDetail = (record: ReturnData) => {
    setSelectedRecord(record);
    setModalVisible(true);
  };

  const handleRefresh = () => {
    setLoading(true);
    // 模拟数据刷新
    setTimeout(() => {
      setReturnData([...MOCK_RETURN_DATA]);
      setLoading(false);
      message.success('数据已刷新');
    }, 1000);
  };

  const handleFilter = (values: any) => {
    setFilters({
      platform: values.platform || '',
      status: values.status || '',
      dateRange: values.dateRange || null,
      minReturnRate: values.minReturnRate || 0,
      maxReturnRate: values.maxReturnRate || 100,
    });
  };

  const getStatusCount = (status: string) => {
    return returnData.filter(item => item.status === status).length;
  };

  const getTotalReturns = () => {
    return returnData.reduce((sum, item) => sum + item.total_returns, 0);
  };

  const getAverageReturnRate = () => {
    if (returnData.length === 0) return 0;
    const totalRate = returnData.reduce((sum, item) => sum + item.return_rate, 0);
    return totalRate / returnData.length;
  };

  return (
    <div style={{ padding: '24px' }}>
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={16}>
          <h1 style={{ margin: 0, fontSize: '24px', fontWeight: 600 }}>退货监控中心</h1>
          <p style={{ color: '#666', margin: '8px 0 0 0' }}>实时监控SKU退货率，及时发现高风险商品</p>
        </Col>
        <Col span={8} style={{ textAlign: 'right' }}>
          <Space>
            <Button 
              icon={<ReloadOutlined />} 
              onClick={handleRefresh}
              loading={loading}
            >
              刷新数据
            </Button>
            <Button icon={<DownloadOutlined />}>
              导出报告
            </Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic 
              title="总退货数" 
              value={getTotalReturns()} 
              prefix={<WarningOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="平均退货率" 
              value={((getAverageReturnRate()) * 100).toFixed(1)} 
              suffix="%"
              valueStyle={{ color: getAverageReturnRate() > 0.2 ? '#ff4d4f' : getAverageReturnRate() > 0.1 ? '#fa8c16' : '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="高风险SKU" 
              value={getStatusCount('HIGH_RISK')} 
              prefix={<ExclamationCircleOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="警告SKU" 
              value={getStatusCount('WARNING')} 
              prefix={<WarningOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
      </Row>

      <Card style={{ marginBottom: 16 }}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="退货率趋势" key="1">
            <div style={{ height: 400 }}>
              <ResponsiveContainer width="100%" height="100%">
                <Line
                  data={MOCK_RETURN_TRENDS}
                  margin={{ top: 20, right: 30, left: 0, bottom: 0 }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis yAxisId="left" />
                  <YAxis yAxisId="right" orientation="right" />
                  <RechartsTooltip />
                  <Legend />
                  <Line yAxisId="left" type="monotone" dataKey="return_rate" name="退货率" stroke="#ff4d4f" strokeWidth={2} />
                  <Line yAxisId="right" type="monotone" dataKey="order_count" name="订单数" stroke="#1890ff" />
                  <Line yAxisId="right" type="monotone" dataKey="return_count" name="退货数" stroke="#fa8c16" />
                </Line>
              </ResponsiveContainer>
            </div>
          </TabPane>
          <TabPane tab="退货原因分析" key="2">
            <div style={{ height: 400 }}>
              <ResponsiveContainer width="100%" height="100%">
                <Bar
                  data={RETURN_REASONS.map(reason => ({
                    name: reason,
                    value: Math.floor(Math.random() * 50) + 10,
                  }))}
                  margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Bar dataKey="value" name="退货数量" fill="#1890ff" />
                </Bar>
              </ResponsiveContainer>
            </div>
          </TabPane>
        </Tabs>
      </Card>

      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h3 style={{ margin: 0 }}>SKU退货率列表</h3>
          <Button icon={<FilterOutlined />} type="primary" onClick={() => {/* 打开筛选面板 */}}>
            筛选
          </Button>
        </div>
        <Table 
          columns={columns} 
          dataSource={returnData} 
          rowKey="id" 
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title="SKU退货详情"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={800}
      >
        {selectedRecord && (
          <div>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="SKU ID">{selectedRecord.sku_id}</Descriptions.Item>
              <Descriptions.Item label="SKU Name">{selectedRecord.sku_name}</Descriptions.Item>
              <Descriptions.Item label="Product Name">{selectedRecord.product_name}</Descriptions.Item>
              <Descriptions.Item label="Return Rate">
                <span style={{ color: selectedRecord.return_rate > 0.2 ? 'red' : selectedRecord.return_rate > 0.1 ? 'orange' : 'green' }}>
                  {((selectedRecord.return_rate) * 100).toFixed(1)}%
                </span>
              </Descriptions.Item>
              <Descriptions.Item label="Total Orders">{selectedRecord.total_orders}</Descriptions.Item>
              <Descriptions.Item label="Total Returns">{selectedRecord.total_returns}</Descriptions.Item>
              <Descriptions.Item label="Return Amount">${selectedRecord.return_amount.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="Avg Processing Time">{selectedRecord.avg_processing_time} days</Descriptions.Item>
              <Descriptions.Item label="Status" span={2}>
                <Tag color={RETURN_STATUS[selectedRecord.status].color} icon={RETURN_STATUS[selectedRecord.status].icon}>
                  {RETURN_STATUS[selectedRecord.status].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Last Return Date">{selectedRecord.last_return_date}</Descriptions.Item>
              <Descriptions.Item label="Created At">{selectedRecord.created_at}</Descriptions.Item>
            </Descriptions>

            <Divider orientation="left">退货原因</Divider>
            <Space wrap>
              {selectedRecord.return_reasons.map((reason, index) => (
                <Tag key={index}>{reason}</Tag>
              ))}
            </Space>

            <Divider orientation="left">退货趋势</Divider>
            <div style={{ height: 300 }}>
              <ResponsiveContainer width="100%" height="100%">
                <Line
                  data={MOCK_RETURN_TRENDS.slice(-7)}
                  margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <RechartsTooltip />
                  <Line type="monotone" dataKey="return_rate" stroke="#ff4d4f" activeDot={{ r: 8 }} />
                </Line>
              </ResponsiveContainer>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ReturnMonitor;