"use client"

import AppLayout from "@/Layouts/AppLayout"
import { useState, useEffect, useRef } from "react"
import useTranslate from "@/hooks/useTranslate"
import Composer from "@/Components/Post/Composer"
import { router } from "@inertiajs/react"
import { route } from "ziggy-js"

export default function PostEditPage({ post, platforms, accounts, media, post_templates, ai_templates, ai_modules }) {
    const t = useTranslate()
    const onPrepare = useRef(null)

    const [postContent, setPostContent] = useState("")
    const [platformPostTypes, setPlatformPostTypes] = useState({})
    const [selectedMedia, setSelectedMedia] = useState([])
    const [mediaCaptions, setMediaCaptions] = useState({})
    const [links, setLinks] = useState([])
    const [isScheduled, setIsScheduled] = useState(false)
    const [scheduledTime, setScheduledTime] = useState(null)
    const [selectedAccounts, setSelectedAccounts] = useState([])
    const [activePlatform, setActivePlatform] = useState("facebook")

    useEffect(() => {
        if (post) {
            setPostContent(post.content || "")
            setPlatformPostTypes(post.postTypes || {})
            setSelectedMedia(post.files || [])
            setLinks(post.links || [])
            setIsScheduled(post.is_scheduled === "1")
            setScheduledTime(post.scheduled_time)
            setSelectedAccounts(post.accounts || [])
            setActivePlatform(post.activePlatform || "facebook")

            if (post.files) {
                const captions = {}
                post.files.forEach((file) => {
                    if (file.caption) {
                        captions[file.id] = file.caption
                    }
                })
                setMediaCaptions(captions)
            }
        }
    }, [post])

    const breadcrumbs = [
        { label: "Home", href: "user.home" },
        { label: "Posts", href: "user.post.index" },
        { label: "Edit Post" },
    ]

    const handlePostContentChange = (content) => {
        setPostContent(content)
    }

    const handlePostTypeChange = (platform, postType) => {
        setPlatformPostTypes((prev) => ({
            ...prev,
            [platform]: postType,
        }))
    }

    const handleSelectedMediaChange = (media) => {
        setSelectedMedia(media)
    }

    const handleMediaCaptionChange = (mediaId, caption) => {
        setMediaCaptions((prev) => ({
            ...prev,
            [mediaId]: caption,
        }))
    }

    const handleLinksChange = (newLinks) => {
        setLinks(newLinks)
    }



    const handleSchedulingChange = (scheduled, time) => {
        setIsScheduled(scheduled)
        setScheduledTime(time)
    }

    const preparePostData = () => {

        const files = selectedMedia.map((media, index) => ({
            ...media,
            caption: mediaCaptions[media.id] || "",
            order: index + 1,
        }))



        const postData = {
            id: post.id ?? null,
            postTypes: platformPostTypes,
            content: postContent,
            files: files,
            links: links,
            is_scheduled: isScheduled ? "1" : "0",
            scheduled_time: scheduledTime,
            is_draft: "0",
        }


        return postData
    }

    onPrepare.current = preparePostData

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <div className="flex-1 p-6 overflow-auto bg-gray-50 dark:bg-black">
                {/* Header */}
                <div className="flex items-center justify-between flex-wrap gap-4 mb-6">
                    <div className="space-y-1">
                        <h1 className="text-xl sm:text-xl sm:text-2xl dark:text-gray-200 font-bold">{t("Edit Template")}</h1>
                        <p className="text-gray-500 dark:text-gray-200">{t("Update your post content and settings")}</p>
                    </div>
                </div>

                <div className="max-w-full mx-auto">
                    <Composer
                        isTemplate={true}
                        isEdit={true}
                        t={t}
                        platform={activePlatform}
                        selectedAccounts={selectedAccounts}
                        media={media}
                        onPostContentChange={handlePostContentChange}
                        onPostTypeChange={handlePostTypeChange}
                        platformPostTypes={platformPostTypes}
                        selectedMedia={selectedMedia}
                        onSelectedMediaChange={handleSelectedMediaChange}
                        mediaCaptions={mediaCaptions}
                        onMediaCaptionChange={handleMediaCaptionChange}
                        links={links}
                        onLinksChange={handleLinksChange}
                        onPost={preparePostData}
                        onSchedulingChange={handleSchedulingChange}
                        isScheduled={isScheduled}
                        scheduledTime={scheduledTime}
                        platforms={platforms}
                        postTemplateList={post_templates}
                        aiTemplateList={ai_templates}
                        exisitngDataOnEdit={post}
                        ai_modules={ai_modules}
                    />
                </div>
            </div>
        </AppLayout>
    )
}
