// pages/plant-detail/edit/index.js
import { MOCK_PLANTS, CARE_TASK_ICONS } from '../../../utils/mockData';

Page({
    data: {
        plantId: '',
        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(options) {
        const { id } = options;
        if (!id) {
            wx.navigateBack();
            return;
        }

        const plant = MOCK_PLANTS.find(p => p.id === id);
        if (!plant) {
            wx.showToast({ title: '植物不存在', icon: 'error' });
            setTimeout(() => wx.navigateBack(), 1500);
            return;
        }

        const defaultIcon = CARE_TASK_ICONS.find(i => i.id === 'water') || CARE_TASK_ICONS[0];

        // Deep copy tasks and ensure icons
        let tasks = plant.careSchedule ? JSON.parse(JSON.stringify(plant.careSchedule)) : [];
        tasks = tasks.map(task => {
            const icon = CARE_TASK_ICONS.find(i => i.id === task.iconId) || defaultIcon;
            return { ...task, taskIcon: icon };
        });

        // Set default date if not present (today)
        let adoptionDate = plant.adoptionDate;
        if (!adoptionDate) {
            const now = new Date();
            adoptionDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
        }

        this.setData({
            plantId: id,
            newPlantName: plant.name || '',
            newPlantLocation: plant.location || '',
            newPlantDate: adoptionDate,
            newPlantImage: plant.images && plant.images.length > 0 ? plant.images[0] : null,
            newCareTasks: tasks,
            careTaskIcons: CARE_TASK_ICONS
        });
    },

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

    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: 'back',
            success: (res) => {
                const tempFilePath = res.tempFiles[0].tempFilePath;
                this.setData({
                    newPlantImage: tempFilePath,
                    isLocalImage: true
                });
            }
        });
    },

    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') || CARE_TASK_ICONS[0];

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

        this.setData({
            newCareTasks: tasks,
            scrollIntoViewId: ''
        }, () => {
            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 });
    },

    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,
                        taskName: t.taskName || selectedIcon.name
                    };
                }
                return t;
            });

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

    handleSavePlant() {
        if (!this.data.newPlantName) {
            wx.showToast({ title: '请输入植物名称', icon: 'none' });
            return;
        }

        const plantIndex = MOCK_PLANTS.findIndex(p => p.id === this.data.plantId);
        if (plantIndex === -1) return;

        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)) || 0;

        const updatedPlant = {
            ...MOCK_PLANTS[plantIndex],
            name: this.data.newPlantName,
            location: this.data.newPlantLocation || '',
            adoptionDate: this.data.newPlantDate,
            images: [this.data.newPlantImage],
            daysPlanted: daysPlanted,
            careSchedule: this.data.newCareTasks.map(task => ({
                id: task.id,
                taskName: task.taskName,
                frequencyValue: task.frequencyValue,
                frequencyUnit: task.frequencyUnit,
                iconId: task.iconId,
                taskIcon: task.taskIcon
            }))
        };

        MOCK_PLANTS[plantIndex] = updatedPlant;

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

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

    handleDeletePlant() {
        wx.showModal({
            title: '确认删除',
            content: '确定要删除这个植物吗？删除后无法恢复。',
            confirmColor: '#EF5350',
            success: (res) => {
                if (res.confirm) {
                    const idx = MOCK_PLANTS.findIndex(p => p.id === this.data.plantId);
                    if (idx > -1) {
                        MOCK_PLANTS.splice(idx, 1);
                        wx.showToast({ title: '已删除', icon: 'success' });
                        setTimeout(() => {
                            wx.switchTab({ url: '/pages/garden/index' });
                        }, 1000);
                    }
                }
            }
        });
    }
})
