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

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

        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;
                this.setData({
                    newPlantImage: tempFilePath,
                    isLocalImage: true
                });
            },
            fail: (err) => {
                console.log('User cancelled', err);
            }
        });
    },

    // 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() {
        if (!this.data.newPlantName) {
            wx.showToast({ title: '请输入植物名称', icon: 'none' });
            return;
        }

        const newId = (MOCK_PLANTS.length + 1).toString();
        const adoption = new Date(this.data.newPlantDate);
        const today = new Date();
        const diffTime = Math.abs(today.getTime() - adoption.getTime());
        const daysPlanted = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        // Prepare care schedule with icon info
        const careSchedule = this.data.newCareTasks.map(task => ({
            id: task.id,
            taskName: task.taskName,
            frequencyValue: task.frequencyValue,
            frequencyUnit: task.frequencyUnit,
            iconId: task.iconId,
            taskIcon: task.taskIcon
        }));

        const newPlant = {
            id: newId,
            name: this.data.newPlantName,
            images: [this.data.newPlantImage || 'monstera_plant_1769757312755.png'],
            daysPlanted: daysPlanted,
            adoptionDate: this.data.newPlantDate,
            location: this.data.newPlantLocation || '未分配位置',
            scientificName: 'Unknown',
            family: '未知科',
            genus: '未知属',
            description: '新添加的植物...',
            difficulty: '⭐️',
            toxicity: '未知',
            flowerMsg: '充满希望',
            careSchedule: careSchedule
        };

        // In a real app we would call an API or update global store
        // For this mock, we append to the imported array (memory only)
        MOCK_PLANTS.push(newPlant);

        wx.showToast({ title: '添加成功', icon: 'success' });

        setTimeout(() => {
            wx.navigateBack();
        }, 1000);
    }
})
