<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { NButton, NCard, NDivider, NIcon, NModal, NResult, NSelect, NSwitch, NForm, NFormItem, NInput, NGrid, NGridItem, NSkeleton, NPopconfirm, type FormRules } from 'naive-ui'
import { SaveOutline, ArrowUpCircleOutline, LockClosedOutline, LogOutOutline, CardOutline, CloseOutline, CloseCircleOutline, RefreshOutline } from '@vicons/ionicons5'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../../stores/auth'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'
import { useVerification } from '../../composables/useVerification'
import { trackAction } from '../../composables/useAnalytics'

const router = useRouter()
const auth = useAuthStore()
const toast = useToast()
const ver = useVerification(toast)

const showUpgrade = ref(false)
const upgradeSuccess = ref(false)
const targetPlan = ref('pro')
interface PlanInfo {
  plan: string
  plan_key: string
  usage?: {
    saved_items: number
    saved_limit: number
    api_quota: number
  }
  [key: string]: unknown
}

const planInfo = ref<PlanInfo | null>(null)
const loadingPlan = ref(true)
const profileForm = ref({ display_name: auth.user?.display_name || '', title: auth.user?.title || '', phone: auth.user?.phone || '' })
const profileFormRef = ref()
const profileRules: FormRules = {
  display_name: { required: true, message: '请输入称呼', trigger: 'blur' },
}
const notifyForm = ref({ notify_email: true, digest_frequency: 'daily' })
const notifySaving = ref(false)
const deactivated = ref(false)
const profileSaving = ref(false)
const profileSaved = ref(false)
const emailVerifyCode = ref('')
const phoneInput = ref('')
const phoneVerifyCode = ref('')

// 支付轮询状态
const showWechatPay = ref(false)
const qrLoading = ref(false)
const codeUrl = ref('')
const orderId = ref('')
const payStatus = ref<'pending' | 'paid' | 'expired' | 'cancelled'>('pending')
const paymentError = ref('')
let pollTimer: ReturnType<typeof setInterval> | null = null

onMounted(async () => {
  try {
    const { data } = await api.get('/auth/me')
    if (data.notify_email !== undefined) notifyForm.value.notify_email = data.notify_email
    if (data.digest_frequency) notifyForm.value.digest_frequency = data.digest_frequency
  } catch { toast.warning('加载通知偏好失败，将使用默认值') }
  try { const { data } = await api.get('/subscriptions/my-plan'); planInfo.value = data } finally { loadingPlan.value = false }
})
onBeforeUnmount(() => { if (pollTimer) { clearInterval(pollTimer); pollTimer = null } })

const digestOptions = [
  { label: '每天', value: 'daily' },
  { label: '每周', value: 'weekly' },
  { label: '不发送', value: 'never' },
]

async function saveNotifyPrefs() {
  notifySaving.value = true
  try {
    await api.put('/auth/me', notifyForm.value)
    trackAction('settings_change', 'setting', 'notify_prefs', { settings: JSON.stringify(notifyForm.value) } as any)
    toast.success('通知偏好已保存')
  } catch (e) { toast.apiError(e, '保存失败') }
  finally { notifySaving.value = false }
}

const planOptions = [
  { label: 'Pro（¥35/月）— AI摘要+高级导出', value: 'pro' },
  { label: 'Team（¥70/人/月）— 团队协作+审批流', value: 'team' },
]

async function createPayment() {
  qrLoading.value = true
  showWechatPay.value = true
  codeUrl.value = ''
  payStatus.value = 'pending'
  paymentError.value = ''
  try {
    const { data } = await api.post('/subscriptions/wechat-pay/create', null, { params: { plan: targetPlan.value } })
    orderId.value = data.order_id
    codeUrl.value = data.code_url
    // 开始轮询
    pollTimer = setInterval(pollPaymentStatus, 3000)
  } catch (e) {
    toast.apiError(e, '创建支付订单失败')
    showWechatPay.value = false
  } finally {
    qrLoading.value = false
  }
}

async function pollPaymentStatus() {
  if (!orderId.value) return
  try {
    const { data } = await api.get(`/subscriptions/payment/${orderId.value}/status`)
    payStatus.value = data.status
    if (data.status === 'paid') {
      clearInterval(pollTimer!)
      pollTimer = null
      upgradeSuccess.value = true
      // 刷新方案信息
      const { data: planData } = await api.get('/subscriptions/my-plan')
      planInfo.value = planData
      if (auth.currentTenant) auth.currentTenant.plan_type = targetPlan.value
      // 延迟关闭支付弹窗
      setTimeout(() => { showWechatPay.value = false }, 1500)
    } else if (data.status === 'cancelled' || data.status === 'expired') {
      clearInterval(pollTimer!)
      pollTimer = null
      paymentError.value = data.status === 'expired' ? '订单已过期，请重新创建' : '订单已取消'
    }
  } catch {
    // 网络错误不中断轮询
  }
}

