"use client"

import React, { useState, useEffect, useRef } from "react"
import {
  Plus,
  Smile,
  Hash,
  Link,
  Info,
  Clock,
  Sparkles,
  FileText,
  ImageIcon,
  Upload,
  Send,
  X,
  ChevronLeft,
  ChevronRight,
  GripVertical,
} from "lucide-react"
import EmojiPicker from "emoji-picker-react"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/Components/UI/DropdownMenu"
import { Modal } from "@/Components/UI/Modal"
import AiAssistance from "@/Components/AiAssistance"
import SideGallery from "@/Components/SideGallery"
import PostTemplate from "@/Components/PostTemplate"
import InfoModal from "@/Components/Post/InfoModal"
import { router } from "@inertiajs/react"
import { route } from "ziggy-js"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/UI/Select"

export default function Composer({
  isCampaign = false,
  isTemplate = false,
  isEdit = false,
  t,
  platform = "facebook",
  selectedAccounts = [],
  onPostContentChange,
  onPostTypeChange,
  platformPostTypes = {},
  selectedMedia = [],
  onSelectedMediaChange,
  mediaCaptions = {},
  onMediaCaptionChange,
  links = [],
  onLinksChange,
  onPost,
  media,
  onSchedulingChange,
  isScheduled = false,
  scheduledTime = null,
  platforms,
  postTemplateList,
  aiTemplateList,
  exisitngDataOnEdit = [],
  ai_modules = [],
}) {
  const [postContent, setPostContent] = useState("")
  const [saveAsTemplate, setSaveAsTemplate] = useState(false)
  const [isDraft, setIsDraft] = useState(false)
  const [schedulerOpen, setSchedulerOpen] = useState(false)
  const [selectedDate, setSelectedDate] = useState(() => {
    // If this is a campaign with start date, use campaign start date
    if (isCampaign && exisitngDataOnEdit?.startDate) {
      return new Date(exisitngDataOnEdit.startDate)
    }
    // Otherwise default to tomorrow to avoid past time issues
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    return tomorrow
  })
  const [selectedTime, setSelectedTime] = useState(() => {
    // Default to a future time (current time + 2 hours)
    const futureTime = new Date()
    futureTime.setHours(futureTime.getHours() + 2)
    return `${futureTime.getHours().toString().padStart(2, '0')}:00`
  })
  const [currentMonth, setCurrentMonth] = useState(() => {
    // If this is a campaign with start date, show the campaign month
    if (isCampaign && exisitngDataOnEdit?.startDate) {
      return new Date(exisitngDataOnEdit.startDate)
    }
    return new Date()
  })
  const [saveTemplateModalOpen, setSaveTemplateModalOpen] = useState(false)
  const [templateName, setTemplateName] = useState("")
  const [templateDescription, setTemplateDescription] = useState("")
  const [aiAssistanceOpen, setAiAssistanceOpen] = useState(false)
  const [galleryOpen, setGalleryOpen] = useState(false)
  const [postTemplateOpen, setPostTemplateOpen] = useState(false)
  const [infoModalOpen, setInfoModalOpen] = useState(false)
  const [linkModalOpen, setLinkModalOpen] = useState(false)
  const [linkUrl, setLinkUrl] = useState("")
  const [emojiPickerOpen, setEmojiPickerOpen] = useState(false)
  const [hashtagModalOpen, setHashtagModalOpen] = useState(false)
  const [customHashtag, setCustomHashtag] = useState("")
  const [draggedIndex, setDraggedIndex] = useState(null)
  const textareaRef = useRef(null)
  const fileInputRef = useRef(null)
  const [intendedPlatform, setIntendedPlatform] = useState(platforms.find(p => p.slug === "facebook")?.id || null)
  const [isSubmitting, setIsSubmitting] = useState(false)

  

  const popularHashtags = [
    "#trending",
    "#viral",
    "#love",
    "#instagood",
    "#photooftheday",
    "#beautiful",
    "#happy",
    "#cute",
    "#tbt",
    "#like4like",
    "#followme",
    "#picoftheday",
    "#follow",
    "#me",
    "#selfie",
    "#summer",
    "#art",
    "#instadaily",
    "#friends",
    "#nature",
  ]

  const defaultPlatformPostTypes = {
    facebook: [
      { id: "feed", label: t("Feed") },
      { id: "reels", label: t("Reels") },
      { id: "story", label: t("Story") },
    ],
    instagram: [
      { id: "feed", label: t("Feed") },
      { id: "reels", label: t("Reels") },
    ],
    twitter: [{ id: "feed", label: t("Feed") }],
    youtube: [
      { id: "feed", label: t("Feed") },
      { id: "shorts", label: t("Shorts") },
    ],
    linkedin: [{ id: "feed", label: t("Feed") }],
    tiktok: [{ id: "feed", label: t("Feed") }],
    threads: [{ id: "feed", label: t("Feed") }],
  }

  const currentPlatformAccounts = selectedAccounts.filter((account) => account?.platform?.slug === platform)

  const platformTypes = platformPostTypes[platform]
  const postTypes = Array.isArray(platformTypes)
    ? platformTypes
    : defaultPlatformPostTypes[platform] || defaultPlatformPostTypes.facebook

  const currentPostType = platformPostTypes[platform] || (postTypes.length > 0 ? postTypes[0] : { id: "feed", label: "Feed" })

  // Ensure we have a valid initial post type ID
  const getInitialPostTypeId = () => {
    if (typeof currentPostType === 'object' && currentPostType.id) {
      return currentPostType.id;
    }
    if (typeof currentPostType === 'string') {
      return currentPostType;
    }
    return 'feed';
  };

  const [selectedPostType, setSelectedPostType] = useState(getInitialPostTypeId())

  useEffect(() => {
    if (postTypes.length > 0) {
      setSelectedPostType(postTypes[0].id)
      if (onPostTypeChange) {
        onPostTypeChange(platform, postTypes[0].id)
      }
    }
  }, [platform])

  useEffect(() => {
    if (exisitngDataOnEdit.content) {
      setPostContent(exisitngDataOnEdit.content)
    }
  }, [exisitngDataOnEdit])

  const insertTextAtCursor = (textToInsert) => {
    const textarea = textareaRef.current
    if (!textarea) return

    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const newContent = postContent.substring(0, start) + textToInsert + postContent.substring(end)

    setPostContent(newContent)
    if (onPostContentChange) {
      onPostContentChange(newContent)
    }

    setTimeout(() => {
      textarea.focus()
      textarea.setSelectionRange(start + textToInsert.length, start + textToInsert.length)
    }, 0)
  }

  const handleInsertLink = () => {
    if (linkUrl) {
      insertTextAtCursor(linkUrl)
      setLinkUrl("")
      setLinkModalOpen(false)
    }
  }

  const extractLinksFromContent = (content) => {
    const urlRegex = /(https?:\/\/[^\s]+)/g
    const extractedLinks = []
    let match

    while ((match = urlRegex.exec(content)) !== null) {
      extractedLinks.push({
        url: match[1],
        id: Date.now() + Math.random(),
      })
    }

    if (extractedLinks.length !== links.length) {
      onLinksChange(extractedLinks)
    }
  }

  const handleEmojiSelect = (emojiObject) => {
    insertTextAtCursor(emojiObject.emoji)
    setEmojiPickerOpen(false)
  }

  const handleHashtagClick = () => {
    setHashtagModalOpen(true)
  }

  const handleHashtagSelect = (hashtag) => {
    insertTextAtCursor(hashtag + " ")
    setHashtagModalOpen(false)
  }

  const handleCustomHashtagInsert = () => {
    if (customHashtag.trim()) {
      const hashtagText = customHashtag.startsWith("#") ? customHashtag : `#${customHashtag}`
      insertTextAtCursor(hashtagText + " ")
      setCustomHashtag("")
      setHashtagModalOpen(false)
    }
  }

  const handlePost = () => {
    if (onPost) {
      const postData = onPost()
      const finalPostData = {
        ...postData,
        is_draft: "0",
      }

      router.post(route("user.post.store"), finalPostData)
    } else {
     
    }
  }

  const handlePostUpdate = () => {
    if (onPost) {
      const postData = onPost()
      const finalPostData = {
        ...postData,
        is_draft: "0",
      }

      isTemplate ? router.post(route("user.template.update"), postData) : router.post(route("user.post.update"), postData)

    } else {
      
    }
  }

  const handleSaveDraft = () => {
    if (onPost) {
      const postData = onPost()
      const draftData = {
        ...postData,
        is_draft: "1",
      }

      router.post(route("user.post.store"), draftData)
    } else {
    }
  }

  const handleAIAssistance = () => {
    setAiAssistanceOpen(true)
  }

  const handlePostTemplate = () => {
    setPostTemplateOpen(true)
  }

  const handleOpenGallery = () => {
    setGalleryOpen(true)
  }

  const handleMediaApply = (mediaItems) => {
    const newMedia = [...selectedMedia, ...mediaItems]
    if (onSelectedMediaChange) {
      onSelectedMediaChange(newMedia)
    }
  }

  const removeMedia = (mediaId) => {
    const newMedia = selectedMedia.filter((item) => item.id !== mediaId)
    if (onSelectedMediaChange) {
      onSelectedMediaChange(newMedia)
    }
  }

  const scheduledDateTime = new Date(selectedDate)
  const [hours, minutes] = selectedTime.split(":")
  scheduledDateTime.setHours(Number.parseInt(hours), Number.parseInt(minutes), 0, 0) // Reset seconds and milliseconds

  // Ensure the scheduled time is in the future
  const now = new Date()
  if (scheduledDateTime <= now) {
    // For campaigns, respect the campaign date range
    if (isCampaign && exisitngDataOnEdit?.startDate) {
      const campaignStart = new Date(exisitngDataOnEdit.startDate)
      const campaignEnd = new Date(exisitngDataOnEdit.endDate)

      // If we're before campaign start, use campaign start date with future time
      if (now < campaignStart) {
        scheduledDateTime.setTime(campaignStart.getTime())
        scheduledDateTime.setHours(Math.max(12, now.getHours() + 1), 0, 0, 0)
      } else if (now <= campaignEnd) {
        // If we're within campaign period, schedule for next hour
        scheduledDateTime.setTime(now.getTime())
        scheduledDateTime.setHours(now.getHours() + 1, 0, 0, 0)
      } else {
        // If campaign is over, don't auto-adjust (let validation handle it)
        console.warn('Scheduled time is after campaign end date')
      }
    } else {
      // For non-campaign posts, add one day as before
      scheduledDateTime.setDate(scheduledDateTime.getDate() + 1)
    }
  }

  // Move onSchedulingChange to useEffect to avoid calling setState during render
  useEffect(() => {
    if (onSchedulingChange) {
      onSchedulingChange(true, scheduledDateTime.toISOString())
    }
  }, [selectedDate, selectedTime])

  const handleSchedulePost = () => {

    setSchedulerOpen(false)

    if (onPost) {
      const postData = onPost()
      const scheduledPostData = {
        ...postData,
        is_scheduled: "1",
        scheduled_time: scheduledDateTime.toISOString().slice(0, 19).replace('T', ' '),
        is_draft: "0",
      }

      router.post(route("user.post.store"), scheduledPostData)
    }
  }

  const navigateMonth = (direction) => {
    setCurrentMonth((prev) => {
      const newMonth = new Date(prev)
      newMonth.setMonth(prev.getMonth() + direction)
      return newMonth
    })
  }

  const getDaysInMonth = (date) => {
    return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate()
  }

  const getFirstDayOfMonth = (date) => {
    return new Date(date.getFullYear(), date.getMonth(), 1).getDay()
  }

  const formatDate = (date) => {
    return date.toLocaleDateString("en-US", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
    })
  }

  const handleDateSelect = (day) => {
    const newDate = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), day)
    setSelectedDate(newDate)
  }

  const handleSaveTemplate = () => {
    const postData = onPost()

    const { accounts, postTypes, is_scheduled, scheduled_time, is_draft, ...templateData } = postData;

    const finalTemplateData = {
      ...templateData,
      platform_id: intendedPlatform,
      name: templateName,
      description: templateDescription,
    };

    router.post(route("user.template.store"), finalTemplateData);


    setSaveTemplateModalOpen(false)
    setTemplateName("")
    setTemplateDescription("")
    setSaveAsTemplate(true)
  }

  const handleSaveAsTemplateChange = (checked) => {
    if (checked) {
      setSaveTemplateModalOpen(true)
    } else {
      setSaveAsTemplate(false)
    }
  }

  const handleUploadMedia = () => {
    fileInputRef.current?.click()
  }

  const handleFileUpload = async (event) => {
    const files = Array.from(event.target.files)
    let currentMedia = [...selectedMedia]

    for (const file of files) {
      const isVideo = file.type.startsWith("video/")

      // Show temporary preview while uploading
      const tempId = Date.now() + Math.random()
      const tempMediaItem = {
        id: tempId,
        type: isVideo ? "video" : "image",
        title: file.name,
        caption: "",
        isVideo: isVideo,
        thumbnail: URL.createObjectURL(file),
        isUploading: true,
      }

      // Add temp item to show upload progress
      currentMedia = [...currentMedia, tempMediaItem]
      if (onSelectedMediaChange) {
        onSelectedMediaChange(currentMedia)
      }

      try {
        // Upload to gallery via AJAX
        const formData = new FormData()
        formData.append('file', file)

        const response = await fetch(route('user.gallery.quick-upload'), {
          method: 'POST',
          body: formData,
          headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'),
            'Accept': 'application/json',
          },
        })

        const result = await response.json()

        if (result.success && result.file) {
          // Replace temp item with real uploaded file
          const uploadedMediaItem = {
            id: result.file.id,
            type: result.file.type,
            title: result.file.title,
            caption: "",
            isVideo: result.file.isVideo,
            thumbnail: result.file.thumbnail,
            alt: result.file.alt,
          }

          currentMedia = currentMedia.map(item =>
            item.id === tempId ? uploadedMediaItem : item
          )
          if (onSelectedMediaChange) {
            onSelectedMediaChange(currentMedia)
          }
        } else {
          // Remove temp item on failure
          currentMedia = currentMedia.filter(item => item.id !== tempId)
          if (onSelectedMediaChange) {
            onSelectedMediaChange(currentMedia)
          }
          console.error('Upload failed:', result)
        }
      } catch (error) {
        // Remove temp item on error
        currentMedia = currentMedia.filter(item => item.id !== tempId)
        if (onSelectedMediaChange) {
          onSelectedMediaChange(currentMedia)
        }
        console.error('Upload error:', error)
      }
    }

    event.target.value = ""
  }

  const handleDragStart = (e, index) => {
    setDraggedIndex(index)
    e.dataTransfer.effectAllowed = "move"
  }

  const handleDragOver = (e) => {
    e.preventDefault()
    e.dataTransfer.dropEffect = "move"
  }

  const handleDrop = (e, dropIndex) => {
    e.preventDefault()

    if (draggedIndex === null || draggedIndex === dropIndex) {
      setDraggedIndex(null)
      return
    }

    const newMedia = [...selectedMedia]
    const draggedItem = newMedia[draggedIndex]    

    // Remove dragged item
    newMedia.splice(draggedIndex, 1)

    // Insert at new position
    newMedia.splice(dropIndex, 0, draggedItem)

    if (onSelectedMediaChange) {
      onSelectedMediaChange(newMedia)
    }

    setDraggedIndex(null)
  }

  const handleDragEnd = () => {
    setDraggedIndex(null)
  }

  const handleTemplateApply = (templates) => {
    try {
      if (!templates || templates.length === 0) {
        console.warn('No templates provided to apply')
        return
      }

      const template = templates[0]

      // Apply content if available
      if (template.content) {
        const newContent = template.content
        setPostContent(newContent)
        if (onPostContentChange) {
          onPostContentChange(newContent)
        }
      }

      // Apply images if available
      if (template.images && Array.isArray(template.images) && template.images.length > 0) {
        // Filter out invalid images and map to proper format
        const validImages = template.images.filter(img => img && (img.url || img.thumbnail))
        if (validImages.length > 0) {
          const newMedia = [...selectedMedia, ...validImages]
          if (onSelectedMediaChange) {
            onSelectedMediaChange(newMedia)
          }
        }
      }

      // Show success toast
      const toast = document.createElement('div')
      toast.className = 'fixed bottom-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-in slide-in-from-bottom-4 duration-300'
      toast.innerHTML = `
        <div class="flex items-center gap-2">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
          <span>Template applied successfully!</span>
        </div>
      `
      document.body.appendChild(toast)

      setTimeout(() => {
        toast.classList.add('animate-out', 'fade-out', 'slide-out-to-bottom-4')
        setTimeout(() => document.body.removeChild(toast), 300)
      }, 3000)

      // Close the template modal
      setPostTemplateOpen(false)
    } catch (error) {
      console.error('Error applying template:', error)

      // Show error toast
      const toast = document.createElement('div')
      toast.className = 'fixed bottom-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-in slide-in-from-bottom-4 duration-300'
      toast.innerHTML = `
        <div class="flex items-center gap-2">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
          <span>Failed to apply template. Please try again.</span>
        </div>
      `
      document.body.appendChild(toast)

      setTimeout(() => {
        toast.classList.add('animate-out', 'fade-out', 'slide-out-to-bottom-4')
        setTimeout(() => document.body.removeChild(toast), 300)
      }, 3000)
    }
  }

  const handleAITemplateApply = (aiContent) => {
    try {
      if (!aiContent) {
        console.warn('No AI content provided')
        return
      }

      // Handle text content from AI
      if (typeof aiContent === 'string') {
        setPostContent(aiContent)
        onPostContentChange?.(aiContent)
      } else if (aiContent.content) {
        // AI text generation response
        const text = aiContent.content
        setPostContent(text)
        onPostContentChange?.(text)
      } else if (aiContent.description) {
        // Template with description
        const text = aiContent.description
        setPostContent(text)
        onPostContentChange?.(text)
      }

      // Handle media content from AI
      if (aiContent.urls && Array.isArray(aiContent.urls) && aiContent.urls.length > 0) {
        // AI image generation response
        const aiImages = aiContent.urls.map((url, index) => ({
          id: `ai-image-${Date.now()}-${index}`,
          url: url,
          thumbnail: url,
          type: 'image',
          isAiGenerated: true
        }))
        const newMedia = [...selectedMedia, ...aiImages]
        if (onSelectedMediaChange) {
          onSelectedMediaChange(newMedia)
        }
      } else if (aiContent.url) {
        // Single media item (video or image)
        const mediaItem = {
          id: `ai-media-${Date.now()}`,
          url: aiContent.url,
          thumbnail: aiContent.thumbnail || aiContent.url,
          type: aiContent.type || 'image',
          isAiGenerated: true
        }
        const newMedia = [...selectedMedia, mediaItem]
        if (onSelectedMediaChange) {
          onSelectedMediaChange(newMedia)
        }
      }

      // Close AI assistance modal
      setAiAssistanceOpen(false)

      // Show success notification
      const toast = document.createElement('div')
      toast.className = 'fixed bottom-4 right-4 bg-gradient-to-r from-primary to-secondary text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-in slide-in-from-bottom-4 duration-300'
      toast.innerHTML = `
        <div class="flex items-center gap-2">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
          </svg>
          <span>AI content applied successfully!</span>
        </div>
      `
      document.body.appendChild(toast)

      setTimeout(() => {
        toast.classList.add('animate-out', 'fade-out', 'slide-out-to-bottom-4')
        setTimeout(() => document.body.removeChild(toast), 300)
      }, 3000)
    } catch (error) {
      console.error('Error applying AI content:', error)

      // Show error notification
      const toast = document.createElement('div')
      toast.className = 'fixed bottom-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-in slide-in-from-bottom-4 duration-300'
      toast.innerHTML = `
        <div class="flex items-center gap-2">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
          <span>Failed to apply AI content. Please try again.</span>
        </div>
      `
      document.body.appendChild(toast)

      setTimeout(() => {
        toast.classList.add('animate-out', 'fade-out', 'slide-out-to-bottom-4')
        setTimeout(() => document.body.removeChild(toast), 300)
      }, 3000)
    }
  }


  const handleInfoClick = () => {
    setInfoModalOpen(true)
  }

  const handlePostTypeChange = (typeId) => {
    setSelectedPostType(typeId)
    if (onPostTypeChange) {
      onPostTypeChange(platform, typeId)
    }
  }

  const handlePostContentChange = (content) => {
    setPostContent(content)
    if (onPostContentChange) {
      onPostContentChange(content)
    }
    extractLinksFromContent(content)
  }

  const handleMediaCaptionChange = (mediaId, caption) => {
    if (onMediaCaptionChange) {
      onMediaCaptionChange(mediaId, caption)
    }
  }

  const renderContentWithLinks = (content) => {
    const urlRegex = /(https?:\/\/[^\s]+)/g
    const parts = content.split(urlRegex)

    return parts.map((part, index) => {
      if (part.match(urlRegex)) {
        return (
          <span key={index} className="text-blue-600 dark:text-blue-400">
            {part}
          </span>
        )
      }
      return part
    })
  }

  return (
    <div className="bg-white dark:bg-zinc-900 rounded-xl border border-gray-200 dark:border-zinc-800 shadow-sm">
      <input
        ref={fileInputRef}
        type="file"
        multiple
        accept="image/*,video/*"
        onChange={handleFileUpload}
        className="hidden"
      />

      <div className="p-4 border-b border-gray-200 dark:border-zinc-800">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center space-x-1 bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
            {postTypes.map((type) => (
              <button
                key={type.id}
                onClick={() => handlePostTypeChange(type.id)}
                className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${selectedPostType === type.id
                  ? "bg-cyan-500 text-white shadow-sm"
                  : "text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
                  }`}
              >
                {type.label}
              </button>
            ))}
          </div>

          <button
            onClick={handleInfoClick}
            className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
          >
            <Info className="w-5 h-5" />
          </button>
        </div>

        <textarea
          ref={textareaRef}
          value={postContent}
          onChange={(e) => handlePostContentChange(e.target.value)}
          placeholder={t("Write Here")}
          className="w-full h-48 resize-none border-none outline-none text-gray-700 dark:text-gray-300 placeholder-gray-400 dark:placeholder-gray-500 bg-transparent text-base leading-relaxed p-2"
        />

        {selectedMedia.length > 0 && (
          <div className="mt-4 grid grid-cols-3 gap-2">
            {selectedMedia.map((media, index) => (
              <div
                key={media.id}
                draggable
                onDragStart={(e) => handleDragStart(e, index)}
                onDragOver={handleDragOver}
                onDrop={(e) => handleDrop(e, index)}
                onDragEnd={handleDragEnd}
                className={`relative group cursor-move ${draggedIndex === index ? "opacity-50" : ""}`}
              >
                <div className="absolute top-1 left-1 w-5 h-5 bg-black/60 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10">
                  <GripVertical className="w-3 h-3" />
                </div>

                {media.isVideo ? (
                  <video
                    src={media.thumbnail || (media.upload ? URL.createObjectURL(media.upload) : media.url)}
                    muted
                    playsInline
                    loop
                    autoPlay
                    className="w-full h-20 object-cover rounded-lg"
                  />
                ) : (
                  <img
                    src={
                      media.thumbnail ||
                      (media.upload ? URL.createObjectURL(media.upload) : media.url) ||
                      "/placeholder.svg"
                    }
                    alt={media.title || media.alt}
                    className="w-full h-20 object-cover rounded-lg"
                  />
                )}

                <button
                  onClick={() => removeMedia(media.id)}
                  className="absolute top-1 right-1 w-5 h-5 bg-black/60 hover:bg-black/80 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10"
                >
                  <X className="w-3 h-3" />
                </button>

                <div className="mt-1">
                  <input
                    type="text"
                    placeholder={t("Add caption...")}
                    value={mediaCaptions[media.id] || media.caption || ""}
                    onChange={(e) => handleMediaCaptionChange(media.id, e.target.value)}
                    className="w-full px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 border-0 rounded text-gray-700 dark:text-gray-300 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-1 focus:ring-cyan-500"
                  />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {currentPlatformAccounts.length > 0 && (
        <div className="px-4 py-2 bg-blue-50 dark:bg-blue-900/20 border-b border-gray-200 dark:border-zinc-800">
          <div className="text-xs text-blue-700 dark:text-blue-300">
            Posting to {currentPlatformAccounts.length} {platform} account
            {currentPlatformAccounts.length > 1 ? "s" : ""} as {postTypes.find(type => type.id === selectedPostType)?.label || 'Feed'}
          </div>
        </div>
      )}

      <div className="flex items-center justify-between flex-wrap gap-4 p-4 border-t border-gray-200 dark:border-zinc-800">
        <div className="flex items-center space-x-3">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
                <Plus className="w-5 h-5" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start" className="w-48">
              <DropdownMenuItem onClick={handlePostTemplate} className="flex items-center space-x-3 px-3 py-2">
                <FileText className="w-4 h-4 text-gray-500" />
                <span>{t("Post Template")}</span>
              </DropdownMenuItem>
              <DropdownMenuItem onClick={handleOpenGallery} className="flex items-center space-x-3 px-3 py-2">
                <ImageIcon className="w-4 h-4 text-gray-500" />
                <span>{t("Open Gallery")}</span>
              </DropdownMenuItem>
              <DropdownMenuItem onClick={handleUploadMedia} className="flex items-center space-x-3 px-3 py-2">
                <Upload className="w-4 h-4 text-gray-500" />
                <span>{t("Upload Media")}</span>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>

          <div className="relative">
            <button
              onClick={() => setEmojiPickerOpen(!emojiPickerOpen)}
              className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              <Smile className="w-5 h-5" />
            </button>

            {emojiPickerOpen && (
              <div className="absolute bottom-full left-0 mb-2 z-50">
                <EmojiPicker
                  onEmojiClick={handleEmojiSelect}
                  width={350}
                  height={400}
                  theme="auto"
                  searchDisabled={false}
                  skinTonesDisabled={false}
                  previewConfig={{
                    showPreview: false,
                  }}
                />
              </div>
            )}
          </div>

          <button
            onClick={handleHashtagClick}
            className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <Hash className="w-5 h-5" />
          </button>

          <button
            onClick={() => setLinkModalOpen(true)}
            className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <Link className="w-5 h-5" />
          </button>
        </div>

        <div className="flex items-center space-x-3">
          <button
            onClick={handleAIAssistance}
            className="flex items-center space-x-2 px-3 py-2 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg border border-gray-300 dark:border-gray-600 transition-colors"
          >
            <Sparkles className="w-4 h-4" />
            <span className="text-sm font-medium">{t("AI Assistance")}</span>
          </button>

          {!isCampaign && (
            isEdit ? (
              <button
                onClick={handlePostUpdate}
                disabled={!postContent.trim()}
                className="flex items-center space-x-2 px-3 py-2 bg-emerald-500 hover:bg-emerald-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"
              >
                <Send className="w-4 h-4" />
                <span className="text-sm">{t("Update")}</span>
              </button>
            ) : (
              <button
                onClick={handlePost}
                disabled={!postContent.trim()}
                className="flex items-center space-x-2 px-3 py-2 bg-cyan-500 hover:bg-cyan-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"
              >
                <Send className="w-4 h-4" />
                <span className="text-sm">{t("Post")}</span>
              </button>
            )
          )}


        </div>
      </div>

      {!isCampaign && !isTemplate && (
        <div className="flex items-center justify-between flex-wrap gap-4 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-b-xl">
          <label className="flex items-center space-x-2 cursor-pointer">
            <input
              type="checkbox"
              checked={saveAsTemplate}
              onChange={(e) => handleSaveAsTemplateChange(e.target.checked)}
              className="w-4 h-4 text-primary border-gray-300 dark:border-gray-600 rounded focus:ring-cyan-500 dark:focus:ring-cyan-400 focus:ring-2"
            />
            <span className="text-sm text-gray-700 dark:text-gray-300 font-medium">
              {saveAsTemplate ? t("Saved") : t("Save This Template")}
            </span>
          </label>

          <div className="flex items-center space-x-3">
            <button
              onClick={handleSaveDraft}
              className="flex items-center space-x-2 px-3 py-2 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg border border-gray-300 dark:border-gray-600 transition-colors"
            >
              <span className="text-sm font-medium">{t("Save draft")}</span>
            </button>

            <div className="relative">
              <button
                onClick={() => setSchedulerOpen(!schedulerOpen)}
                className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              >
                <Clock className="w-5 h-5" />
              </button>

              {schedulerOpen && (
                <div className="absolute bottom-full right-0 mb-2 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-lg shadow-lg p-4 w-80 z-50">
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Schedule Post</h3>
                    <button
                      onClick={() => setSchedulerOpen(false)}
                      className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </div>

                  <div className="flex items-center justify-between mb-4">
                    <button
                      onClick={() => navigateMonth(-1)}
                      className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      <ChevronLeft className="w-4 h-4" />
                    </button>
                    <h4 className="text-sm font-medium text-gray-900 dark:text-gray-100">
                      {currentMonth.toLocaleDateString("en-US", { month: "long", year: "numeric" })}
                    </h4>
                    <button
                      onClick={() => navigateMonth(1)}
                      className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      <ChevronRight className="w-4 h-4" />
                    </button>
                  </div>

                  <div className="grid grid-cols-7 gap-1 mb-4">
                    {["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"].map((day) => (
                      <div key={day} className="text-xs font-medium text-gray-500 dark:text-gray-400 text-center p-2">
                        {day}
                      </div>
                    ))}

                    {Array.from({ length: getFirstDayOfMonth(currentMonth) }).map((_, index) => (
                      <div key={`empty-${index}`} className="p-2"></div>
                    ))}

                    {Array.from({ length: getDaysInMonth(currentMonth) }).map((_, index) => {
                      const day = index + 1
                      const isSelected =
                        selectedDate.getDate() === day &&
                        selectedDate.getMonth() === currentMonth.getMonth() &&
                        selectedDate.getFullYear() === currentMonth.getFullYear()
                      const isToday =
                        new Date().toDateString() ===
                        new Date(currentMonth.getFullYear(), currentMonth.getMonth(), day).toDateString()

                      return (
                        <button
                          key={day}
                          onClick={() => handleDateSelect(day)}
                          className={`p-2 text-sm rounded-md transition-colors ${isSelected
                            ? "bg-cyan-500 text-white"
                            : isToday
                              ? "bg-cyan-100 dark:bg-cyan-900 text-cyan-600 dark:text-cyan-400"
                              : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                            }`}
                        >
                          {day}
                        </button>
                      )
                    })}
                  </div>

                  <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Time</label>
                    <input
                      type="time"
                      value={selectedTime}
                      onChange={(e) => setSelectedTime(e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-zinc-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
                    />
                  </div>

                  <div className="mb-4 p-3 bg-gray-50 dark:bg-zinc-800 rounded-md">
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                      Scheduled for:{" "}
                      <span className="font-medium text-gray-900 dark:text-gray-100">
                        {formatDate(selectedDate)} at {selectedTime}
                      </span>
                    </p>
                  </div>

                  <div className="flex space-x-2">
                    <button
                      onClick={() => setSchedulerOpen(false)}
                      className="flex-1 px-3 py-2 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 border border-gray-300 dark:border-gray-600 rounded-md transition-colors"
                    >
                      Cancel
                    </button>
                    <button
                      onClick={handleSchedulePost}
                      className="flex-1 px-3 py-2 bg-cyan-500 hover:bg-cyan-600 text-white font-medium rounded-md transition-colors"
                    >
                      Schedule
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}


      <Modal
        isOpen={linkModalOpen}
        onClose={() => {
          setLinkModalOpen(false)
          setLinkUrl("")
        }}
        title={t("Insert Link")}
        onSubmit={handleInsertLink}
        submitText={t("Insert Link")}
        showSubmit={true}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{t("URL")}</label>
            <input
              type="url"
              value={linkUrl}
              onChange={(e) => setLinkUrl(e.target.value)}
              placeholder={t("https://example.com")}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-zinc-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
            />
          </div>

          {linkUrl && (
            <div className="p-3 bg-gray-50 dark:bg-zinc-800 rounded-md">
              <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">{t("Preview")}:</p>
              <p className="text-sm text-blue-600 dark:text-blue-400">{linkUrl}</p>
            </div>
          )}
        </div>
      </Modal>

      <Modal
        isOpen={saveTemplateModalOpen}
        onClose={() => {
          setSaveTemplateModalOpen(false)
          setTemplateName("")
          setTemplateDescription("")
          setSaveAsTemplate(false)
        }}
        title={t("Save Template")}
        onSubmit={handleSaveTemplate}
        submitText={t("Save Template")}
        showSubmit={true}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {t("Template Name")}
            </label>
            <input
              type="text"
              value={templateName}
              onChange={(e) => setTemplateName(e.target.value)}
              placeholder={t("Enter template name")}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-zinc-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {t("Description")} ({t("Optional")})
            </label>
            <textarea
              value={templateDescription}
              onChange={(e) => setTemplateDescription(e.target.value)}
              placeholder={t("Describe what this template is for")}
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-zinc-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-cyan-500 focus:border-transparent resize-none"
            />
          </div>

          {/* Platform select */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Select Platform
            </label>
            <Select
              value={intendedPlatform}
              onValueChange={(value) => setIntendedPlatform(value)}
            >
              <SelectTrigger className="w-full min-w-[180px] bg-gray-50 border-gray-200 dark:bg-zinc-800 dark:border-none dark:text-neutral-200">
                <SelectValue placeholder="Choose a platform" />
              </SelectTrigger>
              <SelectContent>
                
                {platforms.map((platform) => (
                  <SelectItem key={platform.id} value={platform.id}>
                    {platform.name}
                  </SelectItem>
                ))}

              </SelectContent>
            </Select>
          </div>
        </div>
      </Modal>

      <Modal
        isOpen={hashtagModalOpen}
        onClose={() => {
          setHashtagModalOpen(false)
          setCustomHashtag("")
        }}
        title={t("Add Hashtag")}
        onSubmit={handleCustomHashtagInsert}
        submitText={t("Add Custom Hashtag")}
        showSubmit={customHashtag.trim().length > 0}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {t("Popular Hashtags")}
            </label>
            <div className="grid grid-cols-3 gap-2 max-h-48 overflow-y-auto">
              {popularHashtags.map((hashtag) => (
                <button
                  key={hashtag}
                  onClick={() => handleHashtagSelect(hashtag)}
                  className="px-3 py-2 text-sm bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg transition-colors text-left"
                >
                  {hashtag}
                </button>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {t("Custom Hashtag")}
            </label>
            <input
              type="text"
              value={customHashtag}
              onChange={(e) => setCustomHashtag(e.target.value)}
              placeholder={t("Enter custom hashtag")}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-zinc-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
              onKeyPress={(e) => {
                if (e.key === "Enter") {
                  handleCustomHashtagInsert()
                }
              }}
            />
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              {t("Don't include the # symbol - it will be added automatically")}
            </p>
          </div>

          {customHashtag && (
            <div className="p-3 bg-gray-50 dark:bg-zinc-800 rounded-md">
              <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">{t("Preview")}:</p>
              <p className="text-sm font-medium text-gray-900 dark:text-gray-100">
                {customHashtag.startsWith("#") ? customHashtag : `#${customHashtag}`}
              </p>
            </div>
          )}
        </div>
      </Modal>

      <AiAssistance
        isOpen={aiAssistanceOpen}
        onClose={() => setAiAssistanceOpen(false)}
        onApply={handleAITemplateApply}
        t={t}
        ai_modules={ai_modules}
        platforms = {platforms}
        templates = {aiTemplateList}
      />

      <SideGallery
        isOpen={galleryOpen}
        onClose={() => setGalleryOpen(false)}
        onApply={handleMediaApply}
        t={t}
        media={media}
      />

      <PostTemplate
        isOpen={postTemplateOpen}
        onClose={() => setPostTemplateOpen(false)}
        onApply={handleTemplateApply}
        t={t}
        templates={postTemplateList}
        platforms={platforms}
      />

      <InfoModal isOpen={infoModalOpen} onClose={() => setInfoModalOpen(false)} t={t} />
    </div>
  )
}
