<template>
  <div class="reply-container">
    <Row :gutter="24">
        <Col
          :span="16"
          :offset="4"
        >
          <!-- Variables Card -->
          <Card
            class="variables-card"
            :bordered="false"
          >
            <div
              slot="title"
              class="card-title"
            >
              <Icon
                type="ios-code"
                size="18"
              />
              <span class="ml-2">{{ $t('SHOPEE_AUTO_REPLY_RATING_VARIABLES') }}</span>
            </div>

            <div class="variables-grid">
              <div
                v-for="(matchValue, matchKey) in matchText"
                :key="matchKey"
                class="variable-item"
              >
                <Tag
                  color="blue"
                  class="variable-tag"
                >
                  {{ matchKey }}
                </Tag>
                <span class="variable-description">{{ matchValue }}</span>
              </div>
            </div>
          </Card>

          <!-- Configuration Card -->
          <Card
            class="config-card mt-4"
            :bordered="false"
          >
            <div
              slot="title"
              class="card-title"
            >
              <Icon
                type="ios-settings"
                size="18"
              />
              <span class="ml-2">{{ $t('SHOPEE_AUTO_REPLY_RATING_CONFIG') }}</span>
            </div>

            <Alert
              v-if="isRunLimitVisible"
              type="warning"
              show-icon
              class="mb-3"
            >
              {{ $t('FEATURE_RUN_LIMIT_INFO', { limit: autoRunLimit }) }}
            </Alert>

            <Form
              :model="formData"
              :label-width="120"
            >
              <Row :gutter="16">
                <Col :span="12">
                  <FormItem :label="$t('SHOPEE_AUTO_REPLY_RATING_INPUT_CONTENT')">
                    <Input
                      v-model="replyRating.text"
                      type="textarea"
                      :rows="4"
                      :placeholder="$t('SHOPEE_AUTO_REPLY_RATING_INPUT_CONTENT')"
                      class="form-textarea"
                    />
                  </FormItem>
                </Col>

                <Col :span="12">
                  <FormItem :label="$t('SHOPEE_AUTO_REPLY_RATING_INPUT_CHAT')">
                    <Input
                      v-model="replyChat.text"
                      type="textarea"
                      :rows="4"
                      :placeholder="$t('INPUT_PLACEHOLDER_EMPTY_WITHOUT_USE')"
                      class="form-textarea"
                    />
                  </FormItem>
                </Col>
              </Row>

              <Row :gutter="16">
                <Col :span="12">
                  <FormItem :label="$t('SHOPEE_AUTO_REPLY_RATING_STAR_FILTER')">
                    <Select
                      v-model="queryRating.star"
                      multiple
                      style="width: 100%"
                      :placeholder="$t('SHOPEE_AUTO_REPLY_RATING_STAR_FILTER')"
                      @on-change="getchMetaRating"
                    >
                      <Option
                        v-for="star in [1, 2, 3, 4, 5]"
                        :key="star"
                        :value="star"
                      >
                        {{ $t('RATING_STAR', { star }) }}
                      </Option>
                    </Select>
                    <div class="form-help-text">
                      {{ $t('SHOPEE_AUTO_REPLY_RATING_STAR_HELP') }}
                    </div>
                  </FormItem>
                </Col>

                <Col :span="12">
                  <FormItem label=" ">
                    <Button
                      type="primary"
                      size="large"
                      :loading="replyHandler.loading"
                      :disabled="!(replyRating.text && queryRating.star.length) || isRunLimitReached"
                      class="action-button"
                      @click="handleReplyRating"
                    >
                      <Icon
                        type="ios-play"
                        size="16"
                      />
                      <span class="ml-1">{{ $t('SHOPEE_AUTO_REPLY_RATING_BTN') }}</span>
                    </Button>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Card>

          <!-- Log Card -->
          <Card
            class="log-card mt-4"
            :bordered="false"
          >
            <div
              slot="title"
              class="card-title"
            >
              <Icon
                type="ios-list"
                size="18"
              />
              <span class="ml-2">{{ $t('SHOPEE_AUTO_REPLY_RATING_LOG') }}</span>
              <Badge
                :count="replyHandler.sent"
                class="ml-2"
                type="primary"
              />
              <span class="ml-2 text-muted"> / {{ replyHandler.total | addCommas }} </span>
            </div>

            <div class="log-container">
              <Input
                :value="logText"
                type="textarea"
                :rows="15"
                readonly
                class="log-textarea"
              />
            </div>
          </Card>
        </Col>
      </Row>
  </div>
</template>
<script>
import delay from 'delay';
import PromiseMap from 'p-map';
import { getRatingListUnReply, replyRatingId, getRatingMeta } from '@/api/shopee/seller/rating';
import { sendChatMessage } from '@/api/shopee/seller/chat';
import { SHOPEE_AUTO_RUN_LIMITS } from '@/constant/shopee';

