"use client"

import { useState } from "react"
import AppLayout from "@/Layouts/AppLayout"
import useTranslate from "@/hooks/useTranslate"
import AccountSelection from "@/Components/Post/AccountSelection"
import Composer from "@/Components/Post/Composer"
import ConnectAccountModal from "@/Components/Post/ConnectAccountModal"
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"

export default function PostIndex({ platforms, accounts, all_accounts, media, post_templates, ai_templates, ai_modules }) {
  const breadcrumbs = [{ label: "Home", href: route("user.home") }, { label: "Create post" }]
  const [selectedAccounts, setSelectedAccounts] = useState([])
  const [activePlatform, setActivePlatform] = useState("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)
  const [connectModalOpen, setConnectModalOpen] = useState(false)

  const t = useTranslate()
  

  const handleSelectedAccountsChange = (selectedAccountsData) => {
    setSelectedAccounts(selectedAccountsData)
  }

  const handleActivePlatformChange = (platform) => {
    setActivePlatform(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
  }

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

  const renderPreview = () => {
    // Return default preview if activePlatform is null or undefined
    if (!activePlatform) {
      return <FacebookPreview postContent={postContent} postType="feed" selectedAccounts={[]} selectedMedia={selectedMedia} mediaCaptions={mediaCaptions} links={links} />
    }

    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 (
    <AppLayout breadcrumbs={breadcrumbs}>
      <div className="flex-1 p-6 overflow-auto bg-gray-50 dark:bg-black">
        {/* Post Header */}
        <div className="space-y-1 mb-6">
          <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">{t("Create post")}</h1>
          <p className="text-gray-500 dark:text-neutral-400">
            {t("Make sure to stay engaged with your social media audience")}
          </p>
        </div>

        {/* Empty state when no accounts exist at all */}
        {(!all_accounts || all_accounts.length === 0) ? (
          <div className="flex flex-col items-center justify-center py-16 px-4">
            <div className="bg-gray-100 dark:bg-gray-800 rounded-full p-4 mb-4">
              <svg className="w-12 h-12 text-gray-400 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
              {t("No Social Accounts Found")}
            </h3>
            <p className="text-gray-500 dark:text-gray-400 text-center max-w-md mb-6">
              {t("You need to add at least one social media account before you can create posts.")}
            </p>
            <button
              onClick={() => setConnectModalOpen(true)}
              className="inline-flex items-center px-4 py-2 bg-gradient-to-r from-primary to-secondary text-white rounded-lg hover:from-secondary hover:to-primary transition-all duration-200 shadow-sm hover:shadow-md"
            >
              <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
              {t("Add Account")}
            </button>
          </div>
        ) : (!accounts || accounts.length === 0) ? (
          <div className="flex flex-col items-center justify-center py-16 px-4">
            <div className="bg-yellow-100 dark:bg-yellow-900/20 rounded-full p-4 mb-4">
              <svg className="w-12 h-12 text-yellow-600 dark:text-yellow-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
              {t("No Accounts Connected")}
            </h3>
            <p className="text-gray-500 dark:text-gray-400 text-center max-w-md mb-6">
              {t("You have accounts set up but none are connected. Please connect your accounts to start posting.")}
            </p>
            <button
              onClick={() => window.location.href = route('user.platform.account.index')}
              className="inline-flex items-center px-4 py-2 bg-gradient-to-r from-primary to-secondary text-white rounded-lg hover:from-secondary hover:to-primary transition-all duration-200 shadow-sm hover:shadow-md"
            >
              <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
              {t("Connect Accounts")}
            </button>
          </div>
        ) : (
        <div className="grid grid-cols-1 lg:grid-cols-[345px_1fr_400px] gap-5">
          {/* Left Column - Account Selection */}
          <div>
            <AccountSelection
              t={t}
              onSelectedAccountsChange={handleSelectedAccountsChange}
              onActivePlatformChange={handleActivePlatformChange}
              accounts={accounts}
              socialPlatforms={platforms}
            />
          </div>

          {/* Middle Column - Composer */}
          <div>
            <Composer
              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}
              ai_modules={ai_modules}
            />
          </div>

          {/* Right Column - Preview */}
          <div>{renderPreview()}</div>
        </div>
        )}

        {/* Connect Account Modal */}
        <ConnectAccountModal
          isOpen={connectModalOpen}
          onClose={() => setConnectModalOpen(false)}
          platforms={platforms}
          t={t}
        />
      </div>
    </AppLayout>
  )
}
