<template>
	<transition name="fade">
		<div v-if="visible" class="fixed inset-0 z-50 flex items-center justify-center bg-gray-900 bg-opacity-50 p-4"
			@click.self="close">
			<div class="relative w-full max-w-md p-8 border border-gray-100 shadow-xl rounded-xl bg-white">
				<button @click="close" aria-label="关闭"
					class="absolute top-3 right-3 text-gray-500 hover:text-gray-700 focus:outline-none">✕</button>
				<div class="text-center px-2">
					<div class="mt-2 grid grid-cols-3 gap-2">
						<button type="button" @click="switchMode('password')" class="w-full px-3 py-1.5 rounded text-sm"
							:class="mode === 'password' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'">
							账号密码登录
						</button>
						<button type="button" @click="switchMode('code')" class="w-full px-3 py-1.5 rounded text-sm"
							:class="mode === 'code' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'">
							验证码登录
						</button>
						<button type="button" @click="switchMode('register')" class="w-full px-3 py-1.5 rounded text-sm"
							:class="mode === 'register' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'">
							验证码注册
						</button>
					</div>
					<div class="mt-6 min-h-[300px]">
						<transition name="fade-slide" mode="out-in">
							<div v-if="mode === 'password'" key="password">
								<div class="space-y-4">
									<div>
										<input type="text" v-model="form.phone" maxlength="20" placeholder="手机号"
											class="appearance-none bg-transparent border border-gray-300 rounded-lg w-full px-3 py-2 text-gray-700 leading-tight focus:outline-none focus:border-blue-500">
									</div>
									<div>
										<input type="password" v-model="form.password" maxlength="20" placeholder="密码"
											class="appearance-none bg-transparent border border-gray-300 rounded-lg w-full px-3 py-2 text-gray-700 leading-tight focus:outline-none focus:border-blue-500">
									</div>
								</div>
								<div class="mt-6">
									<button @click="userLogin"
										class="w-full bg-green-500 hover:bg-green-600 text-white font-medium py-2.5 px-4 rounded-lg focus:outline-none focus:shadow-outline disabled:opacity-50 disabled:cursor-not-allowed"
										:disabled="loading || !canSubmit">
										<span v-if="!loading">立即登录</span>
										<span v-else class="inline-flex items-center justify-center gap-2">
											<svg class="w-4 h-4 animate-spin" xmlns="http://www.w3.org/2000/svg"
												fill="none" viewBox="0 0 24 24">
												<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
													stroke-width="4"></circle>
												<path class="opacity-75" fill="currentColor"
													d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
											</svg>
											登录中...
										</span>
									</button>
								</div>
							</div>
							<div v-else-if="mode === 'code'" key="code">
								<div class="space-y-4">
									<div>
										<input type="text" v-model="form.phone" maxlength="20" placeholder="手机号"
											class="appearance-none bg-transparent border border-gray-300 rounded-lg w-full px-3 py-2 text-gray-700 leading-tight focus:outline-none focus:border-blue-500">
									</div>
									<div>
										<div class="flex items-center gap-2">
											<input type="text" v-model="form.code" maxlength="6" placeholder="验证码"
												class="appearance-none bg-transparent border border-gray-300 rounded-lg w-full px-3 py-2 text-gray-700 leading-tight focus:outline-none focus:border-blue-500">
											<button type="button" @click="sendCode"
												:disabled="codeDisabled || !form.phone"
												class="ml-auto bg-blue-500 hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm px-3 py-2 rounded focus:outline-none focus:shadow-outline whitespace-nowrap flex-shrink-0 inline-flex items-center justify-center min-w-[100px]">
												{{ codeBtnText }}
											</button>
										</div>
									</div>
								</div>
								<div class="mt-6">
									<button @click="userLogin"
										class="w-full bg-green-500 hover:bg-green-600 text-white font-medium py-2.5 px-4 rounded-lg focus:outline-none focus:shadow-outline disabled:opacity-50 disabled:cursor-not-allowed"
										:disabled="loading || !canSubmit">
										<span v-if="!loading">立即登录</span>
										<span v-else class="inline-flex items-center justify-center gap-2">
											<svg class="w-4 h-4 animate-spin" xmlns="http://www.w3.org/2000/svg"
												fill="none" viewBox="0 0 24 24">
												<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
													stroke-width="4"></circle>
												<path class="opacity-75" fill="currentColor"
													d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
											</svg>
											处理中...
										</span>
									</button>
								</div>
							</div>
							<div v-else key="register">
								<div class="space-y-4">
									<div>
										<input type="text" v-model="form.phone" maxlength="20" placeholder="手机号"
											class="appearance-none bg-transparent border border-gray-300 rounded-lg w-full px-3 py-2 text-gray-700 leading-tight focus:outline-none focus:border-blue-500">
									</div>
									<div>
										<input type="text" v-model="form.name" maxlength="20" placeholder="姓名"
											class="appearance-none bg-transparent border border-gray-300 rounded-lg w-full px-3 py-2 text-gray-700 leading-tight focus:outline-none focus:border-blue-500">
									</div>
									<div>
										<input type="password" v-model="form.password" maxlength="20" placeholder="设置密码"
											class="appearance-none bg-transparent border border-gray-300 rounded-lg w-full px-3 py-2 text-gray-700 leading-tight focus:outline-none focus:border-blue-500">
									</div>
									<div>
										<div class="flex items-center gap-2">
											<input type="text" v-model="form.code" maxlength="6" placeholder="验证码"
												class="appearance-none bg-transparent border border-gray-300 rounded-lg w-full px-3 py-2 text-gray-700 leading-tight focus:outline-none focus:border-blue-500">
											<button type="button" @click="sendCode"
												:disabled="codeDisabled || !form.phone"
												class="ml-auto bg-blue-500 hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm px-3 py-2 rounded focus:outline-none focus:shadow-outline whitespace-nowrap flex-shrink-0 inline-flex items-center justify-center min-w-[100px]">
												{{ codeBtnText }}
											</button>
										</div>
									</div>
								</div>
								<div class="mt-6">
									<button @click="userLogin"
										class="w-full bg-blue-500 hover:bg-blue-600 text-white font-medium py-2.5 px-4 rounded-lg focus:outline-none focus:shadow-outline disabled:opacity-50 disabled:cursor-not-allowed"
										:disabled="loading || !canSubmit">
										<span v-if="!loading">验证码注册</span>
										<span v-else class="inline-flex items-center justify-center gap-2">
											<svg class="w-4 h-4 animate-spin" xmlns="http://www.w3.org/2000/svg"
												fill="none" viewBox="0 0 24 24">
												<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
													stroke-width="4"></circle>
												<path class="opacity-75" fill="currentColor"
													d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
											</svg>
											处理中...
										</span>
									</button>
								</div>
							</div>
						</transition>
					</div>
				</div>
			</div>
		</div>
	</transition>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { login, getVerificationCode,} from '@/api/user'