const MOCK_PAID_ENABLED = import.meta.env.DEV

async function mockPaid() {
  if (!orderId.value) return
  try {
    await api.post(`/subscriptions/payment/${orderId.value}/mock-paid`)
    await pollPaymentStatus()
  } catch (e) {
    toast.apiError(e, '模拟支付失败')
  }
}

function closeUpgrade() {
  showUpgrade.value = false
  upgradeSuccess.value = false
  closePayment()
}

function closePayment() {
  showWechatPay.value = false
  if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
}

async function handleDeactivate() {
  try { await api.post('/auth/deactivate', { confirm: true }); deactivated.value = true; setTimeout(() => auth.logout(), 2000) }
  catch (e) { toast.apiError(e, '注销账号失败') }
}

async function saveProfile() {
  try { await profileFormRef.value?.validate() } catch { return }
  profileSaving.value = true; profileSaved.value = false
  try { await api.put('/auth/me', profileForm.value); trackAction('settings_change', 'setting', 'profile'); if (auth.user) { auth.user.display_name = profileForm.value.display_name; auth.user.title = profileForm.value.title }; profileSaved.value = true }
  catch (e) { toast.apiError(e, '保存资料失败') } finally { profileSaving.value = false }
}
</script>

<template>
  <div style="max-width:1400px;margin:0 auto;padding:24px" class="settings-container">
    <h2 style="margin-bottom:24px">⚙️ 帐户设置</h2>

    <!-- 个人资料 -->
    <NCard title="👤 个人资料" size="small" style="margin-bottom:20px">
      <NForm ref="profileFormRef" :model="profileForm" :rules="profileRules" label-placement="left" label-width="60" size="small">
        <n-grid :cols="2" :x-gap="16">
          <n-grid-item><NFormItem path="display_name" label="称呼"><NInput v-model:value="profileForm.display_name" /></NFormItem></n-grid-item>
          <n-grid-item><NFormItem label="邮箱"><div style="line-height:34px;font-size:14px;color:var(--text-secondary)">{{ auth.user?.email }}</div></NFormItem></n-grid-item>
        </n-grid>
        <n-grid :cols="2" :x-gap="16">
          <n-grid-item><NFormItem label="职称"><NInput v-model:value="profileForm.title" placeholder="如：主任医师" /></NFormItem></n-grid-item>
          <n-grid-item><NFormItem label="手机"><NInput v-model:value="profileForm.phone" placeholder="选填" /></NFormItem></n-grid-item>
        </n-grid>
        <NButton type="primary" size="small" :loading="profileSaving" @click="saveProfile" class="sky-btn">
        <template #icon><NIcon size="14"><SaveOutline /></NIcon></template>
        保存资料
      </NButton>
        <span v-if="profileSaved" style="color:#18a058;margin-left:8px;font-size:12px">已保存 ✓</span>
      </NForm>
    </NCard>

    <!-- 方案信息 -->
    <NCard title="💳 订阅方案" size="small" style="margin-bottom:20px">
      <NSkeleton v-if="loadingPlan" text :repeat="2" />
      <template v-if="planInfo">
        <n-grid :cols="3" :x-gap="12" style="margin-bottom:12px" class="plan-stats-grid">
          <n-grid-item><div style="font-size:13px;color:var(--text-secondary)">当前方案</div><div style="font-size:16px;font-weight:700;color:#1a5276">{{ planInfo.plan || 'Free' }}</div></n-grid-item>
          <n-grid-item><div style="font-size:13px;color:var(--text-secondary)">已收藏文献</div><div style="font-size:16px;font-weight:700">{{ planInfo.usage?.saved_items || 0 }} / {{ planInfo.usage?.saved_limit ? planInfo.usage?.saved_limit : '无限' }}</div></n-grid-item>
          <n-grid-item><div style="font-size:13px;color:var(--text-secondary)">API 日配额</div><div style="font-size:16px;font-weight:700">{{ planInfo.usage?.api_quota ? planInfo.usage?.api_quota : '无限' }}</div></n-grid-item>
        </n-grid>
      </template>
      <NButton type="primary" ghost size="small" @click="showUpgrade = true" v-if="planInfo && (planInfo.plan_key === 'free' || planInfo.plan_key === 'pro')" class="sky-btn">
        <template #icon><NIcon size="14"><ArrowUpCircleOutline /></NIcon></template>
        升级方案 →
      </NButton>
      <NButton size="small" @click="router.push('/app/settings/interests')" style="margin-left:8px" class="sky-btn">🎯 编辑关注领域</NButton>
    </NCard>

    <!-- 通知偏好 -->
    <NCard title="🔔 通知偏好" size="small" style="margin-bottom:20px">
      <NForm label-placement="left" label-width="80" size="small">
        <NFormItem label="邮件通知">
          <NSwitch v-model:value="notifyForm.notify_email" />
        </NFormItem>
        <NFormItem label="摘要频率">
          <NSelect v-model:value="notifyForm.digest_frequency" :options="digestOptions" style="width:120px" />
        </NFormItem>
        <NButton size="small" type="primary" :loading="notifySaving" @click="saveNotifyPrefs" class="sky-btn">
          <template #icon><NIcon size="14"><SaveOutline /></NIcon></template>
          保存偏好
        </NButton>
      </NForm>
    </NCard>

    <!-- 安全 -->
    <NCard title="🔐 安全" size="small" style="margin-bottom:20px">
      <div style="margin-bottom:12px">
        <NButton size="small" @click="router.push('/auth/forgot-password')" class="sky-btn">
          <template #icon><NIcon size="14"><LockClosedOutline /></NIcon></template>
          修改密码
        </NButton>
      </div>

      <!-- 邮箱验证 -->
      <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-top:1px solid var(--border-color)" class="security-row">
        <div>
          <span style="font-size:13px;font-weight:500">邮箱验证</span>
          <div style="font-size:12px;color:var(--text-muted);margin-top:2px">{{ auth.user?.email }}</div>
        </div>
        <div v-if="ver.emailVerified.value" style="color:#18a058;font-size:12px">已验证 ✓</div>
        <div v-else style="display:flex;gap:8px;align-items:center" class="verify-actions">
          <NButton class="sky-btn" size="tiny" :loading="ver.sendingEmail.value" @click="ver.sendEmailCode()" :disabled="ver.emailCountdown.value > 0">
            {{ ver.emailCountdown.value > 0 ? `${ver.emailCountdown.value}s` : '发送验证码' }}
          </NButton>
          <NInput v-if="ver.emailCodeSent.value" v-model:value="emailVerifyCode" size="small" placeholder="6位验证码" style="width:100px" />
          <NButton class="sky-btn" v-if="ver.emailCodeSent.value" size="tiny" type="primary" @click="() => ver.verifyEmail(emailVerifyCode)">验证</NButton>
        </div>
      </div>

      <!-- 手机验证 -->
      <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-top:1px solid var(--border-color)" class="security-row">
        <div>
          <span style="font-size:13px;font-weight:500">手机验证</span>
          <div style="font-size:12px;color:var(--text-muted);margin-top:2px">{{ profileForm.phone || '未设置' }}</div>
        </div>
        <div v-if="ver.phoneVerified.value" style="color:#18a058;font-size:12px">已验证 ✓</div>
        <div v-else style="display:flex;gap:8px;align-items:center" class="verify-actions">
          <NInput v-model:value="phoneInput" size="small" placeholder="手机号" style="width:130px" />
          <NButton class="sky-btn" size="tiny" :loading="ver.sendingPhone.value" @click="() => ver.sendPhoneCode(phoneInput)" :disabled="ver.phoneCountdown.value > 0 || !phoneInput">
            {{ ver.phoneCountdown.value > 0 ? `${ver.phoneCountdown.value}s` : '发送验证码' }}
          </NButton>
          <NInput v-if="ver.phoneCodeSent.value" v-model:value="phoneVerifyCode" size="small" placeholder="6位验证码" style="width:100px" />
          <NButton class="sky-btn" v-if="ver.phoneCodeSent.value" size="tiny" type="primary" @click="() => ver.verifyPhone(phoneVerifyCode)">验证</NButton>
        </div>
      </div>
    </NCard>

    <NDivider />
    <NButton type="error" size="small" @click="auth.logout()" class="sky-btn">
      <template #icon><NIcon size="14"><LogOutOutline /></NIcon></template>
      退出登录
    </NButton>

    <!-- 升级方案弹窗 -->
    <NModal v-model:show="showUpgrade" title="升级方案" preset="card" style="width:450px" @update:show="(v: boolean) => { if (!v) closeUpgrade() }">
      <template v-if="!upgradeSuccess">
        <p style="margin-bottom:16px">当前：{{ planInfo?.plan || 'Free' }} →</p>
        <NSelect v-model:value="targetPlan" :options="planOptions" style="margin-bottom:16px" />
        <p style="font-size:13px;color:var(--text-muted);margin-bottom:16px;text-align:center">升级需通过微信支付完成</p>
        <NButton type="primary" block :loading="qrLoading" @click="createPayment" class="sky-btn">
          <template #icon><NIcon size="14"><CardOutline /></NIcon></template>
          微信扫码支付
        </NButton>
      </template>
      <NResult v-else status="success" title="升级成功！" description="方案已生效">
        <template #footer><NButton @click="showUpgrade = false" class="sky-btn"><template #icon><NIcon size="14"><CloseOutline /></NIcon></template>关闭</NButton></template>
      </NResult>
    </NModal>

    <!-- 微信支付二维码弹窗 -->
    <NModal v-model:show="showWechatPay" title="微信扫码支付" preset="card" style="width:400px" @update:show="(v: boolean) => { if (!v) closePayment() }">
        <p style="margin-bottom:8px">方案：<strong>{{ targetPlan === 'pro' ? 'Pro' : 'Team' }}</strong> · ¥{{ targetPlan === 'pro' ? '35' : '70' }}/月</p>

        <!-- 加载中 -->
        <NSkeleton v-if="qrLoading" width="240" height="240" style="margin:12px auto" />

        <!-- 支付成功 -->
        <div v-else-if="payStatus === 'paid'" style="padding:24px">
          <NResult status="success" title="支付成功！" description="方案已升级" size="small" />
        </div>

        <!-- 支付失败 -->
        <div v-else-if="paymentError" style="padding:24px">
          <NResult status="error" :title="paymentError" size="small">
            <template #footer>
              <NButton size="small" @click="createPayment" class="sky-btn"><template #icon><NIcon size="14"><RefreshOutline /></NIcon></template>重新支付</NButton>
            </template>
          </NResult>
        </div>

        <!-- 二维码 + 等待支付 -->
        <template v-else-if="codeUrl">
          <img
            :src="`https://api.qrserver.com/v1/create-qr-code/?size=240x240&data=${encodeURIComponent(codeUrl)}`"
            width="240" height="240" style="margin:12px auto;display:block" alt="微信支付二维码"
          />
          <p style="font-size:13px;color:var(--text-secondary);margin-bottom:4px">请使用微信扫一扫完成支付</p>
          <p style="font-size:12px;color:var(--text-muted)">支付成功后自动关闭</p>

          <!-- 开发模式模拟按钮 -->
          <NButton v-if="MOCK_PAID_ENABLED && codeUrl.includes('qrserver.com')" size="tiny" text style="margin-top:8px;color:var(--text-muted)" @click="mockPaid">
            开发模式: 模拟支付成功
          </NButton>
        </template>

        <template #footer>
          <NButton text size="small" :disabled="payStatus === 'paid'" @click="closePayment">关闭</NButton>
        </template>
    </NModal>
    <NCard title="⚠️ 危险操作" size="small" style="margin-top:20px;border:1px solid #d03050">
      <p style="font-size:13px;color:var(--text-secondary);margin-bottom:12px">注销后账号将被停用，30天内可联系管理员恢复。</p>
      <NPopconfirm @positive-click="handleDeactivate">
        <template #trigger><NButton type="error" size="small" class="sky-btn"><template #icon><NIcon size="14"><CloseCircleOutline /></NIcon></template>注销账号</NButton></template>
        确认注销账号？此操作将立即停用你的账号。
      </NPopconfirm>
      <span v-if="deactivated" style="color:#d03050;margin-left:8px;font-size:12px">账号已注销</span>
    </NCard>
  </div>
</template>

<style scoped>
@media (max-width: 768px) {
  .settings-container {
    padding: 16px !important;
  }
  .settings-container > h2 {
    font-size: 20px;
  }
  .security-row {
    flex-direction: column !important;
    align-items: flex-start !important;
    gap: 4px !important;
  }
  .verify-actions {
    flex-wrap: wrap !important;
  }
  :deep(.n-grid) {
    grid-template-columns: 1fr !important;
  }
}
</style>
