import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  Descriptions,
  Divider,
  message,
  Tag,
  Switch,
  Popconfirm,
  Alert,
  Tooltip,
  Badge,
  Spin,
  Popover,
  Row,
  Col,
  Statistic,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  StopOutlined,
  PlayCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  DownloadOutlined,
  UploadOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { returnDataSource, SKUData } from '@/services/returnDataSource';

const { Option } = Select;
const { TextArea } = Input;

interface SKUFormData {
  sku_name: string;
  product_name: string;
  platform: string;
  price: number;
  stock: number;
  return_rate: number;
  status: 'ACTIVE' | 'INACTIVE' | 'AUTO_REMOVED';
  auto_removed_reason?: string;
  last_updated: string;
  created_at: string;
}

const SKU_STATUS: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  ACTIVE: { color: 'green', text: '在售', icon: <CheckCircleOutlined /> },
  INACTIVE: { color: 'default', text: '下架', icon: <StopOutlined /> },
  AUTO_REMOVED: { color: 'red', text: '自动下架', icon: <ExclamationCircleOutlined /> },
};

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

const MOCK_SKU_DATA: SKUData[] = [
  {
    id: '1',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-001',
    sku_name: 'Wireless Bluetooth Headphones',
    product_name: 'Premium Wireless Headphones',
    platform: 'Amazon',
    price: 200.00,
    stock: 50,
    return_rate: 0.35,
    status: 'AUTO_REMOVED',
    auto_removed_reason: '退货率超过阈值 (35%)',
    last_updated: '2026-03-17',
    created_at: '2026-03-01',
  },
  {
    id: '2',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-002',
    sku_name: 'Smart Fitness Tracker',
    product_name: 'Fitness Tracker Pro',
    platform: 'eBay',
    price: 150.00,
    stock: 30,
    return_rate: 0.15,
    status: 'ACTIVE',
    last_updated: '2026-03-16',
    created_at: '2026-03-01',
  },
  {
    id: '3',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-003',
    sku_name: 'Portable Power Bank',
    product_name: '10000mAh Power Bank',
    platform: 'Shopify',
    price: 50.00,
    stock: 100,
    return_rate: 0.08,
    status: 'ACTIVE',
    last_updated: '2026-03-15',
    created_at: '2026-03-01',
  },
  {
    id: '4',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-004',
    sku_name: 'Bluetooth Speaker',
    product_name: 'Portable Bluetooth Speaker',
    platform: 'Walmart',
    price: 80.00,
    stock: 40,
    return_rate: 0.22,
    status: 'ACTIVE',
    last_updated: '2026-03-17',
    created_at: '2026-03-01',
  },
  {
    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',
    platform: 'Amazon',
    price: 10.00,
    stock: 200,
    return_rate: 0.05,
    status: 'ACTIVE',
    last_updated: '2026-03-14',
    created_at: '2026-03-01',
  },
  {
    id: '6',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-006',
    sku_name: 'Wireless Mouse',
    product_name: 'Ergonomic Wireless Mouse',
    platform: 'eBay',
    price: 30.00,
    stock: 60,
    return_rate: 0.12,
    status: 'ACTIVE',
    last_updated: '2026-03-16',
    created_at: '2026-03-01',
  },
  {
    id: '7',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-007',
    sku_name: 'Laptop Case',
    product_name: 'Protective Laptop Case',
    platform: 'Shopify',
    price: 45.00,
    stock: 25,
    return_rate: 0.18,
    status: 'ACTIVE',
    last_updated: '2026-03-15',
    created_at: '2026-03-01',
  },
  {
    id: '8',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    sku_id: 'SKU-008',
    sku_name: 'Smart Watch',
    product_name: 'Smart Watch Series 5',
    platform: 'Amazon',
    price: 250.00,
    stock: 20,
    return_rate: 0.28,
    status: 'AUTO_REMOVED',
    auto_removed_reason: '退货率超过阈值 (28%)',
    last_updated: '2026-03-17',
    created_at: '2026-03-01',
  },
];

