<template>
  <div
    v-if="visible"
    class="uikit-modal-mask"
    @click.self="handleMaskClick"
  >
    <div :class="modalContainerClass">
      <div class="uikit-modal-header">
        <Icon
          v-if="type === 'success'"
          class="uikit-modal-type-icon"
          :src="successIcon"
          :size="20"
        />
        <Icon
          v-if="type === 'info'"
          class="uikit-modal-type-icon"
          :src="infoIcon"
          :size="20"
        />
        <Icon
          v-if="type === 'error'"
          class="uikit-modal-type-icon"
          :src="errorIcon"
          :size="20"
        />
        <Icon
          v-if="type === 'warning'"
          class="uikit-modal-type-icon"
          :src="warningIcon"
          :size="20"
        />
        <span class="uikit-modal-title">{{ title }}</span>
      </div>
      <div
        class="uikit-modal-body"
        v-html="processedContent"
      />
      <div class="uikit-modal-footer">
        <button
          class="uikit-modal-btn uikit-modal-btn-cancel"
          @click="handleCancel"
        >
          {{ cancelText || 'Cancel' }}
        </button>
        <button
          class="uikit-modal-btn uikit-modal-btn-confirm"
          @click="handleConfirm"
        >
          {{ confirmText || 'Confirm' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, PropType } from '../../../../adapter-vue';
import Icon from '../../base/Icon/Icon.vue';
import { IS_PC } from '../../base/util';
import { t } from '../../../../TUICallService';
import successIcon from '../../../assets/base/success.svg';
import infoIcon from '../../../assets/base/info.svg';
import errorIcon from '../../../assets/base/error.svg';
import warningIcon from '../../../assets/base/waring.svg';

export default defineComponent({
  name: 'UIKitModal',
  components: {
    Icon,
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    id: {
      type: Number,
      required: true,
    },
    title: {
      type: String,
      required: true,
    },
    content: {
      type: [String, Object] as PropType<string | any>,
      required: true,
    },
    type: {
      type: String as PropType<'info' | 'warning' | 'error' | 'success'>,
      required: true,
    },
    onConfirm: {
      type: Function as PropType<(() => void) | undefined>,
      default: undefined,
    },
    onCancel: {
      type: Function as PropType<(() => void) | undefined>,
      default: undefined,
    },
  },
  emits: ['confirm', 'cancel'],
  setup(props, { emit }) {
    const isPC = IS_PC;

    const cancelText = computed(() => t('reject'));
    const confirmText = computed(() => t('accept'));

    const URL_REGEX = /^(https?:\/\/)?([da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/i;
    const FULL_URL_REGEX = /(https?:\/\/[^\s]+)/g;

    const modalContainerClass = computed(() => {
      const classes = ['uikit-modal-default', 'uikit-modal-container'];
      if (!isPC) {
        classes.push('uikit-modal-container-mobile');
      }
      return classes.join(' ');
    });

    const processedContent = computed(() => {
      const { content } = props;

      if (!content || typeof content !== 'string') {
        return content;
      }

      if (URL_REGEX.test(content.trim())) {
        const url = content.trim();
        const href = url.startsWith('http') ? url : `https://${url}`;
        return `<a href="${escapeHtml(href)}" target="_blank" rel="noopener noreferrer" class="uikit-modal-link">${escapeHtml(url)}</a>`;
      }

      if (content.includes('<a ') || content.includes('<a>')) {
        return processAnchorTags(content);
      }

      if (FULL_URL_REGEX.test(content)) {
        return escapeHtml(content).replace(FULL_URL_REGEX, url => `<a href="${url}" target="_blank" rel="noopener noreferrer" class="uikit-modal-link">${url}</a>`);
      }

      return escapeHtml(content);
    });

    function escapeHtml(text: string): string {
      const div = document.createElement('div');
      div.textContent = text;
      return div.innerHTML;
    }

    function processAnchorTags(content: string): string {
      const parser = new DOMParser();
      const doc = parser.parseFromString(content, 'text/html');
      const anchors = doc.querySelectorAll('a');
      anchors.forEach((anchor) => {
        const href = anchor.getAttribute('href');
        if (href) {
          anchor.setAttribute('target', '_blank');
          anchor.setAttribute('rel', 'noopener noreferrer');
          anchor.classList.add('uikit-modal-link');
          const originalText = anchor.textContent || '';
          anchor.innerHTML = `<span style="padding: 0 0.2em; display: inline-block;">${originalText}</span>`;
        }
      });

      return doc.body.innerHTML;
    }

    function handleMaskClick() {
      handleConfirm();
    }

    function handleConfirm() {
      props.onConfirm?.();
      emit('confirm');
    }

    function handleCancel() {
      props.onCancel?.();
      emit('cancel');
    }

    return {
      successIcon,
      infoIcon,
      errorIcon,
      warningIcon,
      cancelText,
      confirmText,
      modalContainerClass,
      processedContent,
      handleMaskClick,
      handleConfirm,
      handleCancel,
    };
  },
});
</script>

<style lang="scss" scoped>
.uikit-modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.6);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.uikit-modal-default {
  width: 480px;
  max-width: calc(100% - 40px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
}

.uikit-modal-container {
  box-sizing: border-box;
  background: #fff;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 24px;
  border-radius: 20px;
}

.uikit-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;

  .uikit-modal-type-icon {
    margin-right: 6px;
  }
}

.uikit-modal-title {
  font-size: 16px;
  line-height: 24px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.uikit-modal-body {
  flex: 1;
  display: block;
  font-size: 14px;
  font-weight: 400;
  line-height: 22px;
  color: #333;
  word-break: break-word;

  ::v-deep .uikit-modal-link {
    color: #006eff;
    text-decoration: none;
    transition: all 0.2s ease;
    cursor: pointer;
    border-bottom: 1px solid transparent;
    margin: 0 0.2em;
  }
}

.uikit-modal-footer {
  padding-top: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.uikit-modal-btn {
  min-width: 88px;
  height: 32px;
  padding: 0 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
  outline: none;
  white-space: nowrap;

  &:active {
    transform: scale(0.98);
  }
}

.uikit-modal-btn-cancel {
  background: #F0F2F9;
  color: #333;

  &:hover {
    background: #e5e7ed;
  }
}

.uikit-modal-btn-confirm {
  background: #1c66e5;
  color: #fff;

  &:hover {
    background: #1557cc;
  }
}

.uikit-modal-header:empty,
.uikit-modal-body:empty,
.uikit-modal-footer:empty {
  padding: 0;
}

.uikit-modal-container-mobile {
  border-radius: 12px;
  max-width: calc(100% - 32px);
  padding: 0;

  .uikit-modal-header {
    padding: 20px 20px 16px;
    justify-content: flex-start;
    padding-bottom: 16px;
  }

  .uikit-modal-body {
    padding: 0 20px 20px;
    justify-content: flex-start;
  }

  .uikit-modal-footer {
    padding: 0;
    border-top: 0.5px solid #e5e5e5;
    gap: 0;

    .uikit-modal-btn {
      flex: 1;
      border-radius: 0;
      height: 56px;
      min-width: auto;
      background: #fff;
      font-size: 17px;

      &:active {
        transform: none;
        background: #f5f5f5;
      }

      &:hover {
        background: #fff;
      }
    }

    .uikit-modal-btn-cancel {
      color: #666;

      &:first-child:last-child {
        border-radius: 0 0 12px 12px;
      }
    }

    .uikit-modal-btn-confirm {
      color: #1c66e5;
      border-left: 0.5px solid #e5e5e5;
      font-weight: 600;
    }
  }
}
</style>
