<template>
  <div class="pdf-editor">
    <Row :gutter="10">
      <Col :span="8">
        <div class="control-panel">
          <div
            v-if="pdfFile"
            class="editor-controls"
          >
            <h3>{{ $t('PDF_PRINT_CONFIG.CREATE_NEW') }}</h3>

            <div class="text-controls">
              <div class="mb-20">
                <Input
                  v-model="configName"
                  :placeholder="$t('PDF_PRINT_CONFIG.ENTER_CONFIG_NAME')"
                />
              </div>
              <div class="mt-10 mb-10">
                <h3>
                  <span>{{ $t('PDF_PRINT_CONFIG.ADD_TEXT') }}</span>
                  <span style="float: right;">
                    <i-switch
                      v-model="configPayload.text.active"
                    />
                  </span>
                </h3>

                <Input
                  v-model="configPayload.text.content"
                  :placeholder="$t('PDF_PRINT_CONFIG.ENTER_TEXT')"
                />
                <div class="position-controls">
                  <Row :gutter="5">
                    <Col :span="24">
                      <div class="position-item">
                        <span class="label">{{ $t('PDF_PRINT_CONFIG.POSITION') }}:</span>
                        <Select
                          v-model="configPayload.text.position"
                          class="w-200"
                        >
                          <Option
                            v-for="option in positionOptions"
                            :key="option.value"
                            :value="option.value"
                          >
                            {{ option.emoji }} {{ $t(`PDF_PRINT_CONFIG.${option.label}`) }}
                          </Option>
                        </Select>
                      </div>
                    </Col>
                    <Col
                      :span="24"
                      class="mt-10"
                    >
                      <div class="position-item">
                        <span class="label">{{ $t('PDF_PRINT_CONFIG.FONT_SIZE') }}:</span>
                        <InputNumber
                          v-model="configPayload.text.fontSize"
                          class="w-200"
                        />
                      </div>
                    </Col>
                  </Row>
                  <div v-if="configPayload.text.position === 'custom'">
                    <Row :gutter="5">
                      <Col :span="12">
                        <div class="position-item">
                          <span class="label">{{ $t('PDF_PRINT_CONFIG.POSITION_X') }}:</span>
                          <InputNumber
                            v-model="configPayload.text.x"
                            :min="0"
                            :max="1000"
                          />
                        </div>
                      </Col>
                      <Col :span="12">
                        <div class="position-item">
                          <span class="label">{{ $t('PDF_PRINT_CONFIG.POSITION_Y') }}:</span>
                          <InputNumber
                            v-model="configPayload.text.y"
                            :min="0"
                            :max="1000"
                          />
                        </div>
                      </Col>
                    </Row>
                  </div>
                </div>
              </div>
              <div>
                <h3>
                  <span>{{ $t('PDF_PRINT_CONFIG.ADD_IMAGE') }}</span>
                  <a
                    :href="openImageUrl"
                    target="_blank"
                    class="ml-5"
                  >
                    <small>{{ $t('PDF_PRINT_CONFIG.OPEN_IMAGE_EXAMPLE') }}</small>
                  </a>
                  <span style="float: right;">
                    <i-switch
                      v-model="configPayload.image.active"
                    />
                  </span>
                </h3>

                <Row>
                  <Col
                    :span="24"
                    class="mb-10"
                  >
                    <Upload
                      action=""
                      accept="image/png,image/jpeg,image/jpg"
                      :before-upload="handleImageUpload"
                      :show-upload-list="false"
                    >
                      <Button icon="ios-image-outline">
                        {{ $t('PDF_PRINT_CONFIG.SELECT_IMAGE') }}
                      </Button>
                    </Upload>
                  </Col>
                  <Col
                    :span="24"
                  >
                    <div class="position-item">
                      <Select
                        v-model="configPayload.image.position"
                        class="w-200"
                      >
                        <Option
                          v-for="option in positionOptions"
                          :key="option.value"
                          :value="option.value"
                        >
                          {{ option.emoji }} {{ $t(`PDF_PRINT_CONFIG.${option.label}`) }}
                        </Option>
                      </Select>
                    </div>
                  </Col>
                </Row>
                <div
                  v-if="imagePreviewUrl"
                  class="image-preview"
                >
                  <img
                    :src="imagePreviewUrl"
                    alt="Preview"
                  >
                </div>
                <div class="position-controls">
                  <template v-if="configPayload.image.position === 'custom'">
                    <Row :gutter="5">
                      <Col :span="12">
                        <div class="position-item">
                          <span class="label">{{ $t('PDF_PRINT_CONFIG.POSITION_X') }}:</span>
                          <InputNumber
                            v-model="configPayload.image.x"
                            :min="0"
                            :max="1000"
                          />
                        </div>
                      </Col>
                      <Col :span="12">
                        <div class="position-item">
                          <span class="label">{{ $t('PDF_PRINT_CONFIG.POSITION_Y') }}:</span>
                          <InputNumber
                            v-model="configPayload.image.y"
                            :min="0"
                            :max="1000"
                          />
                        </div>
                      </Col>
                    </Row>
                  </template>
                  <Row :gutter="5">
                    <Col :span="12">
                      <div class="position-item">
                        <span class="label">{{ $t('PDF_PRINT_CONFIG.IMAGE_WIDTH') }}:</span>
                        <InputNumber
                          v-model="configPayload.image.width"
                          :min="10"
                          :max="1000"
                        />
                      </div>
                    </Col>
                    <Col :span="12">
                      <div class="position-item">
                        <span class="label">{{ $t('PDF_PRINT_CONFIG.IMAGE_HEIGHT') }}:</span>
                        <InputNumber
                          v-model="configPayload.image.height"
                          :min="10"
                          :max="1000"
                        />
                      </div>
                    </Col>
                  </Row>
                </div>

                <div>
                  <Row :gutter="10">
                    <Col :span="8 ">
                      <Button
                        type="info"
                        :disabled="btnDisabled"
                        @click="addContentToAllPages"
                      >
                        {{ $t('PDF_PRINT_CONFIG.PREVIEW') }}
                      </Button>
                    </Col>
                    <Col :span="16">
                      <Button
                        type="primary"
                        icon="md-save"
                        :disabled="!configName || btnDisabled"
                        @click="saveConfig"
                      >
                        {{ $t('PDF_PRINT_CONFIG.SAVE_CONFIG') }}
                      </Button>
                    </Col>
                  </Row>
                </div>
              </div>
            </div>
            <div
              v-if="listConfig.length && pdfFile"
              class="config-controls"
            >
              <h3>{{ $t('PDF_PRINT_CONFIG.SAVED_CONFIGS') }}</h3>

              <div
                class="saved-configs"
              >
                <div
                  v-for="item in listConfig"
                  :key="item._id"
                  class="config-item"
                >
                  <span class="config-name">{{ item.name }}</span>
                  <div class="config-actions">
                    <Button
                      type="primary"
                      size="small"
                      icon="md-play"
                      @click="previewConfig(item)"
                    />
                    <Button
                      type="error"
                      size="small"
                      icon="md-trash"
                      @click="deleteConfig(item)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Col>
      <Col :span="16">
        <div
          v-if="pdfPreviewUrl"
          class="pdf-preview"
        >
          <h3>{{ $t('PDF_PRINT_CONFIG.PREVIEW') }}</h3>
          <iframe
            :src="pdfPreviewUrl"
            width="100%"
            height="800"
            frameborder="0"
          />

          <div class="mt-5">
            <Row>
              <Col :span="12">
                <Select
                  v-model="selectedPlatform"
                  :placeholder="$t('SELECT_PLATFORM.PLACEHOLDER')"
                  class="w-100"
                  @on-change="loadSamplePdf"
                >
                  <Option
                    v-for="item in getListPlatform"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </Option>
                </Select>
              </Col>
              <Col
                :span="12"
                class="text-right"
              >
                <Upload
                  action=""
                  accept=".pdf"
                  :before-upload="handleFileUpload"
                  :show-upload-list="false"
                >
                  <Button icon="ios-cloud-upload-outline">
                    {{ $t('PDF_PRINT_CONFIG.SELECT_PDF') }}
                  </Button>
                </Upload>
              </Col>
            </Row>
          </div>
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { PdfService } from '@/lib/pdf/service';
import { ConfigPdfPrinter } from '@/models/config';
import { usePrinterStore } from '@/vue/pinia/printer';
import { loggerVue } from '@/plugins/logger';

