// pages/community/create/index.js
import { MOCK_POSTS } from '../../../utils/mockData';

Page({
    data: {
        content: '',
        images: [],
        canPublish: false,
        autoFocus: true,
        location: '',
        selectedTopics: [],
        suggestedTopics: ['植物养护', '多肉日记', '绿植分享', '花卉美照', '阳台花园', '新手入门'],
        hasDraft: false,
        showImageSheet: false,
        imageSheetItems: [
            { label: '拍照', value: 'camera' },
            { label: '从相册选择', value: 'album' }
        ]
    },

    onLoad() {
        // Check for saved draft
        this.loadDraft();
    },

    onUnload() {
        // Save draft if there's content
        this.saveDraft();
    },

    loadDraft() {
        try {
            const draft = wx.getStorageSync('post_draft');
            if (draft && (draft.content || draft.images.length > 0)) {
                this.setData({
                    content: draft.content || '',
                    images: draft.images || [],
                    selectedTopics: draft.selectedTopics || [],
                    canPublish: draft.content && draft.content.trim().length > 0,
                    hasDraft: true
                });
            }
        } catch (e) {
            console.log('No draft found');
        }
    },

    saveDraft() {
        if (this.data.content || this.data.images.length > 0) {
            try {
                wx.setStorageSync('post_draft', {
                    content: this.data.content,
                    images: this.data.images,
                    selectedTopics: this.data.selectedTopics
                });
            } catch (e) {
                console.log('Failed to save draft');
            }
        }
    },

    clearDraft() {
        try {
            wx.removeStorageSync('post_draft');
        } catch (e) {
            console.log('Failed to clear draft');
        }
    },

    onContentInput(e) {
        const content = e.detail.value;
        this.setData({
            content,
            canPublish: content.trim().length > 0,
            hasDraft: false
        });
    },

    showImageSourceSheet() {
        this.setData({ showImageSheet: true });
    },

    hideImageSheet() {
        this.setData({ showImageSheet: false });
    },

    onImageSheetSelect(e) {
        const { value } = e.detail.selected;
        this.setData({ showImageSheet: false });

        if (value === 'camera') {
            this.takePhoto();
        } else {
            this.chooseImage();
        }
    },

    chooseImage() {
        const remaining = 9 - this.data.images.length;
        if (remaining <= 0) {
            wx.showToast({ title: '最多9张图片', icon: 'none' });
            return;
        }

        wx.chooseMedia({
            count: remaining,
            mediaType: ['image'],
            sourceType: ['album'],
            success: (res) => {
                const newImages = res.tempFiles.map(f => f.tempFilePath);
                this.setData({
                    images: [...this.data.images, ...newImages],
                    hasDraft: false
                });
            }
        });
    },

    takePhoto() {
        if (this.data.images.length >= 9) {
            wx.showToast({ title: '最多9张图片', icon: 'none' });
            return;
        }

        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['camera'],
            camera: 'back',
            success: (res) => {
                const newImage = res.tempFiles[0].tempFilePath;
                this.setData({
                    images: [...this.data.images, newImage],
                    hasDraft: false
                });
            }
        });
    },

    removeImage(e) {
        const index = e.currentTarget.dataset.index;
        const images = [...this.data.images];
        images.splice(index, 1);
        this.setData({ images });
    },

    showImageMenu(e) {
        const index = e.currentTarget.dataset.index;
        wx.showActionSheet({
            itemList: ['设为封面', '删除'],
            success: (res) => {
                if (res.tapIndex === 0) {
                    // Move to first position
                    const images = [...this.data.images];
                    const [img] = images.splice(index, 1);
                    images.unshift(img);
                    this.setData({ images });
                    wx.showToast({ title: '已设为封面', icon: 'success' });
                } else if (res.tapIndex === 1) {
                    this.removeImage({ currentTarget: { dataset: { index } } });
                }
            }
        });
    },

    chooseLocation() {
        wx.chooseLocation({
            success: (res) => {
                this.setData({ location: res.name || res.address });
            },
            fail: () => {
                // User cancelled or no permission
            }
        });
    },

    toggleTopic(e) {
        const topic = e.currentTarget.dataset.topic;
        const hashtag = `#${topic} `;
        let { content, selectedTopics } = this.data;

        if (selectedTopics.includes(topic)) {
            // Remove topic and hashtag from content
            selectedTopics = selectedTopics.filter(t => t !== topic);
            content = content.replace(hashtag, '');
        } else {
            if (selectedTopics.length >= 3) {
                wx.showToast({ title: '最多选择3个话题', icon: 'none' });
                return;
            }
            // Add topic and insert hashtag into content
            selectedTopics.push(topic);
            content = content + hashtag;
        }

        this.setData({
            selectedTopics,
            content,
            canPublish: content.trim().length > 0
        });
    },

    insertEmoji() {
        // Simple emoji picker simulation
        const emojis = ['🌱', '🌿', '🍀', '🌵', '🌻', '🌺', '🌸', '🌼', '🪴', '🌲'];
        wx.showActionSheet({
            itemList: emojis,
            success: (res) => {
                const emoji = emojis[res.tapIndex];
                this.setData({
                    content: this.data.content + emoji,
                    canPublish: true
                });
            }
        });
    },

    handleCancel() {
        if (this.data.content || this.data.images.length > 0) {
            wx.showModal({
                title: '保存草稿',
                content: '是否保存当前内容为草稿？',
                cancelText: '不保存',
                confirmText: '保存',
                success: (res) => {
                    if (res.confirm) {
                        this.saveDraft();
                        wx.showToast({ title: '已保存草稿', icon: 'success' });
                        setTimeout(() => wx.navigateBack(), 500);
                    } else {
                        this.clearDraft();
                        wx.navigateBack();
                    }
                }
            });
        } else {
            wx.navigateBack();
        }
    },

    handlePublish() {
        if (!this.data.canPublish) {
            wx.showToast({ title: '请输入内容', icon: 'none' });
            return;
        }

        // Content already includes topics as hashtags
        const finalContent = this.data.content.trim();

        // Create new post
        const newPost = {
            id: Date.now().toString(),
            user: '我的花园',
            content: finalContent,
            images: this.data.images,
            time: '刚刚',
            likes: [],
            comments: []
        };

        // Add to global mock data (at the beginning)
        MOCK_POSTS.unshift(newPost);

        // Clear draft
        this.clearDraft();

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

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