"use client"

import { useState, useEffect } from "react"
import AccountSelection from "@/Components/Post/AccountSelection"
import useTranslate from "@/hooks/useTranslate"
import Composer from "@/Components/Post/Composer"
import FacebookPreview from "@/Components/Post/Preview/FacebookPreview"
import InstagramPreview from "@/Components/Post/Preview/InstagramPreview"
import TwitterPreview from "@/Components/Post/Preview/TwitterPreview"
import LinkedInPreview from "@/Components/Post/Preview/LinkedInPreview"
import ThreadsPreview from "@/Components/Post/Preview/ThreadsPreview"
import TiktokPreview from "@/Components/Post/Preview/TiktokPreview"
import YoutubePreview from "@/Components/Post/Preview/YoutubePreview"

const StepTwo = ({ formData, onInputChange, platforms, accounts, media, post_templates, ai_templates,  onPrepare, ai_modules }) => {
    const t = useTranslate()
    const [selectedAccounts, setSelectedAccounts] = useState([])
    const [activePlatform, setActivePlatform] = useState(formData.activePlatform || "facebook")
    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)

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



    const handleSelectedAccountsChange = (selectedAccountsData) => {
        setSelectedAccounts(selectedAccountsData)
        onInputChange("selectedAccounts", selectedAccountsData)
    }

    const handleActivePlatformChange = (platform) => {
        setActivePlatform(platform)
        onInputChange("activePlatform", platform)
    }

    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 preparePostData = () => {
        const accountsData = selectedAccounts.map((account) => ({
            account_id: account.id,
            platform_id: account.platform_id,
            post_type: platformPostTypes[account.platform?.slug] || "feed",
        }))

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

        const postData = {
            accounts: accountsData,
            postTypes: platformPostTypes,
            content: postContent,
            files: files,
            links: links,
            is_scheduled: isScheduled ? "1" : "0",
            scheduled_time: scheduledTime,
            is_draft: "0",
        }
        return postData
    }

    onPrepare.current = preparePostData

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

    const renderPreview = () => {
        const previewProps = {
            postContent,
            postType: platformPostTypes[activePlatform] || "feed",
            selectedAccounts: selectedAccounts.filter((account) => account.platform.slug === activePlatform),
            selectedMedia,
            mediaCaptions,
            links,
        }

        switch (activePlatform.toLowerCase()) {
            case "facebook":
                return <FacebookPreview {...previewProps} />
            case "instagram":
                return <InstagramPreview {...previewProps} />
            case "twitter":
            case "x":
                return <TwitterPreview {...previewProps} />
            case "linkedin":
                return <LinkedInPreview {...previewProps} />
            case "threads":
                return <ThreadsPreview {...previewProps} />
            case "tiktok":
                return <TiktokPreview {...previewProps} />
            case "youtube":
                return <YoutubePreview {...previewProps} />
            default:
                return <FacebookPreview {...previewProps} />
        }
    }

    return (
        <div className="space-y-8">
            {/* Header */}
            <div className="text-center">
                <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
                    Account Selection & Content
                </h2>
                <p className="text-gray-600 dark:text-gray-400">
                    Choose your platforms and create engaging content for your campaign
                </p>
            </div>

            {/* Content Layout */}
            <div className="flex flex-col xl:flex-row gap-6">
                {/* Left Column - Account Selection */}
                <div className="xl:w-80 xl:flex-shrink-0">
                    <AccountSelection
                        t={t}
                        mode="full"
                        onSelectedAccountsChange={handleSelectedAccountsChange}
                        onActivePlatformChange={handleActivePlatformChange}
                        accounts={accounts}
                        socialPlatforms={platforms}
                        selectedAccountIds={selectedAccounts.map(account => account.id)}
                        showAllPlatforms={true}
                    />
                </div>

                {/* Right Section - Composer & Preview */}
                <div className="flex-1 flex flex-col lg:flex-row gap-6">
                    {/* Composer */}
                    <div className="flex-1 min-w-0">
                        <Composer
                            isCampaign={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}
                            exisitngDataOnEdit={formData}
                            ai_modules={ai_modules}
                            aiTemplateList={ai_templates}
                        />
                    </div>

                    {/* Preview - Hide on mobile, show on larger screens */}
                    <div className="hidden lg:block lg:w-80 xl:w-96 flex-shrink-0">
                        <div className="sticky top-6">
                            <div className="bg-gray-50 dark:bg-zinc-800 rounded-xl p-4">
                                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 text-center">
                                    Preview
                                </h3>
                                <div className="max-h-[600px] overflow-y-auto">
                                    {renderPreview()}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Mobile Preview Button */}
            <div className="lg:hidden">
                <details className="bg-gray-50 dark:bg-zinc-800 rounded-xl">
                    <summary className="p-4 cursor-pointer text-center font-medium text-gray-900 dark:text-white hover:bg-gray-100 dark:hover:bg-zinc-700 rounded-xl transition-colors">
                        View Preview
                    </summary>
                    <div className="p-4 pt-0">
                        {renderPreview()}
                    </div>
                </details>
            </div>
        </div>
    )
}

export default StepTwo