import { setToken } from '../../composables/auth'

const props = defineProps({
	modelValue: { type: Boolean, default: false }
})
const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
	get: () => props.modelValue,
	set: (val) => emit('update:modelValue', val)
})

const loading = ref(false)
const mode = ref('password')
const form = ref({
	phone: '',
	name: '',
	password: '',
	code: ''
})
const codeDisabled = ref(false)
const codeBtnText = ref('发送验证码')
let timer = null

const canSubmit = computed(() => {
	if (mode.value === 'password') {
		return form.value.phone.trim() && form.value.password.trim()
	}
	if (mode.value === 'code') {
		return form.value.phone.trim() && form.value.code.trim()
	}
	return form.value.phone.trim() && form.value.name.trim() && form.value.password.trim() && form.value.code.trim()
})

function switchMode(m) {
	mode.value = m
}
function close() {
	emit('update:modelValue', false)
}
async function sendCode() {
	if (!form.value.phone || codeDisabled.value) return
	codeDisabled.value = true
	try {
		await getVerificationCode({ phone: form.value.phone.trim() })
		ElMessage.success('验证码已发送')
		let count = 60
		codeBtnText.value = `${count}s`
		timer = setInterval(() => {
			count -= 1
			if (count <= 0) {
				clearInterval(timer)
				timer = null
				codeDisabled.value = false
				codeBtnText.value = '发送验证码'
			} else {
				codeBtnText.value = `${count}s`
			}
		}, 1000)
	} catch (e) {
		codeDisabled.value = false
		codeBtnText.value = '发送验证码'
	}
}
async function userLogin() {
	if (!canSubmit.value || loading.value) return
	loading.value = true
	try {
		if (mode.value === 'register') {
			const res = await login({
				phone: form.value.phone.trim(),
				name: form.value.name.trim(),
				password: form.value.password.trim(),
				code: form.value.code.trim()
			})
			const data = res.data
			if (data?.success) {
				ElMessage.success('注册成功')
				emit('success', res)
				emit('update:modelValue', false)
			} else {
				ElMessage.error(data?.message || '注册失败')
			}
			return
		}
		const res = await login({
			phone: form.value.phone.trim(),
			name: mode.value === 'password' ? '' : form.value.name.trim(),
			password: mode.value === 'password' ? form.value.password : '',
			code: mode.value === 'code' ? form.value.code.trim() : ''
		})
		const data = res.data
		if (data?.success) {
			try { setToken(data.data) } catch { }
			ElMessage.success('登录成功')
			emit('success', res)
			emit('update:modelValue', false)
		} else {
			ElMessage.error(data?.message || '登录失败')
		}
	} finally {
		loading.value = false
	}
}
watch(
	() => props.modelValue,
	(v) => {
		if (v) {
			form.value = { phone: '', name: '', password: '', code: '' }
			mode.value = 'password'
		} else {
			if (timer) {
				clearInterval(timer)
				timer = null
				codeDisabled.value = false
				codeBtnText.value = '发送验证码'
			}
		}
	}
)
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
	transition: opacity .2s ease;
}

.fade-enter-from,
.fade-leave-to {
	opacity: 0;
}

.fade-slide-enter-active,
.fade-slide-leave-active {
	transition: all .2s ease;
}

.fade-slide-enter-from,
.fade-slide-leave-to {
	opacity: 0;
	transform: translateY(6px);
}
</style>
