import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  TextArea,
  message,
  Spin,
  Row,
  Col,
  Typography,
  Divider,
  Space,
  Tag,
  Descriptions,
  Badge,
} from 'antd';
import {
  MessageOutlined,
  PhoneOutlined,
  MailOutlined,
  UserOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  QuestionCircleOutlined,
  MessageSquareOutlined,
} from '@ant-design/icons';

const { Option } = Select;
const { Title, Text, Paragraph } = Typography;

// 模拟客户服务数据
const mockCustomerServices = [
  {
    id: 'CS-20260318-001',
    customerName: '张三',
    customerId: 'CUST-001',
    contactInfo: '13800138001',
    serviceType: 'PRODUCT_ISSUE',
    subject: '商品质量问题',
    description: '购买的iPhone 15 Pro屏幕出现闪烁问题',
    status: 'PENDING',
    priority: 'HIGH',
    createdAt: '2026-03-18T10:00:00Z',
    updatedAt: '2026-03-18T10:00:00Z',
    assignedTo: '客服专员A',
    messages: [
      {
        id: 'MSG-001',
        sender: 'CUSTOMER',
        content: '购买的iPhone 15 Pro屏幕出现闪烁问题',
        timestamp: '2026-03-18T10:00:00Z',
      },
    ],
  },
  {
    id: 'CS-20260318-002',
    customerName: '李四',
    customerId: 'CUST-002',
    contactInfo: '13900139002',
    serviceType: 'ORDER_ISSUE',
    subject: '订单发货问题',
    description: '订单已经付款但一直未发货',
    status: 'PROCESSING',
    priority: 'MEDIUM',
    createdAt: '2026-03-17T15:30:00Z',
    updatedAt: '2026-03-18T09:00:00Z',
    assignedTo: '客服专员B',
    messages: [
      {
        id: 'MSG-002',
        sender: 'CUSTOMER',
        content: '订单已经付款但一直未发货',
        timestamp: '2026-03-17T15:30:00Z',
      },
      {
        id: 'MSG-003',
        sender: 'SUPPORT',
        content: '您好，我们正在核实您的订单情况，稍后会给您回复',
        timestamp: '2026-03-18T09:00:00Z',
      },
    ],
  },
  {
    id: 'CS-20260318-003',
    customerName: '王五',
    customerId: 'CUST-003',
    contactInfo: '13700137003',
    serviceType: 'REFUND_ISSUE',
    subject: '退款未到账',
    description: '退款申请已经通过但钱还没到账',
    status: 'COMPLETED',
    priority: 'HIGH',
    createdAt: '2026-03-16T14:00:00Z',
    updatedAt: '2026-03-17T10:00:00Z',
    assignedTo: '客服专员A',
    messages: [
      {
        id: 'MSG-004',
        sender: 'CUSTOMER',
        content: '退款申请已经通过但钱还没到账',
        timestamp: '2026-03-16T14:00:00Z',
      },
      {
        id: 'MSG-005',
        sender: 'SUPPORT',
        content: '您好，退款通常需要1-3个工作日到账，请耐心等待',
        timestamp: '2026-03-16T15:00:00Z',
      },
      {
        id: 'MSG-006',
        sender: 'CUSTOMER',
        content: '已经收到退款了，谢谢',
        timestamp: '2026-03-17T10:00:00Z',
      },
    ],
  },
];

// 服务类型选项
const serviceTypes = [
  { value: 'PRODUCT_ISSUE', label: '商品问题' },
  { value: 'ORDER_ISSUE', label: '订单问题' },
  { value: 'REFUND_ISSUE', label: '退款问题' },
  { value: 'SHIPPING_ISSUE', label: '物流问题' },
  { value: 'ACCOUNT_ISSUE', label: '账户问题' },
  { value: 'OTHER', label: '其他问题' },
];

// 优先级选项
const priorities = [
  { value: 'LOW', label: '低', color: 'blue' },
  { value: 'MEDIUM', label: '中', color: 'orange' },
  { value: 'HIGH', label: '高', color: 'red' },
];

// 状态选项
const statuses = [
  { value: 'PENDING', label: '待处理' },
  { value: 'PROCESSING', label: '处理中' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'CLOSED', label: '已关闭' },
];

