<template>
    <ParentPage active="profile">
        <view class="account-card">
            <ParentCard>
                <view class="account-row">
                    <image class="account-avatar" :src="parentAvatarUrl" mode="aspectFill" />
                    <view class="account-main">
                        <text class="nickname">{{ displayNickname }}</text>
                        <text class="current-child">当前孩子：{{ activeChild.name }} · {{ activeChild.className || '暂无年级' }}</text>
                    </view>
                </view>
            </ParentCard>
        </view>

        <view class="children-card">
            <ParentCard title="孩子管理" subtitle="切换后首页与报告将默认展示该孩子">
                <view v-if="loading" class="state-text">加载中...</view>
                <view v-else-if="!childrenList.length" class="state-text">暂无绑定孩子</view>
                <view v-else class="child-grid">
                    <view
                        v-for="(child, index) in childrenList"
                        :key="child.bindId || child.id"
                        class="child-card"
                        :class="{ active: index === activeChildIndex }"
                        @click="selectChild(index)"
                    >
                        <view class="child-title-row">
                            <text class="child-name">{{ child.name }}</text>
                            <text v-if="child.adminFlag" class="admin-tag">管理员</text>
                        </view>
                        <text class="child-account">{{ child.account }}</text>
                        <view class="child-line">{{ child.className || '暂无年级' }}</view>
                        <view v-if="canUnbind(child)" class="child-unbind" @click.stop="onUnbind(child)">
                            解绑
                        </view>
                    </view>
                </view>
                <view class="bind-actions">
                    <view class="bind-action-btn" @click="openManualBind">手动绑定</view>
                    <!-- <view class="bind-action-btn primary" @click="onScanBind">扫码绑定</view> -->
                </view>
            </ParentCard>
        </view>

        <view class="apply-card">
            <ParentCard title="绑定申请" :subtitle="`待处理 ${bindApplyList.length} 条`">
                <view v-if="applyLoading" class="state-text">加载中...</view>
                <view v-else-if="!bindApplyList.length" class="state-text">暂无待处理申请</view>
                <view v-else class="apply-list">
                    <view v-for="item in bindApplyList" :key="item.id" class="apply-item">
                        <view class="apply-user">
                            <image class="apply-avatar" :src="item.initiatingUserAvatar || parentAvatarUrl" mode="aspectFill" />
                            <view class="apply-user-main">
                                <text class="apply-name">{{ item.initiatingUserPhone || '未知用户' }}</text>
                                <text class="apply-time">申请于 {{ item.createTime || '--' }}</text>
                            </view>
                        </view>
                        <view class="apply-target">
                            <text v-if="item.simSerialNumber">申请绑定设备：{{ item.simSerialNumber }}</text>
                            <text v-else>申请绑定孩子：{{ item.childUserName || '--' }}（{{ identityText(item.identityType) }}）</text>
                        </view>
                        <view class="apply-actions">
                            <view class="apply-btn agree" @click="dealApply(item, true)">通过</view>
                            <view class="apply-btn reject" @click="dealApply(item, false)">拒绝</view>
                        </view>
                    </view>
                </view>
            </ParentCard>
        </view>

        <ManualBindChild
            :visible="manualBindVisible"
            @update:visible="manualBindVisible = $event"
            @success="onBindSuccess"
        />

        <view class="menu-card">
            <ParentCard>
                <view class="menu-item" @click="showAbout">
                    <text>关于我们</text>
                    <text class="menu-arrow">查看</text>
                </view>
                <view class="menu-line"></view>
                <view class="menu-item danger" @click="handleLogout">
                    <text>退出登录</text>
                </view>
            </ParentCard>
        </view>
    </ParentPage>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useParentStore } from '@/state/modules/parent';
import { useUserStore } from '@/state/modules/user';
import ParentCard from '../components/ParentCard.vue';
import ParentPage from '../components/ParentPage.vue';
import ManualBindChild from '../components/ManualBindChild.vue';
import { scanAndGoBind } from '../utils/scanBind';
import {
    approveParentBindApply,
    getParentBindApplies,
    unbindParentChild,
    type ParentBindApplyItem,
} from '@/api/parent';
import { PARENT_TYPE_MAP } from '../utils/parentIdentity';
import type { ParentChildItem } from '@/state/modules/parent';

const DEFAULT_AVATAR = 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/logo.png';
const showBindActions = false;

