<template>
  <div class="message-container">
    <Row :gutter="24">
        <Col
          :span="16"
          :offset="4"
        >
          <!-- Connection Status Card -->
          <Card
            class="status-card"
            :bordered="false"
          >
            <div
              slot="title"
              class="card-title"
            >
              <Icon
                type="ios-pulse"
                size="18"
              />
              <span class="ml-2">{{ $t('SHOPEE_AUTO_SEND_MESSAGE_STATUS') }}</span>
            </div>

            <div class="status-content">
              <Row :gutter="16">
                <Col :span="8">
                  <div class="status-item">
                    <div class="status-label">
                      {{ $t('SHOPEE_AUTO_SEND_MESSAGE_CONNECTION') }}
                    </div>
                    <div class="status-value">
                      <Tag
                        :color="socketChat.connected ? 'success' : 'error'"
                        class="status-tag"
                      >
                        <Icon
                          :type="socketChat.connected ? 'ios-checkmark' : 'ios-close'"
                          size="14"
                        />
                        <span class="ml-1">
                          {{ socketChat.connected ? $t('CONNECTED') : $t('DISCONNECTED') }}
                        </span>
                      </Tag>
                    </div>
                  </div>
                </Col>

                <Col :span="8">
                  <div class="status-item">
                    <div class="status-label">
                      {{ $t('SHOPEE_AUTO_SEND_MESSAGE_CONNECTED_TIME') }}
                    </div>
                    <div class="status-value">
                      <span class="status-text">
                        {{ socketChat.timeConnected ? formatTime(socketChat.timeConnected) : '-' }}
                      </span>
                    </div>
                  </div>
                </Col>

                <Col :span="8">
                  <div class="status-item">
                    <div class="status-label">
                      {{ $t('SHOPEE_AUTO_SEND_MESSAGE_MESSAGES') }}
                    </div>
                    <div class="status-value">
                      <Badge
                        :count="logChat.length"
                        type="primary"
                        class="status-badge"
                      />
                    </div>
                  </div>
                </Col>
              </Row>

              <div
                v-if="socketChat.error"
                class="error-message"
              >
                <Alert
                  type="error"
                  :title="$t('SHOPEE_AUTO_SEND_MESSAGE_ERROR')"
                  :description="socketChat.error"
                  show-icon
                />
              </div>
            </div>
          </Card>

          <!-- Messages Log Card -->
          <Card
            class="log-card mt-4"
            :bordered="false"
          >
            <div
              slot="title"
              class="card-title"
            >
              <Icon
                type="ios-chatbubbles"
                size="18"
              />
              <span class="ml-2">{{ $t('SHOPEE_AUTO_SEND_MESSAGE_LOG') }}</span>
              <Badge
                :count="logChat.length"
                class="ml-2"
                type="primary"
              />
            </div>

            <div class="log-container">
              <div
                v-if="logChat.length === 0"
                class="empty-state"
              >
                <Icon
                  type="ios-chatbubbles-outline"
                  size="48"
                  class="empty-icon"
                />
                <p class="empty-text">
                  {{ $t('SHOPEE_AUTO_SEND_MESSAGE_NO_MESSAGES') }}
                </p>
              </div>

              <div
                v-else
                class="messages-list"
              >
                <div
                  v-for="(message, index) in logChat"
                  :key="index"
                  class="message-item"
                >
                  <div class="message-header">
                    <Icon
                      type="ios-person"
                      size="16"
                    />
                    <span class="message-sender">{{ message.sender_name || 'Unknown' }}</span>
                    <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                  </div>
                  <div class="message-content">
                    {{ message.content || message.text || 'No content' }}
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </Col>
      </Row>
  </div>
</template>
<script>
import { sendChatMessage } from '@/api/shopee/seller/chat/index';
import { socketConnectChat } from '@/api/shopee/seller/chat/socket';
import { loggerShopee } from '@/plugins/logger';

