<template>
  <div class="sp-profile">
    <!-- Cover -->
    <div class="sp-profile__cover">
      <div class="sp-profile__cover-pattern" />
    </div>

    <!-- Avatar -->
    <div class="sp-profile__avatar-ring">
      <img
        v-if="image"
        :src="image"
        class="sp-profile__avatar-img"
        alt="avatar"
      >
      <div
        v-else
        class="sp-profile__avatar-fallback"
      >
        <Icon
          type="ios-person"
          size="36"
          color="#bbb"
        />
      </div>
    </div>

    <!-- Identity -->
    <div class="sp-profile__identity">
      <div class="sp-profile__name">
        {{ name || username || '—' }}
      </div>
      <div
        v-if="username && name && username !== name"
        class="sp-profile__username"
      >
        @{{ username }}
      </div>
      <div class="sp-profile__status">
        <Badge
          status="success"
          :text="$t('SHOP_INFO')"
        />
      </div>
    </div>

    <!-- Info pills -->
    <div
      v-if="isShopAuthed"
      class="sp-profile__pills"
    >
      <div
        v-if="id"
        class="sp-profile__pill"
      >
        <Icon
          type="ios-barcode-outline"
          size="13"
        />
        <span>{{ id }}</span>
      </div>
      <div
        v-if="phone"
        class="sp-profile__pill"
      >
        <Icon
          type="ios-call-outline"
          size="13"
        />
        <span>{{ phone }}</span>
      </div>
      <div
        v-if="email"
        class="sp-profile__pill"
      >
        <Icon
          type="ios-mail-outline"
          size="13"
        />
        <span>{{ email }}</span>
      </div>
    </div>

    <Divider class="sp-profile__sep" />

    <!-- Technical section -->
    <Collapse
      class="sp-profile__collapse"
      simple
    >
      <Panel name="tech">
        <Icon
          type="ios-settings-outline"
          size="13"
        />
        {{ $t('SHOP_SPCF') }} / {{ $t('SHOP_COOKIES') }}

        <template #content>
          <div class="sp-profile__tech">
            <div class="sp-profile__tech-row">
              <span class="sp-profile__tech-label">{{ $t('SHOP_SPCF') }}</span>
              <div class="sp-profile__tech-input">
                <Input
                  v-model="spcf"
                  size="small"
                  :disabled="!edit.spcf"
                  @on-change="changeSpcf"
                />
              </div>
              <Checkbox
                v-model="edit.spcf"
                size="small"
              >
                {{ $t('CHANGE_BTN') }}
              </Checkbox>
            </div>

            <div class="sp-profile__tech-row">
              <span class="sp-profile__tech-label">{{ $t('SHOP_COOKIES') }}</span>
              <div class="sp-profile__tech-input">
                <Input
                  v-model="cookie"
                  size="small"
                  :disabled="!edit.cookie"
                  @on-change="changeCookie"
                />
              </div>
              <Checkbox
                v-model="edit.cookie"
                size="small"
              >
                {{ $t('CHANGE_BTN') }}
              </Checkbox>
            </div>
          </div>
        </template>
      </Panel>
    </Collapse>

    <!-- Sync button -->
    <div
      v-if="isShopAuthed && getIsAuthed"
      class="sp-profile__sync"
    >
      <Button
        type="error"
        long
        :loading="loading"
        :disabled="loading"
        @click="createShop"
      >
        <Icon type="ios-cloud-upload-outline" />
        {{ $t('SYNC_SHOP_TO_CLOUD') }}
      </Button>
    </div>
  </div>
</template>

<script>
import Promise from 'bluebird';
import { Input } from 'view-design';
import { shopeeShopSyncSellerCreate } from '@/api/autoshopee/shopee/shop';
import { imageUrl } from '@/adapter/shopee/render/index';
import { removeKeyCookie, setKeyCookie } from '@/browser/cookies';
import { getShopeeSpcfValue, getShopeeClientCookies, getShopeeProfileClient } from '@/api/shopee/client/shop/index';
import { getShopeeSellerFallbackInfo } from '@/api/shopee/seller';
import { loggerShopee } from '@/plugins/logger';