const userStore = useUserStore();
const parentStore = useParentStore();
const { userInfo } = storeToRefs(userStore);
const { childrenList, activeChild, activeChildIndex, loading } = storeToRefs(parentStore);
const parentAvatarUrl = computed(() => userInfo.value.avatarUrl || DEFAULT_AVATAR);
const parentPhone = ref('');
const manualBindVisible = ref(false);
const applyLoading = ref(false);
const bindApplyList = ref<ParentBindApplyItem[]>([]);

const displayNickname = computed(() => {
    const nick = userInfo.value.nickName;
    if (nick != null && String(nick).trim() !== '') {
        return String(nick).trim();
    }
    const phone = userInfo.value.phone || parentPhone.value;
    return phone?.trim() || '--';
});

onShow(async () => {
    parentPhone.value = userInfo.value.phone || parentPhone.value;
    try {
        if (!userInfo.value.id) {
            await userStore.fetchParentUserInfo();
        }
        if (!childrenList.value.length) {
            await parentStore.fetchBindChildren(userInfo.value.id);
        }
        await fetchBindApplies();
    } catch {
        /* ignore */
    }
});

const selectChild = (index: number) => {
    parentStore.selectChildByIndex(index);
    uni.showToast({
        title: `已切换到${childrenList.value[index]?.name || '孩子'}`,
        icon: 'none',
    });
};

const openManualBind = () => {
    manualBindVisible.value = true;
};

const onScanBind = () => {
    scanAndGoBind();
};

const onBindSuccess = async () => {
    try {
        if (!userInfo.value.id) {
            await userStore.fetchParentUserInfo();
        }
        await parentStore.fetchBindChildren(userInfo.value.id);
        await fetchBindApplies();
    } catch (e: any) {
        uni.showToast({ title: e?.message || '刷新孩子列表失败', icon: 'none' });
    }
};

const canUnbind = (child: ParentChildItem) => {
    if (!childrenList.value.length) return false;
    return !!child.isSelfBind || !!child.adminFlag;
};

const onUnbind = (child: ParentChildItem) => {
    const parentId = userInfo.value.id;
    if (!parentId || !child.id) return;
    uni.showModal({
        title: '解绑确认',
        content: `确定解绑「${child.name}」吗？`,
        confirmText: '解绑',
        confirmColor: '#ef4444',
        success: async (res) => {
            if (!res.confirm) return;
            try {
                await unbindParentChild({
                    parentId,
                    childId: child.id,
                });
                uni.showToast({ title: '解绑成功', icon: 'success' });
                await parentStore.fetchBindChildren(parentId);
                await fetchBindApplies();
            } catch (e: any) {
                uni.showToast({ title: e?.message || '解绑失败', icon: 'none' });
            }
        },
    });
};

const identityText = (identityType?: number) => {
    if (!identityType) return '其他';
    return PARENT_TYPE_MAP[identityType] || '其他';
};

const fetchBindApplies = async () => {
    applyLoading.value = true;
    try {
        const res = await getParentBindApplies();
        bindApplyList.value = res.data || [];
    } catch (e: any) {
        bindApplyList.value = [];
        uni.showToast({ title: e?.message || '绑定申请加载失败', icon: 'none' });
    } finally {
        applyLoading.value = false;
    }
};

const dealApply = (item: ParentBindApplyItem, approvalFlag: boolean) => {
    const action = approvalFlag ? '通过' : '拒绝';
    const target = item.simSerialNumber || item.childUserName || '该请求';
    uni.showModal({
        title: `${action}申请`,
        content: `确定${action}绑定「${target}」的申请吗？`,
        success: async (res) => {
            if (!res.confirm) return;
            try {
                await approveParentBindApply({
                    id: String(item.id || ''),
                    approvalFlag,
                    leadFlag: approvalFlag ? 0 : undefined,
                });
                uni.showToast({ title: `${action}成功`, icon: 'success' });
                await Promise.all([
                    parentStore.fetchBindChildren(userInfo.value.id),
                    fetchBindApplies(),
                ]);
            } catch (e: any) {
                uni.showToast({ title: e?.message || `${action}失败`, icon: 'none' });
            }
        },
    });
};

const showAbout = () => {
    uni.showModal({
        title: '关于灵犀学AI',
        content: '灵犀学AI为学生、老师和家长提供学习过程分析与成长陪伴。',
        showCancel: false,
    });
};

const handleLogout = () => {
    uni.showModal({
        title: '提示',
        content: '确定退出家长端吗？',
        success: async (res) => {
            if (!res.confirm) return;
            await userStore.logout();
        },
    });
};
</script>

