import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Descriptions,
  Divider,
  message,
  Tabs,
  Badge,
  Tooltip,
  Row,
  Col,
  Statistic,
  List,
  Avatar,
  Typography,
  Dropdown,
  Menu,
  Popconfirm,
} from 'antd';
import {
  MessageOutlined,
  UserOutlined,
  SendOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  MoreOutlined,
  PhoneOutlined,
  MailOutlined,
  FileTextOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { afterSalesDataSource, CustomerServiceTicket } from '@/services/afterSalesDataSource';

const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;
const { Text, Paragraph } = Typography;

interface CustomerServiceFormData {
  orderId: string;
  customerId: string;
  customerName: string;
  customerEmail: string;
  subject: string;
  category: string;
  priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'URGENT';
  status: 'OPEN' | 'IN_PROGRESS' | 'WAITING_CUSTOMER' | 'RESOLVED' | 'CLOSED';
  assignedTo?: string;
  createdAt: string;
  updatedAt: string;
  platform: string;
  lastMessage?: string;
  messageCount: number;
}

interface ChatMessage {
  id: string;
  ticketId: string;
  sender: 'CUSTOMER' | 'AGENT' | 'SYSTEM';
  senderName: string;
  content: string;
  attachments?: string[];
  createdAt: string;
  isRead: boolean;
}

const TICKET_STATUS_MAP: Record<string, { color: string; text: string }> = {
  OPEN: { color: 'error', text: 'Open' },
  IN_PROGRESS: { color: 'processing', text: 'In Progress' },
  WAITING_CUSTOMER: { color: 'warning', text: 'Waiting Customer' },
  RESOLVED: { color: 'success', text: 'Resolved' },
  CLOSED: { color: 'default', text: 'Closed' },
};

const PRIORITY_MAP: Record<string, { color: string; text: string }> = {
  LOW: { color: 'default', text: 'Low' },
  MEDIUM: { color: 'blue', text: 'Medium' },
  HIGH: { color: 'orange', text: 'High' },
  URGENT: { color: 'red', text: 'Urgent' },
};

const CATEGORIES = [
  { value: 'ORDER_ISSUE', label: 'Order Issue' },
  { value: 'REFUND_REQUEST', label: 'Refund Request' },
  { value: 'RETURN_REQUEST', label: 'Return Request' },
  { value: 'SHIPPING_ISSUE', label: 'Shipping Issue' },
  { value: 'PRODUCT_INQUIRY', label: 'Product Inquiry' },
  { value: 'PAYMENT_ISSUE', label: 'Payment Issue' },
  { value: 'OTHER', label: 'Other' },
];

const QUICK_REPLIES = [
  'Thank you for contacting us. How can I help you today?',
  'I understand your concern. Let me check that for you.',
  'I apologize for the inconvenience. We will resolve this as soon as possible.',
  'Your request has been processed. Is there anything else I can help with?',
  'Thank you for your patience. We are looking into this issue.',
];

export const CustomerService: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [tickets, setTickets] = useState<CustomerServiceTicket[]>([]);
  const [selectedTicket, setSelectedTicket] = useState<CustomerServiceTicket | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [chatModalVisible, setChatModalVisible] = useState(false);
  const [newTicketModalVisible, setNewTicketModalVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('all');
  const [messageInput, setMessageInput] = useState('');
  const [stats, setStats] = useState({
    total: 0,
    open: 0,
    inProgress: 0,
    resolved: 0,
    avgResponseTime: 0,
  });
  const chatEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    fetchTickets();
  }, []);

  useEffect(() => {
    if (chatModalVisible && chatEndRef.current) {
      chatEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, chatModalVisible]);

  const fetchTickets = async () => {
    setLoading(true);
    try {
      const mockTickets: CustomerServiceTicket[] = [
        {
          id: '1',
          ticketId: 'TKT-2026-001',
          orderId: 'ORD-2026-001',
          customerId: 'CUST_001',
          customerName: 'John Smith',
          customerEmail: 'john.smith@email.com',
          subject: 'Order not received',
          category: 'SHIPPING_ISSUE',
          priority: 'HIGH',
          status: 'OPEN',
          createdAt: '2026-03-18 10:30:00',
          updatedAt: '2026-03-18 11:00:00',
          platform: 'Amazon',
          lastMessage: 'When will my order arrive?',
          messageCount: 3,
        },
        {
          id: '2',
          ticketId: 'TKT-2026-002',
          orderId: 'ORD-2026-002',
          customerId: 'CUST_002',
          customerName: 'Emma Wilson',
          customerEmail: 'emma.wilson@email.com',
          subject: 'Request for refund',
          category: 'REFUND_REQUEST',
          priority: 'MEDIUM',
          status: 'IN_PROGRESS',
          assignedTo: 'Agent_001',
          createdAt: '2026-03-17 14:20:00',
          updatedAt: '2026-03-18 09:00:00',
          platform: 'eBay',
          lastMessage: 'I would like to request a refund for my order.',
          messageCount: 5,
        },
        {
          id: '3',
          ticketId: 'TKT-2026-003',
          orderId: 'ORD-2026-003',
          customerId: 'CUST_003',
          customerName: 'Michael Brown',
          customerEmail: 'michael.brown@email.com',
          subject: 'Product quality issue',
          category: 'RETURN_REQUEST',
          priority: 'LOW',
          status: 'RESOLVED',
          assignedTo: 'Agent_002',
          createdAt: '2026-03-16 09:15:00',
          updatedAt: '2026-03-17 16:30:00',
          platform: 'Shopify',
          lastMessage: 'Thank you for resolving my issue.',
          messageCount: 8,
        },
        {
          id: '4',
          ticketId: 'TKT-2026-004',
          orderId: 'ORD-2026-004',
          customerId: 'CUST_004',
          customerName: 'Sarah Davis',
          customerEmail: 'sarah.davis@email.com',
          subject: 'Payment failed',
          category: 'PAYMENT_ISSUE',
          priority: 'URGENT',
          status: 'WAITING_CUSTOMER',
          assignedTo: 'Agent_001',
          createdAt: '2026-03-18 08:00:00',
          updatedAt: '2026-03-18 10:00:00',
          platform: 'Amazon',
          lastMessage: 'Please provide your payment screenshot.',
          messageCount: 4,
        },
      ];

      setTickets(mockTickets);
      calculateStats(mockTickets);
    } catch (error) {
      message.error('Failed to load tickets');
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (ticketList: CustomerServiceTicket[]) => {
    setStats({
      total: ticketList.length,
      open: ticketList.filter((t) => t.status === 'OPEN').length,
      inProgress: ticketList.filter((t) => t.status === 'IN_PROGRESS').length,
      resolved: ticketList.filter((t) => t.status === 'RESOLVED').length,
      avgResponseTime: 2.5,
    });
  };

  const fetchMessages = async (ticketId: string) => {
    const mockMessages: ChatMessage[] = [
      {
        id: '1',
        ticketId,
        sender: 'CUSTOMER',
        senderName: selectedTicket?.customerName || 'Customer',
        content: 'Hello, I have an issue with my order.',
        createdAt: '2026-03-18 10:30:00',
        isRead: true,
      },
      {
        id: '2',
        ticketId,
        sender: 'AGENT',
        senderName: 'Support Agent',
        content: 'Hello! Thank you for contacting us. How can I help you today?',
        createdAt: '2026-03-18 10:32:00',
        isRead: true,
      },
      {
        id: '3',
        ticketId,
        sender: 'CUSTOMER',
        senderName: selectedTicket?.customerName || 'Customer',
        content: 'My order was supposed to arrive yesterday but it hasnt been delivered yet.',
        createdAt: '2026-03-18 10:35:00',
        isRead: true,
      },
      {
        id: '4',
        ticketId,
        sender: 'AGENT',
        senderName: 'Support Agent',
        content: 'I apologize for the delay. Let me check the status of your order for you.',
        createdAt: '2026-03-18 10:38:00',
        isRead: true,
      },
    ];
    setMessages(mockMessages);
  };

  const handleViewDetail = (ticket: CustomerServiceTicket) => {
    setSelectedTicket(ticket);
    setDetailModalVisible(true);
  };

  const handleOpenChat = (ticket: CustomerServiceTicket) => {
    setSelectedTicket(ticket);
    setChatModalVisible(true);
    fetchMessages(ticket.ticketId);
  };

  const handleSendMessage = async () => {
    if (!messageInput.trim()) return;

    const newMessage: ChatMessage = {
      id: Date.now().toString(),
      ticketId: selectedTicket?.ticketId || '',
      sender: 'AGENT',
      senderName: 'Support Agent',
      content: messageInput,
      createdAt: new Date().toISOString(),
      isRead: true,
    };

    setMessages([...messages, newMessage]);
    setMessageInput('');
    message.success('Message sent');
  };

  const handleQuickReply = (reply: string) => {
    setMessageInput(reply);
  };

  const handleStatusChange = async (ticketId: string, newStatus: string) => {
    setLoading(true);
    try {
      console.log('Updating ticket status:', { ticketId, newStatus });
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Status updated successfully');
      fetchTickets();
    } catch (error) {
      message.error('Failed to update status');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateTicket = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      console.log('Creating new ticket:', values);

      await new Promise((resolve) => setTimeout(resolve, 1000));

      message.success('Ticket created successfully');
      setNewTicketModalVisible(false);
      form.resetFields();
      fetchTickets();
    } catch (error) {
      message.error('Failed to create ticket');
    } finally {
      setLoading(false);
    }
  };

  const getFilteredTickets = () => {
    if (activeTab === 'all') return tickets;
    return tickets.filter((t) => t.status === activeTab.toUpperCase());
  };

  const columns: ColumnsType<CustomerServiceTicket> = [
    {
      title: 'Ticket ID',
      dataIndex: 'ticketId',
      key: 'ticketId',
      width: 130,
      render: (text: string, record) => (
        <a onClick={() => handleViewDetail(record)}>{text}</a>
      ),
    },
    {
      title: 'Subject',
      dataIndex: 'subject',
      key: 'subject',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 120,
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 90,
      render: (platform: string) => <Tag>{platform}</Tag>,
    },
    {
      title: 'Category',
      dataIndex: 'category',
      key: 'category',
      width: 130,
      render: (category: string) => (
        <Tag color="blue">{CATEGORIES.find((c) => c.value === category)?.label || category}</Tag>
      ),
    },
    {
      title: 'Priority',
      dataIndex: 'priority',
      key: 'priority',
      width: 90,
      render: (priority: string) => {
        const config = PRIORITY_MAP[priority];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 130,
      render: (status: string) => {
        const config = TICKET_STATUS_MAP[status];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Messages',
      dataIndex: 'messageCount',
      key: 'messageCount',
      width: 80,
      render: (count: number) => (
        <Badge count={count} showZero color="#1890ff" />
      ),
    },
    {
      title: 'Updated',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 150,
    },
    {
      title: 'Actions',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Tooltip title="View Details">
            <Button
              type="link"
              icon={<FileTextOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          <Tooltip title="Chat">
            <Button
              type="link"
              icon={<MessageOutlined />}
              onClick={() => handleOpenChat(record)}
            />
          </Tooltip>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item
                  key="resolve"
                  onClick={() => handleStatusChange(record.ticketId, 'RESOLVED')}
                >
                  Mark as Resolved
                </Menu.Item>
                <Menu.Item
                  key="close"
                  onClick={() => handleStatusChange(record.ticketId, 'CLOSED')}
                >
                  Close Ticket
                </Menu.Item>
              </Menu>
            }
          >
            <Button type="link" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      ),
    },
  ];

  return (
    <div className="customer-service-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="Total Tickets"
              value={stats.total}
              prefix={<FileTextOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Open"
              value={stats.open}
              valueStyle={{ color: '#f5222d' }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="In Progress"
              value={stats.inProgress}
              valueStyle={{ color: '#1890ff' }}
              prefix={<MessageOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Resolved"
              value={stats.resolved}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="Avg Response Time"
              value={stats.avgResponseTime}
              suffix="hours"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      <Card
        title="Customer Service Tickets"
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={fetchTickets}>
              Refresh
            </Button>
            <Button type="primary" onClick={() => setNewTicketModalVisible(true)}>
              New Ticket
            </Button>
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane
            tab={
              <span>
                <Badge count={stats.open} offset={[10, 0]} size="small">
                  All
                </Badge>
              </span>
            }
            key="all"
          />
          <TabPane
            tab={
              <span>
                <Badge count={stats.open} offset={[10, 0]} size="small">
                  Open
                </Badge>
              </span>
            }
            key="open"
          />
          <TabPane tab="In Progress" key="in_progress" />
          <TabPane tab="Waiting Customer" key="waiting_customer" />
          <TabPane tab="Resolved" key="resolved" />
          <TabPane tab="Closed" key="closed" />
        </Tabs>

        <Table
          columns={columns}
          dataSource={getFilteredTickets()}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} tickets`,
          }}
        />
      </Card>

      <Modal
        title="Ticket Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
          <Button
            key="chat"
            type="primary"
            icon={<MessageOutlined />}
            onClick={() => {
              setDetailModalVisible(false);
              handleOpenChat(selectedTicket!);
            }}
          >
            Open Chat
          </Button>,
        ]}
        width={700}
      >
        {selectedTicket && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="Ticket ID" span={2}>
              {selectedTicket.ticketId}
            </Descriptions.Item>
            <Descriptions.Item label="Order ID">{selectedTicket.orderId}</Descriptions.Item>
            <Descriptions.Item label="Platform">{selectedTicket.platform}</Descriptions.Item>
            <Descriptions.Item label="Subject" span={2}>
              {selectedTicket.subject}
            </Descriptions.Item>
            <Descriptions.Item label="Category">
              {CATEGORIES.find((c) => c.value === selectedTicket.category)?.label}
            </Descriptions.Item>
            <Descriptions.Item label="Priority">
              <Tag color={PRIORITY_MAP[selectedTicket.priority].color}>
                {PRIORITY_MAP[selectedTicket.priority].text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="Status">
              <Tag color={TICKET_STATUS_MAP[selectedTicket.status].color}>
                {TICKET_STATUS_MAP[selectedTicket.status].text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="Assigned To">
              {selectedTicket.assignedTo || 'Unassigned'}
            </Descriptions.Item>
            <Descriptions.Item label="Customer Name">
              {selectedTicket.customerName}
            </Descriptions.Item>
            <Descriptions.Item label="Customer Email">
              <MailOutlined /> {selectedTicket.customerEmail}
            </Descriptions.Item>
            <Descriptions.Item label="Created At">
              {selectedTicket.createdAt}
            </Descriptions.Item>
            <Descriptions.Item label="Updated At">
              {selectedTicket.updatedAt}
            </Descriptions.Item>
            <Descriptions.Item label="Last Message" span={2}>
              <Text ellipsis>{selectedTicket.lastMessage}</Text>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      <Modal
        title={
          <Space>
            <MessageOutlined />
            <span>Chat - {selectedTicket?.ticketId}</span>
          </Space>
        }
        open={chatModalVisible}
        onCancel={() => setChatModalVisible(false)}
        footer={null}
        width={700}
      >
        {selectedTicket && (
          <>
            <Card size="small" style={{ marginBottom: 16, background: '#f5f5f5' }}>
              <Descriptions column={3} size="small">
                <Descriptions.Item label="Customer">
                  {selectedTicket.customerName}
                </Descriptions.Item>
                <Descriptions.Item label="Order">{selectedTicket.orderId}</Descriptions.Item>
                <Descriptions.Item label="Platform">
                  {selectedTicket.platform}
                </Descriptions.Item>
              </Descriptions>
            </Card>

            <div
              style={{
                height: 300,
                overflowY: 'auto',
                border: '1px solid #d9d9d9',
                borderRadius: 4,
                padding: 16,
                marginBottom: 16,
              }}
            >
              <List
                dataSource={messages}
                renderItem={(msg) => (
                  <List.Item style={{ border: 'none', padding: '8px 0' }}>
                    <div
                      style={{
                        display: 'flex',
                        flexDirection: msg.sender === 'CUSTOMER' ? 'row' : 'row-reverse',
                        width: '100%',
                      }}
                    >
                      <Avatar
                        style={{
                          background: msg.sender === 'CUSTOMER' ? '#1890ff' : '#52c41a',
                        }}
                        icon={<UserOutlined />}
                      />
                      <div
                        style={{
                          maxWidth: '70%',
                          marginLeft: msg.sender === 'CUSTOMER' ? 12 : 0,
                          marginRight: msg.sender === 'AGENT' ? 12 : 0,
                        }}
                      >
                        <div
                          style={{
                            background: msg.sender === 'CUSTOMER' ? '#e6f7ff' : '#f6ffed',
                            padding: '8px 12px',
                            borderRadius: 8,
                          }}
                        >
                          <Text type="secondary" style={{ fontSize: 12 }}>
                            {msg.senderName} - {msg.createdAt}
                          </Text>
                          <Paragraph style={{ margin: '4px 0 0' }}>{msg.content}</Paragraph>
                        </div>
                      </div>
                    </div>
                  </List.Item>
                )}
              />
              <div ref={chatEndRef} />
            </div>

            <div style={{ marginBottom: 12 }}>
              <Text type="secondary" style={{ fontSize: 12 }}>
                Quick Replies:
              </Text>
              <div style={{ marginTop: 8 }}>
                {QUICK_REPLIES.map((reply, index) => (
                  <Tag
                    key={index}
                    style={{ cursor: 'pointer', marginBottom: 4 }}
                    onClick={() => handleQuickReply(reply)}
                  >
                    {reply.substring(0, 30)}...
                  </Tag>
                ))}
              </div>
            </div>

            <Space.Compact style={{ width: '100%' }}>
              <TextArea
                value={messageInput}
                onChange={(e) => setMessageInput(e.target.value)}
                placeholder="Type your message..."
                autoSize={{ minRows: 1, maxRows: 3 }}
                onPressEnter={(e) => {
                  if (!e.shiftKey) {
                    e.preventDefault();
                    handleSendMessage();
                  }
                }}
                style={{ borderRadius: '4px 0 0 4px' }}
              />
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleSendMessage}
                style={{ height: 'auto' }}
              >
                Send
              </Button>
            </Space.Compact>
          </>
        )}
      </Modal>

      <Modal
        title="Create New Ticket"
        open={newTicketModalVisible}
        onCancel={() => setNewTicketModalVisible(false)}
        onOk={handleCreateTicket}
        confirmLoading={loading}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="customerId"
                label="Customer ID"
                rules={[{ required: true }]}
              >
                <Input placeholder="Enter customer ID" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="orderId"
                label="Order ID"
                rules={[{ required: true }]}
              >
                <Input placeholder="Enter order ID" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="subject"
            label="Subject"
            rules={[{ required: true }]}
          >
            <Input placeholder="Enter ticket subject" />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="category"
                label="Category"
                rules={[{ required: true }]}
              >
                <Select placeholder="Select category">
                  {CATEGORIES.map((cat) => (
                    <Option key={cat.value} value={cat.value}>
                      {cat.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="priority"
                label="Priority"
                rules={[{ required: true }]}
              >
                <Select placeholder="Select priority">
                  <Option value="LOW">Low</Option>
                  <Option value="MEDIUM">Medium</Option>
                  <Option value="HIGH">High</Option>
                  <Option value="URGENT">Urgent</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="description"
            label="Description"
            rules={[{ required: true }]}
          >
            <TextArea rows={4} placeholder="Describe the issue..." />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CustomerService;
