// pages/garden/add/index.js
import { MOCK_PLANTS, CARE_TASK_ICONS } from '../../../utils/mockData';
import request from '../../../utils/request';

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

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

        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: 'Uploading...' });

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

                    // User provided response format: { data: { file: { url: ..., id: ... } } }
                    // request.js unwraps 'data', so 'data' here is { file: { ... } }
                    const fileData = data?.file || {};
                    const imageUrl = fileData.url;
                    const imageId = fileData.id;

                    if (imageUrl && imageId) {
                        this.setData({
                            newPlantImage: imageUrl,
                            uploadedImageId: imageId,
                            isLocalImage: true
                        });
                        wx.showToast({ title: 'Success', icon: 'success' });
                    } else {
                        wx.showToast({ title: 'No URL returned', icon: 'none' });
                    }
                }).catch(err => {
                    wx.hideLoading();
                    wx.showToast({ title: 'Upload Failed', 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 }); },

    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 tasks = this.data.newCareTasks.map(t => t.id === id ? { ...t, frequencyValue: parseInt(e.detail.value) || 1 } : 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;
        }

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

        // Construct Payload
        const payload = {
            name: newPlantName,
            plantTime: newPlantDate,
            placement: newPlantLocation || '',
            ossIds: [uploadedImageId],
            carePlans: carePlans,
            // Default fields as not in UI yet
            potMaterial: '',
            potSize: '',
            sunlight: '',
            plantingMaterial: ''
        };

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

            // Refresh previous page (e.g. garden list) if needed
            // const pages = getCurrentPages();
            // const prevPage = pages[pages.length - 2];
            // if (prevPage && prevPage.onRefresh) prevPage.onRefresh();

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