export default {
  name: 'ShopPopup',
  data() {
    return {
      name: '',
      username: '',
      id: '',
      image: '',
      password: '',
      phone: '',
      email: '',
      spcf: '',
      cookie: '',
      edit: {
        spcf: false,
        cookie: false,
      },
      listUrl: [],
      rootDomain: '',
      loading: false,
    };
  },
  computed: {
    isShopAuthed() {
      return !!this.id;
    },
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      this.listUrl = [this.configAppApi.shopee.home, this.configAppApi.shopee.seller];
      this.rootDomain = this.configAppApi.shopee.domain;

      this.spcf = await getShopeeSpcfValue();
      this.cookie = JSON.stringify(await getShopeeClientCookies());

      const sellerData = await getShopeeProfileClient();

      if (sellerData && sellerData.shopid) {
        this.name = sellerData.display_name;
        this.username = sellerData.username;
        this.phone = sellerData.phone;
        this.email = sellerData.email;
        this.id = sellerData.shopid;
        this.image = imageUrl(sellerData.portrait);
        return;
      }

      const sellerFallback = await getShopeeSellerFallbackInfo();
      this.name = sellerFallback.shopName;
      this.username = sellerFallback.username;
      this.id = sellerFallback.shopId;
    },
    async setCookie(name, value, time = 0) {
      await Promise.mapSeries(this.listUrl, async (url) => {
        await removeKeyCookie(name, url).catch(() => {});
        await setKeyCookie(name, value, url, this.rootDomain, time).catch(() => {});
      });
    },
    async changeSpcf() {
      const value = this.spcf;
      if (value) {
        await this.setCookie('SPC_F', value).catch(() => {});
        this.reloadTabCurrent(true);
      }
    },
    async changeCookie() {
      const raw = this.cookie;
      if (!raw) {
        return;
      }
      try {
        const listCookie = JSON.parse(raw);
        await Promise.mapSeries(listCookie, async ({ name, value, expirationDate }) => {
          if (name === 'SPC_F') {
            this.spcf = value;
          }
          await this.setCookie(name, value, expirationDate).catch(() => {});
        });
        this.reloadTabCurrent(true);
      } catch (error) {
        loggerShopee.error({ msg: 'ERROR_PARSE_COOKIE', error });
      }
    },
    async createShop() {
      this.$Modal.confirm({
        render: (h) => h(Input, {
          props: {
            autofocus: true,
            placeholder: this.$t('ENTER_SHOP_PASSWORD'),
          },
          on: {
            input: (password) => {
              this.password = password;
            },
          },
        }),
        onOk: async () => {
          this.loading = true;
          try {
            const result = await shopeeShopSyncSellerCreate({
              account: this.username,
              password: this.password,
              cookies: JSON.parse(this.cookie),
              id: this.id,
              spcf: this.spcf,
            });

            if (result.success) {
              this.$Message.success(result.msg);
            } else {
              this.$Message.error(result.msg);
            }
          } catch (error) {
            loggerShopee.error({ msg: 'ERROR_CONNECT_SHOP', error });
            this.$Message.error(this.$t('SHOP_CONNECT_ERROR'));
          }
          this.loading = false;
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.sp-profile {
  position: relative;
  background: #fff;
  border-radius: 10px;
  overflow: hidden;

  &__cover {
    position: relative;
    height: 96px;
    background: linear-gradient(120deg, #ee4d2d 0%, #ff7043 50%, #ffab40 100%);
    overflow: hidden;
  }

  &__cover-pattern {
    position: absolute;
    inset: 0;
    background-image:
      radial-gradient(circle at 20% 50%, rgba(255,255,255,0.08) 0%, transparent 50%),
      radial-gradient(circle at 80% 20%, rgba(255,255,255,0.12) 0%, transparent 40%);
  }

  &__avatar-ring {
    position: relative;
    z-index: 2;
    width: 76px;
    height: 76px;
    border-radius: 50%;
    border: 4px solid #fff;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.18);
    margin: -38px auto 0;
    background: #f5f5f5;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  &__avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
  }

  &__avatar-fallback {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }

  &__identity {
    text-align: center;
    padding: 10px 16px 0;
  }

  &__name {
    font-size: 16px;
    font-weight: 700;
    color: #1a1a1a;
    line-height: 1.3;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &__username {
    font-size: 12px;
    color: #999;
    margin-top: 2px;
  }

  &__status {
    margin-top: 6px;
    display: flex;
    justify-content: center;
  }

  &__pills {
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 10px 20px 0;
  }

  &__pill {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: #555;
    background: #f7f7f7;
    border: 1px solid #eee;
    border-radius: 20px;
    padding: 4px 12px;

    i {
      color: #ee4d2d;
      flex-shrink: 0;
    }

    span {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  &__sep {
    margin: 14px 0 0 !important;
  }

  &__collapse {
    border: none !important;
    box-shadow: none !important;

    :deep(.ivu-collapse-header) {
      font-size: 12px;
      color: #888;
      padding: 6px 16px;
      border: none;
      background: transparent;
    }

    :deep(.ivu-collapse-content) {
      padding: 0;
      border: none;
    }

    :deep(.ivu-collapse-content-box) {
      padding: 8px 16px 4px;
    }

    :deep(.ivu-collapse-item) {
      border: none;
    }
  }

  &__tech {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  &__tech-row {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  &__tech-label {
    font-size: 11px;
    color: #aaa;
    width: 52px;
    flex-shrink: 0;
  }

  &__tech-input {
    flex: 1;
    min-width: 0;
  }

  &__sync {
    padding: 12px 16px 16px;
  }
}
</style>