<style lang="scss" scoped>
.account-card {
    margin-top: 28rpx;
}

.account-row {
    display: flex;
    align-items: center;
    gap: 24rpx;
}

.account-avatar {
    width: 112rpx;
    height: 112rpx;
    border-radius: 38rpx;
    flex-shrink: 0;
    background: #ecfeff;
    box-shadow: 0 12rpx 26rpx rgba(8, 145, 178, 0.22);
}

.account-main {
    flex: 1;
    min-width: 0;
}

.nickname {
    display: block;
    color: #164e63;
    font-size: 38rpx;
    font-weight: 900;
}

.current-child {
    display: block;
    margin-top: 8rpx;
    color: #64748b;
    font-size: 24rpx;
}

.children-card,
.apply-card,
.menu-card {
    margin-top: 40rpx;
}

.child-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16rpx;
}

.state-text {
    padding: 24rpx 0;
    text-align: center;
    color: #94a3b8;
    font-size: 26rpx;
}

.child-card {
    padding: 20rpx;
    border-radius: 24rpx;
    border: 2rpx solid #e2e8f0;
    background: #f8fafc;

    &.active {
        border-color: #0891b2;
        background: #ecfeff;
        box-shadow: inset 0 -3rpx 0 rgba(34, 211, 238, 0.3);
    }
}

.child-title-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12rpx;
}

.child-name {
    display: block;
    color: #164e63;
    font-size: 28rpx;
    font-weight: 900;
}

.admin-tag {
    padding: 4rpx 12rpx;
    border-radius: 999rpx;
    background: #e0f2fe;
    color: #0369a1;
    font-size: 20rpx;
    font-weight: 700;
}

.child-account {
    display: block;
    margin-top: 4rpx;
    color: #94a3b8;
    font-size: 22rpx;
}

.child-line {
    margin-top: 8rpx;
    color: #64748b;
    font-size: 22rpx;
}

.child-unbind {
    margin-top: 12rpx;
    color: #ef4444;
    font-size: 24rpx;
    font-weight: 700;
}

.bind-actions {
    display: flex;
    gap: 16rpx;
    margin-top: 18rpx;
}

.bind-action-btn {
    flex: 1;
    height: 78rpx;
    border-radius: 24rpx;
    border: 2rpx dashed #67e8f9;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #0891b2;
    font-size: 26rpx;
    font-weight: 900;

    &.primary {
        border-style: solid;
        border-color: transparent;
        color: #fff;
        background: linear-gradient(135deg, #0891b2, #06b6d4);
        box-shadow: 0 12rpx 26rpx rgba(8, 145, 178, 0.22);
    }
}

.apply-list {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
}

.apply-item {
    padding: 20rpx;
    border-radius: 24rpx;
    border: 2rpx solid #e2e8f0;
    background: #f8fafc;
}

.apply-user {
    display: flex;
    align-items: center;
    gap: 14rpx;
}

.apply-avatar {
    width: 64rpx;
    height: 64rpx;
    border-radius: 20rpx;
    background: #ecfeff;
}

.apply-user-main {
    flex: 1;
    min-width: 0;
}

.apply-name {
    display: block;
    color: #164e63;
    font-size: 26rpx;
    font-weight: 800;
}

.apply-time {
    display: block;
    margin-top: 4rpx;
    color: #94a3b8;
    font-size: 22rpx;
}

.apply-target {
    margin-top: 14rpx;
    color: #334155;
    font-size: 24rpx;
}

.apply-actions {
    display: flex;
    gap: 14rpx;
    margin-top: 16rpx;
}

.apply-btn {
    flex: 1;
    height: 72rpx;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26rpx;
    font-weight: 800;

    &.agree {
        background: linear-gradient(135deg, #0891b2, #06b6d4);
        color: #fff;
    }

    &.reject {
        border: 2rpx solid #e2e8f0;
        color: #64748b;
        background: #fff;
    }
}

.menu-card {
    padding-top: 16rpx;
    padding-bottom: 16rpx;
}

.menu-item {
    min-height: 82rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #164e63;
    font-size: 28rpx;
    font-weight: 700;

    &.danger {
        color: #ef4444;
    }
}

.menu-arrow {
    color: #94a3b8;
    font-size: 24rpx;
}

.menu-line {
    height: 2rpx;
    background: #f1f5f9;
}
</style>