const SKUManage: React.FC = () => {
  const [skuData, setSkuData] = useState<SKUData[]>(MOCK_SKU_DATA);
  const [loading, setLoading] = useState(false);
  const [selectedSku, setSelectedSku] = useState<SKUData | null>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [form] = Form.useForm();

  const columns: ColumnsType<SKUData> = [
    {
      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: SKUData) => (
        <a onClick={() => handleViewDetail(record)}>{name}</a>
      ),
    },
    {
      title: 'Product Name',
      dataIndex: 'product_name',
      key: 'product_name',
      width: 200,
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 100,
    },
    {
      title: 'Price',
      dataIndex: 'price',
      key: 'price',
      width: 100,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: 'Stock',
      dataIndex: 'stock',
      key: 'stock',
      width: 80,
    },
    {
      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: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string, record: SKUData) => {
        const config = SKU_STATUS[status as keyof typeof SKU_STATUS];
        return (
          <Popover content={record.auto_removed_reason || ''}>
            <Tag color={config.color} icon={config.icon}>
              {config.text}
            </Tag>
          </Popover>
        );
      },
    },
    {
      title: 'Last Updated',
      dataIndex: 'last_updated',
      key: 'last_updated',
      width: 120,
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 150,
      render: (_: any, record: SKUData) => (
        <Space size="middle">
          <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>
            View
          </Button>
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            Edit
          </Button>
          {record.status === 'ACTIVE' ? (
            <Popconfirm
              title="确定要下架这个SKU吗？"
              onConfirm={() => handleToggleStatus(record.id, 'INACTIVE')}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link" icon={<StopOutlined />} style={{ color: 'orange' }}>
                下架
              </Button>
            </Popconfirm>
          ) : (
            <Button 
              type="link" 
              icon={<PlayCircleOutlined />} 
              style={{ color: 'green' }}
              onClick={() => handleToggleStatus(record.id, 'ACTIVE')}
            >
              上架
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const handleViewDetail = (record: SKUData) => {
    setSelectedSku(record);
    setModalVisible(true);
  };

  const handleEdit = (record: SKUData) => {
    form.setFieldsValue({
      sku_id: record.sku_id,
      sku_name: record.sku_name,
      product_name: record.product_name,
      platform: record.platform,
      price: record.price,
      stock: record.stock,
    });
    setSelectedSku(record);
    setModalVisible(true);
  };

  const handleToggleStatus = (id: string, newStatus: 'ACTIVE' | 'INACTIVE') => {
    setLoading(true);
    setTimeout(() => {
      setSkuData(skuData.map(item => 
        item.id === id ? { ...item, status: newStatus, last_updated: new Date().toISOString().split('T')[0] } : item
      ));
      setLoading(false);
      message.success(`${newStatus === 'ACTIVE' ? '上架' : '下架'}成功`);
    }, 500);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setConfirmLoading(true);
      setTimeout(() => {
        setSkuData(skuData.map(item => 
          item.id === selectedSku?.id 
            ? { 
                ...item, 
                ...values, 
                last_updated: new Date().toISOString().split('T')[0] 
              } 
            : item
        ));
        setConfirmLoading(false);
        setModalVisible(false);
        message.success('SKU信息更新成功');
      }, 1000);
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const handleRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      setSkuData([...MOCK_SKU_DATA]);
      setLoading(false);
      message.success('数据已刷新');
    }, 1000);
  };

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

  const getHighRiskCount = () => {
    return skuData.filter(item => item.return_rate > 0.2).length;
  };

  return (
    <div style={{ padding: '24px' }}>
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={16}>
          <h1 style={{ margin: 0, fontSize: '24px', fontWeight: 600 }}>SKU管理中心</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>
            <Button icon={<UploadOutlined />} type="primary">
              批量上传
            </Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic 
              title="总SKU数" 
              value={skuData.length} 
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="在售SKU" 
              value={getStatusCount('ACTIVE')} 
              prefix={<PlayCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="自动下架" 
              value={getStatusCount('AUTO_REMOVED')} 
              prefix={<ExclamationCircleOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="高风险SKU" 
              value={getHighRiskCount()} 
              prefix={<WarningOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
      </Row>

      <Alert
        message="高退货率SKU提醒"
        description={`当前有 ${getHighRiskCount()} 个SKU退货率超过20%，请及时处理`}
        type="warning"
        showIcon
        style={{ marginBottom: 16 }}
      />

      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h3 style={{ margin: 0 }}>SKU列表</h3>
          <Button type="primary" icon={<PlusOutlined />}>
            添加SKU
          </Button>
        </div>
        <Table 
          columns={columns} 
          dataSource={skuData} 
          rowKey="id" 
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title={selectedSku ? "编辑SKU信息" : "添加SKU"}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="sku_id"
            label="SKU ID"
            rules={[{ required: true, message: '请输入SKU ID' }]}
          >
            <Input placeholder="请输入SKU ID" />
          </Form.Item>
          <Form.Item
            name="sku_name"
            label="SKU Name"
            rules={[{ required: true, message: '请输入SKU名称' }]}
          >
            <Input placeholder="请输入SKU名称" />
          </Form.Item>
          <Form.Item
            name="product_name"
            label="Product Name"
            rules={[{ required: true, message: '请输入产品名称' }]}
          >
            <Input placeholder="请输入产品名称" />
          </Form.Item>
          <Form.Item
            name="platform"
            label="Platform"
            rules={[{ required: true, message: '请选择平台' }]}
          >
            <Select placeholder="请选择平台">
              {PLATFORMS.map(platform => (
                <Option key={platform} value={platform}>{platform}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="price"
            label="Price"
            rules={[{ required: true, message: '请输入价格' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入价格"
              min={0}
              step={0.01}
              formatter={(value) => `$ ${value}`}
              parser={(value) => value?.replace(/^\$\s*/, '')}
            />
          </Form.Item>
          <Form.Item
            name="stock"
            label="Stock"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入库存"
              min={0}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SKUManage;