export default {
  name: 'ShopeeAutoReplyReview',
  data() {
    /** @type {ShopeeWebchatSocketMessage[]} */
    const logChat = [];

    return {
      socketChat: {
        timeConnected: null,
        timeDisConnected: null,
        connected: false,
        disconnected: false,
        error: null,
      },
      logChat,
    };
  },
  methods: {
    /**
     * Format time to readable string
     * @param {Date|string|number} time
     * @returns {string}
     */
    formatTime(time) {
      if (!time) {
        return '-';
      }

      const date = new Date(time);
      return date.toLocaleString('vi-VN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      });
    },

    /**
     * Handle new message from socket
     * @param {ShopeeWebchatSocketMessage} chatData
     */
    onNewMessage(chatData) {
      loggerShopee.info({
        msg: 'SHOPEE_CHAT_NEW_MESSAGE_RECEIVED',
        chatData,
      });
      this.logChat.push(chatData);
    },

    /**
     * Start listening to socket connection
     */
    startListenSocket() {
      socketConnectChat(
        this.onNewMessage,
        () => {
          this.socketChat.connected = true;
          this.socketChat.timeConnected = new Date();
          this.socketChat.error = null;
        },
        (error) => {
          this.socketChat.disconnected = true;
          this.socketChat.timeDisConnected = new Date();
          this.socketChat.error = error;
        },
      );
    },
  },
  created() {
    this.startListenSocket();
    if (false) {
      const toUserId = 1201756367;
      const toShopId = 792026147;
      const text = 'Xin chào quý khách, cảm ơn bạn đã ghé thăm cửa hàng của chúng tôi. Chúc bạn có một ngày tốt lành!';
      sendChatMessage(toUserId, toShopId, text)
        .then((response) => {
          loggerShopee.info({
            msg: 'SHOPEE_CHAT_MESSAGE_SENT',
            response,
          });
        })
        .catch((error) => {
          loggerShopee.error({
            msg: 'SHOPEE_CHAT_SEND_MESSAGE_ERROR',
            error,
          });
        });
    }
  },
};
</script>

<style scoped>
  .header-content {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .header-icon {
    color: #ff9900;
  }

  .header-title {
    margin: 0;
    color: #ff9900;
    font-size: 24px;
    font-weight: 600;
  }

  .message-container {
    padding: 24px 0;
  }

  .status-card,
  .log-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .card-title {
    display: flex;
    align-items: center;
    font-weight: 600;
    color: #333;
  }

  .status-content {
    padding: 16px 0;
  }

  .status-item {
    text-align: center;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
  }

  .status-label {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .status-value {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .status-tag {
    font-weight: 600;
  }

  .status-text {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .status-badge {
    font-size: 16px;
  }

  .error-message {
    margin-top: 16px;
  }

  .log-container {
    max-height: 400px;
    overflow-y: auto;
  }

  .empty-state {
    text-align: center;
    padding: 48px 24px;
    color: #999;
  }

  .empty-icon {
    color: #ddd;
    margin-bottom: 16px;
  }

  .empty-text {
    margin: 0;
    font-size: 16px;
  }

  .messages-list {
    max-height: 300px;
    overflow-y: auto;
  }

  .message-item {
    padding: 12px;
    border-bottom: 1px solid #f0f0f0;
    transition: background-color 0.2s ease;
  }

  .message-item:hover {
    background-color: #f8f9fa;
  }

  .message-item:last-child {
    border-bottom: none;
  }

  .message-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }

  .message-sender {
    font-weight: 600;
    color: #333;
    font-size: 14px;
  }

  .message-time {
    font-size: 12px;
    color: #999;
    margin-left: auto;
  }

  .message-content {
    font-size: 14px;
    color: #666;
    line-height: 1.4;
    word-break: break-word;
  }

  .mt-4 {
    margin-top: 24px;
  }

  .ml-1 {
    margin-left: 4px;
  }

  .ml-2 {
    margin-left: 8px;
  }
</style>
