// pages/garden/add/index.js
import { CARE_TASK_ICONS } from '../../../utils/constant';
import request from '../../../utils/request';
import { requestSubscription, checkSubscriptionSettings } from '../../../utils/subscribe';

Page({
    data: {
        newPlantName: '',
        newPlantLocation: '',
        newPlantDate: '',
        newPlantImage: null,
        isLocalImage: false,
        newCareTasks: [],
        scrollIntoViewId: '',

        uploadedImageId: '', // Store the uploaded image ID

        // Extra fields
        potMaterial: '',
        potSize: '',
        sunlight: '',
        plantingMaterial: '',

        showActionSheet: false,
        actionSheetItems: [
            { label: '拍照', value: 'camera' },
            { label: '从相册选取', value: 'album' }
        ],

        // Icon picker
        careTaskIcons: [],
        showIconPicker: false,
        currentEditingTaskId: null
    },

    onLoad() {
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');

        // Default care task with water icon
        const defaultIcon = CARE_TASK_ICONS.find(i => i.id === 'water');

        this.setData({
            newPlantDate: `${year}-${month}-${day}`,
            newCareTasks: [{
                id: Date.now().toString(),
                taskName: '浇水',
                frequencyValue: 7,
                frequencyUnit: 'day',
                iconId: 'water',
                taskIcon: defaultIcon
            }],
            careTaskIcons: CARE_TASK_ICONS
        });
    },

    handleBack() {
        wx.navigateBack();
    },

    // Action Sheet Logic
    showActionSheet() {
        this.setData({ showActionSheet: true });
    },

    onActionSheetCancel() {
        this.setData({ showActionSheet: false });
    },

    onActionSheetSelected(e) {
        const { value } = e.detail.selected;
        this.handleImageUpload(value);
        this.setData({ showActionSheet: false });
    },

    handleImageUpload(sourceType) {
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: [sourceType], // 'camera' or 'album'
            camera: 'back',
            success: (res) => {
                const tempFilePath = res.tempFiles[0].tempFilePath;

                // 1. Show temp image immediately for UX
                this.setData({
                    newPlantImage: tempFilePath,
                    isLocalImage: true
                });

                // Show loading
                wx.showLoading({ title: '上传中...' });

                // Call upload API
                request.upload(tempFilePath).then(data => {
                    wx.hideLoading();

                    // request.js unwraps data, response is flat FileInfo {id, url, name, ...}
                    const imageUrl = data?.url || '';
                    const imageId = data?.id || '';

                    if (imageUrl && imageId) {
                        this.setData({
                            newPlantImage: imageUrl,
                            uploadedImageId: imageId,
                            isLocalImage: true
                        });

                    }
                }).catch(err => {
                    wx.hideLoading();
                    wx.showToast({ title: '上传失败', icon: 'none' });
                });
            },
            fail: (err) => {
                // User cancelled or error
            }
        });
    },

    // Form Handlers
    onNameInput(e) { this.setData({ newPlantName: e.detail.value }); },
    onLocationInput(e) { this.setData({ newPlantLocation: e.detail.value }); },
    onDateChange(e) { this.setData({ newPlantDate: e.detail.value }); },

    // Extra field inputs
    onPotMaterialInput(e) { this.setData({ potMaterial: e.detail.value }); },
    onPotSizeInput(e) { this.setData({ potSize: e.detail.value }); },
    onSunlightInput(e) { this.setData({ sunlight: e.detail.value }); },
    onPlantingMaterialInput(e) { this.setData({ plantingMaterial: e.detail.value }); },

    handleAddCareTask() {
        const tasks = this.data.newCareTasks;
        const defaultIcon = CARE_TASK_ICONS.find(i => i.id === 'other');

        tasks.push({
            id: Date.now().toString(),
            taskName: '',
            frequencyValue: 1,
            frequencyUnit: 'day',
            iconId: 'other',
            taskIcon: defaultIcon
        });

        // First clear the scrollIntoViewId, then set it to trigger scroll
        this.setData({
            newCareTasks: tasks,
            scrollIntoViewId: ''
        }, () => {
            // Use setTimeout to ensure the DOM has updated before scrolling
            setTimeout(() => {
                this.setData({ scrollIntoViewId: 'care-list-bottom' });
            }, 50);
        });
    },

    handleRemoveCareTask(e) {
        const id = e.currentTarget.dataset.id;
        const tasks = this.data.newCareTasks.filter(t => t.id !== id);
        this.setData({ newCareTasks: tasks });
    },

    onTaskNameInput(e) {
        const { id } = e.currentTarget.dataset;
        const tasks = this.data.newCareTasks.map(t => t.id === id ? { ...t, taskName: e.detail.value } : t);
        this.setData({ newCareTasks: tasks });
    },

    onTaskFreqInput(e) {
        const { id } = e.currentTarget.dataset;
        const raw = e.detail.value;
        // Allow empty while editing; validate on save
        const tasks = this.data.newCareTasks.map(t => {
            if (t.id === id) {
                return { ...t, frequencyValue: raw === '' ? '' : (parseInt(raw) || '') };
            }
            return t;
        });
        this.setData({ newCareTasks: tasks });
    },

    // Icon Picker
    showIconPickerForTask(e) {
        const taskId = e.currentTarget.dataset.id;
        this.setData({
            showIconPicker: true,
            currentEditingTaskId: taskId
        });
    },

    hideIconPicker() {
        this.setData({
            showIconPicker: false,
            currentEditingTaskId: null
        });
    },

    selectIcon(e) {
        const iconId = e.currentTarget.dataset.iconid;
        const { currentEditingTaskId, careTaskIcons, newCareTasks } = this.data;

        const selectedIcon = careTaskIcons.find(i => i.id === iconId);

        if (selectedIcon && currentEditingTaskId) {
            const updatedTasks = newCareTasks.map(t => {
                if (t.id === currentEditingTaskId) {
                    return {
                        ...t,
                        iconId: iconId,
                        taskIcon: selectedIcon,
                        // Auto-fill task name if empty
                        taskName: t.taskName || selectedIcon.name
                    };
                }
                return t;
            });

            this.setData({
                newCareTasks: updatedTasks,
                showIconPicker: false,
                currentEditingTaskId: null
            });
        }
    },

    handleAddPlant() {
        const { newPlantName, newPlantLocation, newPlantDate, uploadedImageId, newCareTasks } = this.data;

        // Basic Validation
        if (!newPlantName) {
            wx.showToast({ title: '请输入植物名称', icon: 'none' });
            return;
        }
        if (!uploadedImageId) {
            wx.showToast({ title: '请先上传图片', icon: 'none' });
            return;
        }

        // Validate care task periods
        for (const task of newCareTasks) {
            const p = parseInt(task.frequencyValue);
            if (!p || p < 1) {
                wx.showToast({ title: `"${task.taskName || '未命名事项'}" 的周期天数不合法`, icon: 'none' });
                return;
            }
        }

        // Construct Care Plans
        const carePlans = newCareTasks.map(task => ({
            name: task.taskName || '未命名事项',
            period: parseInt(task.frequencyValue) || 1,
            icon: JSON.stringify(task.taskIcon || {}), // Serialize icon details
            targetAction: (task.taskIcon && task.taskIcon.targetAction) ? task.taskIcon.targetAction : ''
        }));

        // Construct Payload
        const payload = {
            name: newPlantName,
            plantTime: newPlantDate,
            placement: newPlantLocation || '',
            ossIds: [uploadedImageId],
            carePlans: carePlans,
            potMaterial: this.data.potMaterial || '',
            potSize: this.data.potSize || '',
            sunlight: this.data.sunlight || '',
            plantingMaterial: this.data.plantingMaterial || ''
        };

        // Submit
        wx.showLoading({ title: '植物种植中...' });
        request.post('/plant/add', payload).then(async () => {
            wx.hideLoading();
            wx.showToast({ title: '添加成功', icon: 'success' });

            // Smart Subscription Check
            const subStatus = await checkSubscriptionSettings();

            if (subStatus === 'accept') {
                // Already authorized 'Always', just call API to consume quota
                requestSubscription().finally(() => {
                    wx.navigateBack();
                });
            } else if (subStatus === 'reject' || subStatus === 'ban') {
                // User rejected 'Always', do not disturb
                setTimeout(() => wx.navigateBack(), 500);
            } else {
                // Not set, ask user
                wx.showModal({
                    title: '添加成功',
                    content: '是否订阅植物养护提醒？',
                    confirmText: '订阅',
                    cancelText: '暂不',
                    success: (res) => {
                        if (res.confirm) {
                            requestSubscription().finally(() => {
                                wx.navigateBack();
                            });
                        } else {
                            wx.navigateBack();
                        }
                    }
                });
            }

        }).catch(err => {
            wx.hideLoading();
            console.error('Add plant failed', err);
            // Error handling is done inside request.post, but fallback here
        });
    }
})
