<script setup lang="ts">
import type { Dayjs } from 'dayjs';

import type {
  MemberMessageAudienceType,
  MemberMessageReachChannel,
  MemberMessageScheduleType,
} from '#/api/member/message-reach';
import type { MessageReachEditorForm } from '#/views/member/message-reach/types';

import {
  Button,
  DatePicker,
  Drawer,
  Form,
  Input,
  Select,
  Spin,
  Tag,
} from 'ant-design-vue';

import {
  MESSAGE_AUDIENCE_TAG_OPTIONS,
  MESSAGE_AUDIENCE_TYPE_OPTIONS,
  MESSAGE_REACH_CHANNEL_OPTIONS,
  MESSAGE_SCHEDULE_TYPE_OPTIONS,
} from '../composables/message-reach-page/constants';
import { formatInteger } from '../composables/message-reach-page/helpers';

defineProps<{
  audienceEstimateCount: number;
  canManage: boolean;
  estimatingAudience: boolean;
  form: MessageReachEditorForm;
  open: boolean;
  submitting: boolean;
  title: string;
}>();

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'setAudienceType', value: MemberMessageAudienceType): void;
  (event: 'setChannel', value: MemberMessageReachChannel): void;
  (event: 'setContent', value: string): void;
  (event: 'setScheduleType', value: MemberMessageScheduleType): void;
  (event: 'setScheduledAt', value: Dayjs | null): void;
  (event: 'setTitle', value: string): void;
  (event: 'submitDraft'): void;
  (event: 'submitSend'): void;
  (event: 'switchToTemplateTab'): void;
  (event: 'toggleAudienceTag', value: string): void;
}>();

const CheckableTag = Tag.CheckableTag;
const audienceTypeOptions = MESSAGE_AUDIENCE_TYPE_OPTIONS.map((item) => ({
  ...item,
}));

function handleChannelChange(
  value: MemberMessageReachChannel,
  checked: boolean,
) {
  if (!checked) {
    return;
  }
  emit('setChannel', value);
}

function handleScheduleTypeChange(
  value: MemberMessageScheduleType,
  checked: boolean,
) {
  if (!checked) {
    return;
  }
  emit('setScheduleType', value);
}
</script>

<template>
  <Drawer :open="open" :title="title" width="560" @close="emit('close')">
    <Form layout="vertical" class="mmr-editor-form">
      <Form.Item label="消息标题" required>
        <Input
          :value="form.title"
          placeholder="如：新品上线通知"
          @update:value="(value) => emit('setTitle', String(value ?? ''))"
        />
      </Form.Item>

      <Form.Item label="推送渠道" required>
        <div class="mmr-pill-group">
          <CheckableTag
            v-for="item in MESSAGE_REACH_CHANNEL_OPTIONS"
            :key="item.value"
            :checked="form.channels.includes(item.value)"
            class="mmr-pill"
            @change="(checked) => handleChannelChange(item.value, checked)"
          >
            {{ item.label }}
          </CheckableTag>
        </div>
      </Form.Item>

      <Form.Item label="目标人群" required>
        <Select
          :value="form.audienceType"
          :options="audienceTypeOptions"
          @update:value="
            (value) =>
              emit(
                'setAudienceType',
                String(value || 'all') as MemberMessageAudienceType,
              )
          "
        />

        <div v-if="form.audienceType === 'tag'" class="mmr-tag-panel">
          <div class="mmr-pill-group">
            <CheckableTag
              v-for="item in MESSAGE_AUDIENCE_TAG_OPTIONS"
              :key="item.value"
              :checked="form.audienceTags.includes(item.value)"
              class="mmr-pill"
              @change="() => emit('toggleAudienceTag', item.value)"
            >
              {{ item.label }}
            </CheckableTag>
          </div>
          <div class="mmr-reach-row">
            <Spin :spinning="estimatingAudience" size="small">
              预计触达 {{ formatInteger(audienceEstimateCount) }}人
            </Spin>
          </div>
        </div>
      </Form.Item>

      <Form.Item label="消息内容" required>
        <Input.TextArea
          :value="form.content"
          :rows="5"
          placeholder="支持变量：{name}姓名 {level}等级"
          @update:value="(value) => emit('setContent', String(value ?? ''))"
        />
        <div class="mmr-form-hint">可使用变量实现个性化推送</div>
      </Form.Item>

      <Form.Item label="发送时间" required>
        <div class="mmr-pill-group">
          <CheckableTag
            v-for="item in MESSAGE_SCHEDULE_TYPE_OPTIONS"
            :key="item.value"
            :checked="form.scheduleType === item.value"
            class="mmr-pill"
            @change="
              (checked) =>
                handleScheduleTypeChange(
                  item.value as MemberMessageScheduleType,
                  checked,
                )
            "
          >
            {{ item.label }}
          </CheckableTag>
        </div>

        <DatePicker
          v-if="form.scheduleType === 'scheduled'"
          class="mmr-scheduled-picker"
          show-time
          :value="form.scheduledAt ?? undefined"
          format="YYYY-MM-DD HH:mm"
          @update:value="
            (value) => emit('setScheduledAt', (value as Dayjs) || null)
          "
        />
      </Form.Item>

      <Form.Item class="mmr-template-link-wrap">
        <Button
          type="link"
          class="mmr-template-link"
          @click="emit('switchToTemplateTab')"
        >
          从模板选择
        </Button>
      </Form.Item>
    </Form>

    <template #footer>
      <div class="mmr-drawer-footer">
        <Button
          :disabled="!canManage || submitting"
          @click="emit('submitDraft')"
        >
          存为草稿
        </Button>
        <Button
          type="primary"
          :disabled="!canManage || submitting"
          :loading="submitting"
          @click="emit('submitSend')"
        >
          发送
        </Button>
      </div>
    </template>
  </Drawer>
</template>