const printerStore = usePrinterStore();

export default {
  name: 'PdfPrinterConfig',
  data() {
    /** @type {PrintPdfConfigOverlay} */
    const configPayload = {
      text: {
        active: true,
        content: '',
        position: 'top-center',
        x: 100,
        y: 100,
        fontSize: 20,
        isBold: true,
      },
      image: {
        active: true,
        data: null,
        base64: '',
        position: 'bottom-center',
        x: 100,
        y: 100,
        width: 180,
        height: 50,
      },
    };

    /** @type {PrintPdfConfigList[]} */
    const listConfig = [];

    const pdfService = new PdfService();

    const openImageUrl = 'https://drive.google.com/drive/u/0/folders/1btOrjBYtfLblWo6_5IpttwYmKn69edqI';

    return {
      pdfService,
      pdfFile: null,
      pdfBytes: null,
      pdfPreviewUrl: '',
      imagePreviewUrl: '',
      selectedPlatform: 'shopee',
      configName: '',
      configPayload,
      listConfig,
      positionOptions: printerStore.listPosition,
      openImageUrl,
    };
  },
  methods: {
    async handleFileUpload(file) {
      if (!file) {
        return false;
      }
      await this.pdfService.loadPdfFromFile(file);

      this.pdfFile = this.pdfService.getPdfFile();
      this.pdfBytes = this.pdfService.getPdfBytes();
      this.updatePdfPreview();
    },
    async handleImageUpload(file) {
      if (!file) {
        return false;
      }

      this.configPayload.image.data = file;
      this.configPayload.image.base64 = await this.fileToBase64(file);

      this.imagePreviewUrl = URL.createObjectURL(file);
    },
    updatePdfPreview() {
      this.pdfPreviewUrl = this.pdfService.getPdfPreviewUrl(this.pdfBytes);
    },
    async addContentToAllPages() {
      try {
        this.pdfBytes = await this.pdfService.addConfigContent(this.configPayload);

        this.updatePdfPreview();
      } catch (error) {
        loggerVue.error({
          msg: 'PDF_PREVIEW_CONFIG_ERROR',
          error,
        });

        this.$Message.error(this.$t('PDF_PRINT_CONFIG.CONTENT_ADDED_ERROR'));
      }
    },
    async loadSamplePdf(platform) {
      try {
        await this.pdfService.loadPdfFromUrl(`/platform/${platform}/order.pdf`);

        this.pdfFile = this.pdfService.getPdfFile();
        this.pdfBytes = this.pdfService.getPdfBytes();
        this.updatePdfPreview();
      } catch (error) {
        this.$Message.error(this.$t('PDF_PRINT_CONFIG.SAMPLE_LOADED_ERROR'));
      }
    },
    loadExampleConfig() {
      const imageUrl = '/example/pdf_sign.png';
      fetch(imageUrl)
        .then((res) => res.blob())
        .then((blob) => {
          const file = new File([blob], 'pdf_sign.png', { type: blob.type });
          this.handleImageUpload(file);
        }).catch((error) => {
          loggerVue.error({
            msg: 'PDF_LOAD_EXAMPLE_IMAGE_ERROR',
            error,
          });
        });
    },
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    },
    async loadSavedConfigs() {
      this.listConfig = await ConfigPdfPrinter.findAll();
    },
    async saveConfig() {
      try {
        const payloadConfig = {
          name: this.configName,
          config: this.configPayload,
        };

        payloadConfig.config.image.base64 = await this.fileToBase64(this.configPayload.image.data);

        await ConfigPdfPrinter.insert(payloadConfig);

        this.$Message.success(this.$t('PDF_PRINT_CONFIG.CONFIG_SAVED_SUCCESS'));
        this.configName = '';
        this.loadSavedConfigs();
      } catch (error) {
        loggerVue.error({
          msg: 'PDF_SAVE_CONFIG_ERROR',
          error,
        });
        this.$Message.error(this.$t('PDF_PRINT_CONFIG.CONFIG_SAVED_ERROR'));
      }
    },
    async previewConfig({ name, config }) {
      try {
        this.pdfBytes = await this.pdfService.addConfigContent(config);
        this.updatePdfPreview();
        this.$Message.success(this.$t('PDF_PRINT_CONFIG.CONFIG_APPLIED_SUCCESS', { name }));
      } catch (error) {
        loggerVue.error({
          msg: 'PDF_PREVIEW_CONFIG_ERROR',
          error,
        });
        this.$Message.error(this.$t('PDF_PRINT_CONFIG.CONFIG_APPLIED_ERROR', { name }));
      }
    },
    async deleteConfig({ _id, name }) {
      this.$Modal.confirm({
        content: name,
        title: this.$t('REMOVE_CONFIRM'),
        onOk: async () => {
          await ConfigPdfPrinter.removeId(_id);
          this.loadSavedConfigs();
          this.$Message.success(this.$t('PDF_PRINT_CONFIG.CONFIG_DELETED_SUCCESS', { name }));
        },
      });
    },
  },
  async created() {
    this.loadExampleConfig();
    this.loadSamplePdf(this.selectedPlatform);
    this.loadSavedConfigs();

    ConfigPdfPrinter.syncRemote();
  },
  computed: {
    btnDisabled() {
      if (this.configPayload.text.content || this.configPayload.image.data) {
        return false;
      }

      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
.pdf-editor {
  padding: 20px;

  .control-panel {
    position: sticky;
    top: 20px;
  }

  .upload-section {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    align-items: center;
  }

  .editor-controls {
    display: flex;
    flex-direction: column;
    gap: 20px;

    .text-controls,
    .image-controls {
      padding: 15px;
      border: 1px solid #ddd;
      border-radius: 4px;
      background-color: #fff;

      h3 {
        margin-bottom: 15px;
        color: #333;
      }

      .position-controls {
        display: flex;
        flex-direction: column;
        gap: 15px;
        margin: 15px 0;

        .position-item {
          display: inline-flex;
          align-items: center;
          gap: 10px;
          margin-right: 15px;

          .label {
            min-width: 70px;
            color: #666;
          }
        }
      }

      .ivu-btn {
        width: 100%;
        margin-top: 10px;
      }
    }
  }

  .pdf-preview {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 15px;
    background-color: #fff;
    height: 100%;

    h3 {
      margin-bottom: 15px;
      color: #333;
    }

    iframe {
      border: 1px solid #eee;
      border-radius: 4px;
      background-color: #f5f5f5;
    }
  }

  .config-controls {
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: #fff;

    h3 {
      margin-bottom: 15px;
      color: #333;
    }

    .saved-configs {
      margin-top: 20px;

      h4 {
        margin-bottom: 10px;
        color: #666;
      }

      .config-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px;
        border: 1px solid #eee;
        border-radius: 4px;
        margin-bottom: 8px;

        .config-name {
          font-size: 14px;
          color: #333;
        }

        .config-actions {
          display: flex;
          gap: 8px;
        }
      }
    }
  }

  .image-preview {
    margin: 10px 0;
    text-align: center;

    img {
      max-width: 200px;
      max-height: 200px;
      object-fit: contain;
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 5px;
    }
  }
}
</style>