const CustomerService: React.FC = () => {
  const [services, setServices] = useState(mockCustomerServices);
  const [selectedService, setSelectedService] = useState<any>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [form] = Form.useForm();
  const [messageForm] = Form.useForm();
  const [newMessage, setNewMessage] = useState('');

  // 处理服务详情查看
  const handleServiceView = (service: any) => {
    setSelectedService(service);
    setIsModalVisible(true);
  };

  // 处理消息发送
  const handleMessageSend = async () => {
    if (!newMessage.trim()) return;
    
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const updatedServices = services.map(service => {
        if (service.id === selectedService.id) {
          const updatedService = {
            ...service,
            messages: [
              ...service.messages,
              {
                id: `MSG-${Date.now()}`,
                sender: 'SUPPORT',
                content: newMessage,
                timestamp: new Date().toISOString(),
              },
            ],
            updatedAt: new Date().toISOString(),
          };
          return updatedService;
        }
        return service;
      });
      
      setServices(updatedServices);
      setSelectedService(updatedServices.find(s => s.id === selectedService.id));
      setNewMessage('');
      message.success('消息发送成功');
    } catch (error) {
      message.error('消息发送失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 处理服务状态更新
  const handleStatusUpdate = async (values: any) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const updatedServices = services.map(service => {
        if (service.id === selectedService.id) {
          return {
            ...service,
            status: values.status,
            priority: values.priority,
            updatedAt: new Date().toISOString(),
          };
        }
        return service;
      });
      
      setServices(updatedServices);
      setSelectedService(updatedServices.find(s => s.id === selectedService.id));
      message.success('服务状态更新成功');
    } catch (error) {
      message.error('服务状态更新失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 获取服务类型标签
  const getServiceTypeTag = (type: string) => {
    const serviceType = serviceTypes.find(t => t.value === type);
    return serviceType ? <Tag>{serviceType.label}</Tag> : <Tag>{type}</Tag>;
  };

  // 获取优先级标签
  const getPriorityTag = (priority: string) => {
    const p = priorities.find(p => p.value === priority);
    return p ? <Tag color={p.color}>{p.label}</Tag> : <Tag>{priority}</Tag>;
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'PENDING':
        return <Tag color="processing"><ClockCircleOutlined /> 待处理</Tag>;
      case 'PROCESSING':
        return <Tag color="processing"><ClockCircleOutlined /> 处理中</Tag>;
      case 'COMPLETED':
        return <Tag color="success"><CheckCircleOutlined /> 已完成</Tag>;
      case 'CLOSED':
        return <Tag color="default"><CloseCircleOutlined /> 已关闭</Tag>;
      default:
        return <Tag>{status}</Tag>;
    }
  };

  // 服务表格列
  const serviceColumns = [
    {
      title: '服务ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '客户信息',
      key: 'customer',
      render: (_, record: any) => (
        <div>
          <div>{record.customerName}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>{record.contactInfo}</div>
        </div>
      ),
    },
    {
      title: '服务类型',
      dataIndex: 'serviceType',
      key: 'serviceType',
      render: (type: string) => getServiceTypeTag(type),
    },
    {
      title: '主题',
      dataIndex: 'subject',
      key: 'subject',
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      render: (priority: string) => getPriorityTag(priority),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Button type="primary" onClick={() => handleServiceView(record)}>
          处理
        </Button>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={4} style={{ margin: 0 }}>客户服务管理</Title>
            <Text type="secondary">售后逆向流程第三步</Text>
          </div>
        }
        extra={
          <Button type="primary">
            新建服务工单
          </Button>
        }
      >
        <Divider orientation="left">服务工单</Divider>
        <Table
          columns={serviceColumns}
          dataSource={services}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 客户服务详情模态框 */}
      {selectedService && (
        <Modal
          title="客户服务详情"
          open={isModalVisible}
          onCancel={() => setIsModalVisible(false)}
          footer={null}
          width={1000}
        >
          <Row gutter={16}>
            <Col span={16}>
              <Descriptions bordered column={1}>
                <Descriptions.Item label="服务ID">{selectedService.id}</Descriptions.Item>
                <Descriptions.Item label="客户姓名">{selectedService.customerName}</Descriptions.Item>
                <Descriptions.Item label="客户ID">{selectedService.customerId}</Descriptions.Item>
                <Descriptions.Item label="联系方式">{selectedService.contactInfo}</Descriptions.Item>
                <Descriptions.Item label="服务类型">{getServiceTypeTag(selectedService.serviceType)}</Descriptions.Item>
                <Descriptions.Item label="主题">{selectedService.subject}</Descriptions.Item>
                <Descriptions.Item label="描述">{selectedService.description}</Descriptions.Item>
                <Descriptions.Item label="优先级">{getPriorityTag(selectedService.priority)}</Descriptions.Item>
                <Descriptions.Item label="状态">{getStatusTag(selectedService.status)}</Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {new Date(selectedService.createdAt).toLocaleString()}
                </Descriptions.Item>
                <Descriptions.Item label="更新时间">
                  {new Date(selectedService.updatedAt).toLocaleString()}
                </Descriptions.Item>
                <Descriptions.Item label="分配给">{selectedService.assignedTo}</Descriptions.Item>
              </Descriptions>
            </Col>
            <Col span={8}>
              <Card title="状态管理">
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={handleStatusUpdate}
                  initialValues={{
                    status: selectedService.status,
                    priority: selectedService.priority,
                  }}
                >
                  <Form.Item
                    name="status"
                    label="服务状态"
                    rules={[{ required: true, message: '请选择服务状态' }]}
                  >
                    <Select placeholder="请选择服务状态">
                      {statuses.map(status => (
                        <Option key={status.value} value={status.value}>
                          {status.label}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="priority"
                    label="优先级"
                    rules={[{ required: true, message: '请选择优先级' }]}
                  >
                    <Select placeholder="请选择优先级">
                      {priorities.map(priority => (
                        <Option key={priority.value} value={priority.value}>
                          {priority.label}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="remark"
                    label="处理备注"
                  >
                    <TextArea rows={3} placeholder="请输入处理备注" />
                  </Form.Item>

                  <Form.Item>
                    <Button type="primary" htmlType="submit" loading={isLoading}>
                      更新状态
                    </Button>
                  </Form.Item>
                </Form>
              </Card>
            </Col>
          </Row>

          <Divider orientation="left">消息记录</Divider>
          <div style={{ 
            height: 400, 
            border: '1px solid #f0f0f0', 
            borderRadius: 4, 
            padding: 16, 
            overflow: 'auto',
            marginBottom: 16,
          }}>
            {selectedService.messages.map((message: any, index: number) => (
              <div
                key={message.id}
                style={{
                  marginBottom: 16,
                  display: 'flex',
                  flexDirection: message.sender === 'CUSTOMER' ? 'row' : 'row-reverse',
                }}
              >
                <div
                  style={{
                    width: '32px',
                    height: '32px',
                    borderRadius: '50%',
                    backgroundColor: message.sender === 'CUSTOMER' ? '#1890ff' : '#52c41a',
                    color: 'white',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    margin: '0 8px',
                  }}
                >
                  {message.sender === 'CUSTOMER' ? (
                    <UserOutlined />
                  ) : (
                    <MessageSquareOutlined />
                  )}
                </div>
                <div
                  style={{
                    maxWidth: '70%',
                    padding: 12,
                    borderRadius: 8,
                    backgroundColor: message.sender === 'CUSTOMER' ? '#f0f0f0' : '#e6f7ff',
                  }}
                >
                  <div style={{ marginBottom: 4, fontSize: '12px', color: '#999' }}>
                    {message.sender === 'CUSTOMER' ? '客户' : '客服'}
                    {' '}|
                    {' '}{new Date(message.timestamp).toLocaleString()}
                  </div>
                  <div>{message.content}</div>
                </div>
              </div>
            ))}
          </div>

          <div style={{ display: 'flex' }}>
            <TextArea
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              placeholder="输入回复消息"
              rows={3}
              style={{ flex: 1, marginRight: 8 }}
            />
            <Button
              type="primary"
              onClick={handleMessageSend}
              loading={isLoading}
              disabled={!newMessage.trim()}
            >
              发送
            </Button>
          </div>
        </Modal>
      )}
    </div>
  );
};

export default CustomerService;