<template>
  <view class="review-page" :style="{ background: themeConfig.bgColor }">
    <PageHeader
      title="今日复盘"
      :subtitle="formatDisplayDate(currentDate)"
      :show-right="true"
      :show-back="false"
    >
      <template #right>
        <view class="header-actions">
          <view class="action-btn" :style="{ background: themeConfig.cardBgColor }" @click="toggleCalendar">
            <FaIcon icon="calendar-days" :size="20" :color="themeConfig.textPrimary" />
          </view>
          <view class="action-btn" :style="{ background: themeConfig.cardBgColor }" @click="goHistory">
            <FaIcon icon="list" :size="20" :color="themeConfig.textPrimary" />
          </view>
        </view>
      </template>
    </PageHeader>

    <view class="calendar-wrap" v-if="showCalendar">
      <InlineCalendar
        :value="currentDate"
        @change="handleDateChange"
      />
    </view>

    <scroll-view class="main-content" scroll-y :show-scrollbar="false">
      <view class="content-wrap">
        <view class="loading-state" v-if="loading">
          <view class="loading-spinner" :style="{ borderTopColor: themeConfig.primaryColor }"></view>
          <text class="loading-text" :style="{ color: themeConfig.textSecondary }">加载中...</text>
        </view>

        <template v-else>
          <AppCard
            :padding="26"
            :radius="22"
            :marginBottom="20"
            :showShadow="true"
          >
            <view class="method-intro">
              <view class="intro-icon" :style="{ background: themeConfig.bgColor }">
                <FaIcon :icon="currentIntro.iconName" :size="22" :color="themeConfig.primaryColor" />
              </view>
              <view class="intro-texts">
                <text class="intro-title" :style="{ color: themeConfig.textPrimary }">{{ currentIntro.title }}</text>
                <text class="intro-desc" :style="{ color: themeConfig.textSecondary }">{{ currentIntro.desc }}</text>
              </view>
            </view>
          </AppCard>

          <view class="review-content">
            <AppCard
              v-for="(field, idx) in currentFields"
              :key="field.key"
              :padding="26"
              :radius="20"
              :marginBottom="idx < currentFields.length - 1 ? 20 : 0"
              :showShadow="true"
            >
              <view class="input-card">
                <view class="card-header">
                  <view class="card-icon-wrap" :style="{ background: getFieldBg(field.colorKey) }">
                    <FaIcon :icon="field.iconName" :size="22" :color="getProgressColor(field.colorKey)" />
                  </view>
                  <view class="card-title-wrap">
                    <text class="card-title" :style="{ color: themeConfig.textPrimary }">{{ field.title }}</text>
                    <text class="card-subtitle" :style="{ color: themeConfig.textSecondary }">{{ field.subtitle }}</text>
                  </view>
                </view>
                <view class="card-body">
                  <textarea
                    class="card-input"
                    v-model="currentData[field.key]"
                    :placeholder="field.placeholder"
                    :style="{ color: themeConfig.textPrimary }"
                    auto-height
                    :maxlength="500"
                    show-confirm-bar="{{ false }}"
                  ></textarea>
                </view>
                <view class="card-footer">
                  <view class="progress-wrap">
                    <ProgressBar
                      :percent="getProgressPercent(currentData[field.key])"
                      :height="8"
                      :color="getProgressColor(field.colorKey)"
                      :show-text="false"
                    />
                  </view>
                  <text class="word-count" :style="{ color: themeConfig.textSecondary }">
                    {{ currentData[field.key].length }}/500
                  </text>
                </view>
              </view>
            </AppCard>
          </view>
        </template>

        <view class="bottom-spacer"></view>
      </view>
    </scroll-view>

    <view class="footer-section">
      <view
        class="submit-button"
        :class="{ disabled: !canSave }"
        @click="handleSave"
        :style="{
          background: themeConfig.gradientVibrant,
          boxShadow: `0 12rpx 36rpx ${themeConfig.shadowColor}`
        }"
      >
        <view class="btn-content">
          <text class="btn-text">{{ isEdit ? '更新复盘' : '保存复盘' }}</text>
        </view>
      </view>
    </view>

    <GrowthModal
      :visible="growthModalVisible"
      :title="growthModalTitle"
      :message="growthModalMessage"
      :icon="growthModalIcon"
      :confirm-text="growthModalConfirmText"
      @close="onGrowthModalClose"
    />
  </view>
</template>

<script>
import { saveReview, getReviewByDate } from '@/api'
import growthModalMixin from '@/mixins/growthModalMixin.js'
import themeMixin from '@/mixins/themeMixin.js'
import PageHeader from '@/components/PageHeader.vue'
import InlineCalendar from '@/components/InlineCalendar.vue'
import ProgressBar from '@/components/ProgressBar.vue'
import AppCard from '@/components/AppCard.vue'
import EmptyState from '@/components/EmptyState.vue'
import GrowthModal from '@/components/GrowthModal.vue'
import FaIcon from '@/components/FaIcon.vue'
import { isLogin } from '@/utils/auth'
import { refreshNavBarTheme } from '@/utils/themeGlobal'

