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

Page({
    data: {
        plantId: '',
        newPlantName: '',
        newPlantLocation: '',
        newPlantDate: '',
        newPlantImage: null,
        isLocalImage: false,
        uploadedImageId: '',

        // Extra fields requested by user struct
        potMaterial: '',
        potSize: '',
        sunlight: '',
        plantingMaterial: '',

        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;
        }

        this.setData({
            plantId: id,
            careTaskIcons: CARE_TASK_ICONS
        });

        // Try to receive data from opener page first
        const eventChannel = this.getOpenerEventChannel();
        let hasReceivedData = false;



        if (eventChannel) {
            // Listen for events from the opener page
            eventChannel.on('acceptDataFromOpenerPage', (data) => {

                if (data && data.plant) {
                    hasReceivedData = true;
                    // Directly render with passed data
                    this.renderPlantUI(data.plant);
                }
            });
        }

        const isFromDetail = options.source === 'detail';

        // If from detail, wait longer for event channel. If direct open, fetch immediately.
        const waitTime = isFromDetail ? 2000 : 0;

        setTimeout(() => {
            if (!hasReceivedData) {
                this.fetchPlantDetail(id);
            }
        }, waitTime);
    },

    fetchPlantDetail(id) {
        request.get('/plant/detail', { id }).then(plant => {
            this.renderPlantUI(plant);
        }).catch(err => {
            console.error('Fetch detail for edit failed', err);
        });
    },

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

        // Parse carePlans (careSchedule is from detail UI structure, carePlans is from backend)
        // If passed from detail page, it might already have 'careSchedule' with parsed icons. 
        // But backend structure 'carePlans' needs parsing.
        // Let's handle both cases robustly.

        let tasks = [];
        if (plant.careSchedule) {
            // Data from Detail Page
            tasks = plant.careSchedule.map(cp => ({
                id: cp.id,
                name: cp.name,
                period: cp.period,
                taskIcon: cp.taskIcon
            }));
        } else if (plant.carePlans) {
            // Data from Backend
            tasks = plant.carePlans.map(cp => {
                let iconObj = defaultIcon;
                if (typeof cp.icon === 'string' && cp.icon.startsWith('{')) {
                    try {
                        iconObj = JSON.parse(cp.icon);
                    } catch (e) { }
                }
                return {
                    id: cp.id,
                    name: cp.name,
                    period: cp.period,
                    taskIcon: iconObj
                };
            });
        }

        // Map images: get first one if exists and handle path resolution
        let imageUrl = '';
        let imageId = '';

        if (plant.imgList && plant.imgList.length > 0) {
            imageUrl = plant.imgList[0].url || '';
            imageId = plant.imgList[0].id || '';
        }

        // Path resolution for local vs remote
        if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/') && !imageUrl.startsWith('wxfile')) {
            imageUrl = '/assets/' + imageUrl;
        }

        // Formatting date (extract YYYY-MM-DD)
        let adoptionDate = plant.plantTime || '';
        if (adoptionDate.includes('T')) {
            adoptionDate = adoptionDate.split('T')[0];
        }

        this.setData({
            newPlantName: plant.name || '',
            newPlantLocation: plant.placement || '',
            newPlantDate: adoptionDate,
            newPlantImage: imageUrl,
            uploadedImageId: imageId,
            potMaterial: plant.potMaterial || '',
            potSize: plant.potSize || '',
            sunlight: plant.sunlight || '',
            plantingMaterial: plant.plantingMaterial || '',
            newCareTasks: tasks
        });
    },

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

                wx.showLoading({ title: '上传图片...' });
                request.upload(tempFilePath).then(data => {
                    wx.hideLoading();
                    const fileData = data?.file || {};
                    if (fileData.id) {
                        this.setData({
                            uploadedImageId: fileData.id,
                            newPlantImage: fileData.url
                        });
                    }
                }).catch(err => {
                    wx.hideLoading();
                    wx.showToast({ title: '上传失败', icon: 'none' });
                });
            }
        });
    },

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

        tasks.push({
            id: 'new_' + Date.now(),
            name: '',
            period: 1,
            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, name: 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, period: 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,
                        name: t.name || selectedIcon.name
                    };
                }
                return t;
            });

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

    handleSavePlant() {
        const {
            plantId, newPlantName, newPlantLocation, potMaterial, potSize,
            sunlight, plantingMaterial
        } = this.data;

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

        const payload = {
            id: plantId,
            name: newPlantName,
            placement: newPlantLocation || '',
            potMaterial: potMaterial || '',
            potSize: potSize || '',
            sunlight: sunlight || '',
            plantingMaterial: plantingMaterial || ''
        };

        request.post('/plant/update', payload).then(() => {
            wx.showToast({ title: '修改成功', icon: 'success' });
            setTimeout(() => {
                wx.navigateBack();
            }, 1000);
        }).catch(err => {
            console.error('Update plant failed', err);
        });
    },

    handleDeletePlant() {
        wx.showModal({
            title: '确认删除',
            content: '确定要删除这个植物吗？删除后无法恢复。',
            confirmColor: '#EF5350',
            success: (res) => {
                if (res.confirm) {
                    // Assuming there might be a delete API later, but user didn't provide one.
                    // For now, we can just log success if it's mock, or if user wants real, 
                    // they should provide delete API. I'll just keep the UI feedback.
                    wx.showToast({ title: '已删除', icon: 'success' });
                    setTimeout(() => {
                        wx.switchTab({ url: '/pages/garden/index' });
                    }, 1000);
                }
            }
        });
    }
})
