<template>
  <div>
    <Row>
        <Col
          :span="10"
          :offset="7"
        >
          <div class="text-right mb-10">
            <Button
              type="primary"
              @click="onCreate"
            >
              <i
                class="fa fa-plus mr-5"
                aria-hidden="true"
              />
              <span>{{ $t('MARKETING_SENDER_CREATE_BTN') }}</span>
            </Button>
          </div>

          <div v-if="loadingData">
            <Spin fix>
              <Icon
                type="ios-loading"
                size="18"
                class="spin-icon-load"
              />
              <div>{{ $t('LOADING_DATA') }}</div>
            </Spin>
          </div>

          <div v-else-if="!listCollect.length">
            <Alert
              type="warning"
              show-icon
            >
              {{ $t('MARKETING_SENDER_LIST_EMPTY') }}
            </Alert>
          </div>

          <List v-else>
            <ListItem
              v-for="item in listCollectShow"
              :key="item._id"
            >
              <ListItemMeta>
                <template slot="title">
                  <Tag :color="getStatusColor(item.status)">
                    {{ $t(`MARKETING_SENDER_STATUS.${item.status}`) }}
                  </Tag>
                  <span class="mr-10">
                    {{ item.title }}
                  </span>
                </template>
                <template slot="description">
                  <div class="collect-description">
                    <span
                      v-for="(desc, index) in item.descriptionItems"
                      :key="index"
                      :class="desc.color"
                    >
                      {{ desc.text }}
                      <span v-if="index < item.descriptionItems.length - 1"> | </span>
                    </span>
                  </div>
                </template>
              </ListItemMeta>

              <template #action>
                <li>
                  <Button
                    :disabled="item.isDisabled"
                    type="text"
                    size="small"
                    @click="openPopupUrl(item.toCollect)"
                  >
                    {{ $t('COLLECT_CUSTOMERS_BTN') }}
                  </Button>
                  <span>|</span>
                  <Button
                    :disabled="item.isDisabled"
                    type="text"
                    size="small"
                    @click="openPopupUrl(item.toSend)"
                  >
                    {{ $t('SEND_MESSAGE_BTN') }}
                  </Button>
                  <span>|</span>
                  <Button
                    type="text"
                    size="small"
                    class="text-danger"
                    :disabled="item.isDisabled"
                    @click="onRemove(item)"
                  >
                    {{ $t('DELETE_BTN') }}
                  </Button>
                </li>
              </template>
            </ListItem>
          </List>
        </Col>
      </Row>

    <Modal
      v-model="popupCreate"
      :title="$t('MARKETING_SENDER_CREATE_TITLE')"
      @on-ok="handlerCreate"
      @on-cancel="onCancel"
    >
      <Form>
        <FormItem :label="$t('MARKETING_SENDER_INPUT_NAME')">
          <Input
            v-model="formCreate.name"
            type="text"
            :placeholder="$t('MARKETING_SENDER_INPUT_NAME_PLACEHOLDER')"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import {
  ShopeeMarketingSenderCollect,
  ShopeeMarketingSenderCustomer,
} from '@/models/shopee/marketing/sender';