const REVIEW_STORAGE_PREFIX = 'review_'

export default {
  name: 'ReviewPage',
  components: {
    PageHeader,
    InlineCalendar,
    ProgressBar,
    AppCard,
    EmptyState,
    GrowthModal,
    FaIcon
  },
  mixins: [growthModalMixin, themeMixin],
  data() {
    return {
      currentDate: '',
      kptData: {
        keep: '',
        problem: '',
        try: ''
      },
      showCalendar: false,
      loading: false,
      isEdit: false,
      kptFields: [
        { key: 'keep', title: 'Keep（保持）', subtitle: '做得好的地方', iconName: 'lightbulb', colorKey: 'success', placeholder: '今天哪些做得好的地方值得保持？' },
        { key: 'problem', title: 'Problem（问题）', subtitle: '遇到的挑战', iconName: 'triangle-exclamation', colorKey: 'danger', placeholder: '今天遇到了什么问题和挑战？' },
        { key: 'try', title: 'Try（尝试）', subtitle: '改进方向', iconName: 'rocket', colorKey: 'secondary', placeholder: '明天尝试什么改进方法？' }
      ]
    }
  },
  computed: {
    currentFields() {
      return this.kptFields
    },
    currentData() {
      return this.kptData
    },
    canSave() {
      return Object.values(this.kptData).some(v => v && v.trim())
    },
    storageKey() {
      return `${REVIEW_STORAGE_PREFIX}${this.currentDate}`
    },
    currentIntro() {
      return {
        iconName: 'lightbulb',
        title: 'KPT 复盘法',
        desc: '通过记录做得好的、遇到的问题、改进方向，快速复盘成长'
      }
    }
  },
  onLoad(options) {
    if (!isLogin()) {
      uni.redirectTo({ url: '/pages/login/login' })
      return
    }
    const now = new Date()
    this.currentDate = options.date || this.formatDate(now)
    refreshNavBarTheme()
    this.loadReview()
  },
  onShow() {
    refreshNavBarTheme()
  },
  onUnload() {
    this.autoSaveDraft()
  },
  methods: {
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    formatDisplayDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const today = new Date()
      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)
      const tomorrow = new Date(today)
      tomorrow.setDate(tomorrow.getDate() + 1)

      if (date.toDateString() === today.toDateString()) {
        return '今天'
      } else if (date.toDateString() === yesterday.toDateString()) {
        return '昨天'
      } else if (date.toDateString() === tomorrow.toDateString()) {
        return '明天'
      } else {
        const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
        const month = date.getMonth() + 1
        const day = date.getDate()
        const weekDay = weekDays[date.getDay()]
        return `${month}月${day}日 ${weekDay}`
      }
    },
    getProgressPercent(text) {
      if (!text) return 0
      return Math.min(100, (text.length / 500) * 100)
    },
    getProgressColor(colorKey) {
      const colorMap = {
        success: this.themeConfig.successColor,
        danger: this.themeConfig.dangerColor,
        secondary: this.themeConfig.secondaryColor,
        primary: this.themeConfig.primaryColor,
        warning: this.themeConfig.warningColor,
        accent: this.themeConfig.accentColor
      }
      return colorMap[colorKey] || this.themeConfig.primaryColor
    },
    getFieldBg(colorKey) {
      const color = this.getProgressColor(colorKey)
      return color + '18'
    },
    toggleCalendar() {
      this.showCalendar = !this.showCalendar
    },
    handleDateChange(dateStr) {
      this.currentDate = dateStr
      this.showCalendar = false
      this.loadReview()
    },
    goHistory() {
      uni.navigateTo({ url: '/pages/review/reviewList' })
    },
    async loadReview() {
      this.loading = true

      try {
        const result = await getReviewByDate({ date: this.currentDate })

        if (result) {
          this.isEdit = true
          // Support both nested {kpt: {keep, problem, try}} and flat {keep, problem, try}
          const kptData = result.kpt || result
          this.kptData = {
            keep: kptData.keep || '',
            problem: kptData.problem || '',
            try: kptData.try || ''
          }
        }
      } catch (e) {
        console.warn('API加载复盘失败，尝试本地存储:', e)
        this.loadReviewFromLocal()
      } finally {
        this.loading = false
      }
    },
    loadReviewFromLocal() {
      try {
        const storedData = uni.getStorageSync(this.storageKey)
        if (storedData) {
          const data = JSON.parse(storedData)
          const kptData = data.kpt || data
          this.kptData = {
            keep: kptData.keep || '',
            problem: kptData.problem || '',
            try: kptData.try || ''
          }
          this.isEdit = !data.isDraft
        }
      } catch (e) {
        console.error('本地存储加载失败:', e)
      }
    },
    autoSaveDraft() {
      try {
        const dataToSave = {
          date: this.currentDate,
          method: 'kpt',
          kpt: this.kptData,
          isDraft: true,
          saveTime: new Date().toISOString()
        }
        uni.setStorageSync(this.storageKey, JSON.stringify(dataToSave))
      } catch (e) {
        console.error('保存草稿失败:', e)
      }
    },
    async handleSave() {
      if (!this.canSave) {
        uni.showToast({ title: '请填写至少一项内容', icon: 'none' })
        return
      }

      uni.showLoading({ title: '保存中...', mask: true })

      try {
        const dataToSave = {
          date: this.currentDate,
          kpt: this.kptData
        }

        const result = await saveReview(dataToSave)

        uni.hideLoading()
        uni.showToast({ title: '保存成功', icon: 'success' })

        this.isEdit = true

        if (result && (result.levelUp || (result.newAchievements && result.newAchievements.length > 0))) {
          this.showGrowthModalWithCallback(result, () => {
            setTimeout(() => uni.navigateBack(), 1500)
          })
        } else {
          this.showGrowthModal({
            type: 'review',
            exp: result && result.expGained ? result.expGained : 10,
            level: result && result.currentLevel ? result.currentLevel : null
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (e) {
        uni.hideLoading()
        console.error('保存复盘失败:', e)

        try {
          const dataToSave = {
            date: this.currentDate,
            method: 'kpt',
            kpt: this.kptData,
            isDraft: false,
            saveTime: new Date().toISOString()
          }
          uni.setStorageSync(this.storageKey, JSON.stringify(dataToSave))
          this.isEdit = true
          uni.showToast({ title: '已本地保存', icon: 'success' })
          setTimeout(() => uni.navigateBack(), 1500)
        } catch (fallbackErr) {
          console.error('本地保存也失败:', fallbackErr)
          uni.showToast({ title: '保存失败，请重试', icon: 'none' })
        }
      }
    },
    onGrowthModalClose() {
      this.growthModalVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.review-page {
  min-height: 100vh;
  position: relative;
  overflow: hidden;
}

.header-actions {
  display: flex;
  gap: 14rpx;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 18rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.25s ease;
}

.action-btn:active {
  transform: scale(0.93);
}

.action-icon {
  font-size: 32rpx;
}

.calendar-wrap {
  margin: 0 36rpx 16rpx;
}

.main-content {
  height: calc(100vh - 200rpx);
  position: relative;
  z-index: 5;
}

.content-wrap {
  padding: 0 32rpx;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  gap: 24rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f0f0f0;
  border-top-color: #333;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 26rpx;
}

.method-intro {
  display: flex;
  align-items: center;
  gap: 18rpx;
}

.intro-icon {
  width: 56rpx;
  height: 56rpx;
  border-radius: 14rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.intro-texts {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.intro-title {
  font-size: 28rpx;
  font-weight: 700;
}

.intro-desc {
  font-size: 24rpx;
  line-height: 1.5;
}

.review-content {
  display: flex;
  flex-direction: column;
}

.input-card {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 18rpx;
}

.card-icon-wrap {
  width: 60rpx;
  height: 60rpx;
  border-radius: 14rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.card-icon {
  font-size: 30rpx;
}

.card-title-wrap {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.card-title {
  font-size: 30rpx;
  font-weight: 700;
}

.card-subtitle {
  font-size: 24rpx;
}

.card-body {
  margin-bottom: 4rpx;
}

.card-input {
  width: 100%;
  min-height: 160rpx;
  font-size: 28rpx;
  line-height: 1.8;
  box-sizing: border-box;
}

.card-footer {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding-top: 12rpx;
  border-top: 1rpx solid rgba(0, 0, 0, 0.05);
}

.progress-wrap {
  flex: 1;
}

.word-count {
  font-size: 22rpx;
  font-weight: 500;
  min-width: 100rpx;
  text-align: right;
}

.footer-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 26rpx 36rpx;
  padding-bottom: calc(26rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(26rpx + env(safe-area-inset-bottom));
  background: linear-gradient(to top, rgba(248, 250, 252, 0.99) 0%, rgba(248, 250, 252, 0.9) 55%, transparent 100%);
  backdrop-filter: blur(14rpx);
  z-index: 20;
}

.submit-button {
  width: 100%;
  height: 108rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 18rpx;
  position: relative;
  overflow: hidden;
}

.submit-button.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.btn-content {
  display: flex;
  align-items: center;
  gap: 14rpx;
  position: relative;
  z-index: 1;
}

.btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
}

.btn-emoji {
  margin-left: 8rpx;
}

.bottom-spacer {
  height: 60rpx;
}
</style>