export default {
  name: 'ShopeeAutoReplyReview',
  data() {
    return {
      formData: {},
      queryRating: {
        star: [5],
        limit: 20,
      },
      replyRating: {
        text: this.$t('SHOPEE_AUTO_REPLY_RATING_PARAM_TEXT'),
      },
      replyChat: {
        text: '',
      },
      replyHandler: {
        loading: false,
        log: [],
        sent: 0,
        total: 0,
        sleepPerList: 5000,
        sleepPerRating: 500,
      },
      matchText: {
        BUYER_NAME: this.$t('SHOPEE_AUTO_REPLY_RATING_PARAM_BUYER_NAME'),
        ORDER_ID: this.$t('SHOPEE_AUTO_REPLY_RATING_PARAM_ORDER_ID'),
        RATING_STAR: this.$t('SHOPEE_AUTO_REPLY_RATING_PARAM_RATING_STAR'),
      },
    };
  },
  methods: {
    async getchMetaRating() {
      const metaRating = await getRatingMeta(this.queryRating.star);
      this.replyHandler.total = metaRating.to_reply_count;
    },
    async handleReplyRating() {
      this.replyHandler.loading = true;

      this.replyHandler.sent = 0;

      let isAllow = true;

      while (isAllow) {
        const listRating = await getRatingListUnReply(
          this.queryRating.star,
          this.queryRating.limit,
        );

        if (!(listRating && listRating.length)) {
          break;
        }

        await PromiseMap(
          listRating,
          async (ratingData) => {
            if (!isAllow) {
              return false;
            }

            const {
              user_id: buyerId,
              order_id: orderId,
              comment_id: commentId,
              rating_star: ratingStar,
              user_name: buyerName,
              reply,
            } = ratingData;

            if (!(!reply && this.queryRating.star.includes(ratingStar))) {
              return false;
            }

            const ratingText = this.replyRating.text
              .replace(/BUYER_NAME/g, buyerName)
              .replace(/ORDER_ID/g, orderId)
              .replace(/RATING_STAR/g, ratingStar);

            const payloadLog = {
              buyer: buyerName,
              order_id: orderId,
              star: ratingStar,
              text: ratingText,
              process_current: this.replyHandler.sent,
              process_total: this.replyHandler.total,
            };

            await replyRatingId(orderId, commentId, ratingText)
              .then((result) => {
                if (result.message === 'success') {
                  this.replyHandler.log.push(
                    `✅ ${this.$t('SHOPEE_AUTO_REPLY_RATING_SENT_SUCCESS', payloadLog)}`,
                  );
                } else {
                  this.replyHandler.log.push(
                    `❌ ${this.$t('SHOPEE_AUTO_REPLY_RATING_SENT_ERROR', payloadLog)}`,
                  );
                }
              })
              .catch(() => {
                this.replyHandler.log.push(
                  `❌ ${this.$t('SHOPEE_AUTO_REPLY_RATING_SENT_ERROR', payloadLog)}`,
                );
              });

            if (this.replyChat.text) {
              const toUserId = buyerId;
              const toShopId = buyerId;

              const textChat = this.replyChat.text
                .replace(/BUYER_NAME/g, buyerName)
                .replace(/ORDER_ID/g, orderId)
                .replace(/RATING_STAR/g, ratingStar);

              const payloadLog = {
                buyer: buyerName,
                text: textChat,
              };

              sendChatMessage(toUserId, toShopId, textChat)
                .then(() => {
                  this.replyHandler.log.push(
                    `✅ ${this.$t('SHOPEE_AUTO_CHAT_RATING_SENT_SUCCESS', payloadLog)}`,
                  );
                })
                .catch(() => {
                  this.replyHandler.log.push(
                    `❌ ${this.$t('SHOPEE_AUTO_CHAT_RATING_SENT_ERROR', payloadLog)}`,
                  );
                });
            }

            this.replyHandler.log.push('-------------');

            this.replyHandler.sent += 1;

            if (this.replyHandler.sent >= this.autoRunLimit) {
              const msg = this.$t('FEATURE_RUN_LIMIT_REACHED', {
                sent: this.replyHandler.sent,
                limit: this.autoRunLimit,
              });
              this.$Message.warning(msg);
              this.replyHandler.log.push(msg);
              isAllow = false;
            }

            await delay(this.replyHandler.sleepPerRating);
          },
          {
            concurrency: 1,
          },
        );

        if (!isAllow) {
          break;
        }

        await delay(this.replyHandler.sleepPerList);
      }
      this.replyHandler.loading = false;
    },
  },
  created() {
    this.getchMetaRating();
  },
  computed: {
    logText() {
      return this.replyHandler.log.join('\n');
    },
    autoRunLimit() {
      const config = SHOPEE_AUTO_RUN_LIMITS.replyRating[this.getUserPlan];
      if (config) {
        return config.runLimit;
      }
      return 0;
    },
    isRunLimitVisible() {
      return Number.isFinite(this.autoRunLimit) && this.autoRunLimit > 0;
    },
    isRunLimitReached() {
      return this.isRunLimitVisible && this.replyHandler.sent >= this.autoRunLimit;
    },
  },
};
</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;
  }

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

  .variables-card,
  .config-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;
  }

  .variables-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 16px;
  }

  .variable-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
  }

  .variable-tag {
    font-family: 'Courier New', monospace;
    font-weight: 600;
  }

  .variable-description {
    color: #666;
    font-size: 14px;
  }

  .form-textarea {
    resize: vertical;
    min-height: 80px;
  }

  .form-help-text {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }

  .action-button {
    width: 100%;
    height: 40px;
    font-weight: 600;
  }

  .log-container {
    position: relative;
  }

  .log-textarea {
    font-family: 'Courier New', monospace;
    font-size: 13px;
    line-height: 1.4;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
  }

  .text-muted {
    color: #999;
  }

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

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

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