export default {
  name: 'ShopeeAutoSendMessageIndex',
  data() {
    return {
      loadingData: false,
      listCollect: [],
      popupCreate: false,
      formCreate: {
        name: '',
      },
    };
  },
  computed: {
    listCollectShow() {
      return this.listCollect.map((item) => {
        const totalCustomers = this.$t('MARKETING_SENDER_COLUMN_TOTAL_CUSTOMERS');
        const sentCount = this.$t('MARKETING_SENDER_COLUMN_SENT_COUNT');
        const failedCount = this.$t('MARKETING_SENDER_COLUMN_FAILED_COUNT');

        const descriptionItems = [
          {
            text: `${totalCustomers}: ${item.totalCustomers || 0}`,
            color: 'text-default',
          },
          {
            text: `${sentCount}: ${item.sentCount || 0}`,
            color: 'text-v',
          },
          {
            text: `${failedCount}: ${item.failedCount || 0}`,
            color: 'text-default',
          },
        ];

        return {
          ...item,
          title: [`[${item.shopName}]`, item.name].join(' '),
          descriptionItems,
          isDisabled: item.shopId.toString() !== this.getShopeeShopId.toString(),
          toCollect: `/shopee/seller/auto/send-message/collect/${item._id}`,
          toSend: `/shopee/seller/auto/send-message/send/${item._id}`,
        };
      });
    },
  },
  methods: {
    getStatusColor(status) {
      const colorMap = {
        pending: 'warning',
        sending: 'primary',
        completed: 'success',
        failed: 'error',
      };
      return colorMap[status] || 'default';
    },
    onCreate() {
      this.formCreate.name = '';
      this.popupCreate = true;
    },
    onCancel() {
      this.formCreate.name = '';
    },
    async handlerCreate() {
      if (!this.formCreate.name || !this.formCreate.name.trim()) {
        this.$Message.error(this.$t('MARKETING_SENDER_NAME_REQUIRED'));
        return;
      }

      if (!this.getShopeeShopId) {
        this.$Message.error(this.$t('SHOP_NOT_CONNECTED'));
        return;
      }

      try {
        const payload = {
          name: this.formCreate.name.trim(),
          shopId: this.getShopeeShopId.toString(),
          shopName: this.getShopeeShopName || '',
          status: 'pending',
          totalCustomers: 0,
          sentCount: 0,
          failedCount: 0,
        };

        await ShopeeMarketingSenderCollect.insert(payload);

        this.$Message.success(this.$t('CREATE_SUCCESS'));
        this.popupCreate = false;
        this.formCreate.name = '';
        await this.getList();
      } catch (error) {
        this.$Message.error(this.$t('CREATE_ERROR'));
        this.loggerApi.error('Create marketing sender error:', error);
      }
    },
    onRemove(row) {
      this.$Modal.confirm({
        title: this.$t('REMOVE_CONFIRM'),
        content: this.$t('MARKETING_SENDER_REMOVE_CONFIRM', { name: row.name }),
        onOk: async () => {
          try {
            await ShopeeMarketingSenderCollect.removeId(row._id);

            await ShopeeMarketingSenderCustomer.removeQuery({ collectId: row._id });

            this.$Message.success(this.$t('REMOVE_SUCCESS'));
            await this.getList();
          } catch (error) {
            this.$Message.error(this.$t('REMOVE_ERROR'));
            this.loggerApi.error('Remove marketing sender error:', error);
          }
        },
      });
    },
    async getList() {
      this.loadingData = true;

      try {
        const shopId = this.getShopeeShopId?.toString();

        if (!shopId) {
          this.listCollect = [];
          this.loadingData = false;
          return;
        }

        const listData = await ShopeeMarketingSenderCollect.findMany({ shopId }, 1000, 0);

        this.listCollect = listData
          .map((item) => ({
            ...item,
          }))
          .sort((a, b) => {
            const timeA = a.createdAt || 0;
            const timeB = b.createdAt || 0;
            return timeB - timeA;
          });
      } catch (error) {
        this.$Message.error(this.$t('ERROR_GET_DATA'));
        this.loggerApi.error('Get marketing sender list error:', error);
      } finally {
        this.loadingData = false;
      }
    },
  },
  created() {
    this.getList();

    ShopeeMarketingSenderCollect.syncRemote();
    ShopeeMarketingSenderCustomer.syncRemote();
  },
};
</script>

<style scoped>
  .collect-description {
    font-size: 13px;
  }

  .collect-description .text-default {
    color: #808695;
  }

  .collect-description .text-success {
    color: #19be6b;
  }

  .collect-description .text-error {
    color: #ed4014;
  }
</style>
