"use client"

import { useState, useEffect } from "react"
import { Calendar, Clock, Users, BarChart3, Plus } from "lucide-react"
import { Button } from "@/Components/UI/Button"
import AppLayout from "@/Layouts/AppLayout"
import AccountSelection from "@/Components/Post/AccountSelection"
import CalendarView from "@/Components/Calendar/CalendarView"
import ListView from "@/Components/Calendar/ListView"
import { Tabs, TabsList, TabsTrigger } from "@/Components/UI/Tabs"
import { router } from "@inertiajs/react"
import { route } from "ziggy-js"
import { motion, AnimatePresence } from "framer-motion";

const CalendarIndex = ({ platforms, accounts, posts, pagination }) => {
  const breadcrumbs = [{ label: "Home", href: route("user.home") }, { label: "Calendar" }]

  const [activeTab, setActiveTab] = useState("calendar")
  const [openMenus, setOpenMenus] = useState({})
  const [activePostTab, setActivePostTab] = useState("all");

  const [currentDate, setCurrentDate] = useState(new Date())
  const [dateRange, setDateRange] = useState({
    startDate: new Date(),
    endDate: new Date(new Date().setMonth(new Date().getMonth() + 1)),
  })

  const [postList, setPostList] = useState(posts)
  const [isLoadingMore, setIsLoadingMore] = useState(false)

  const [selectedAccounts, setSelectedAccounts] = useState([])
  const [activePlatform, setActivePlatform] = useState("facebook")
  const [draggedPost, setDraggedPost] = useState(null)

  const t = (key) => key

  useEffect(() => {
    setPostList(posts)
  }, [posts])

  // Close menus when clicking outside
  useEffect(() => {
    const handleClickOutside = () => {
      setOpenMenus({})
    }

    document.addEventListener('click', handleClickOutside)
    return () => {
      document.removeEventListener('click', handleClickOutside)
    }
  }, [])

  // Calculate stats for header
  const scheduledPosts = posts.filter(post => post.status === 'SCHEDULE').length
  const totalPosts = posts.length
  const connectedAccounts = accounts.length
  const activePlatforms = [...new Set(accounts.map(acc => acc.platform.name))].length

  const handleActivePostTabChange = (tab) => {
    setActivePostTab(tab);

    router.get(
      route("user.calender.index"),
      {
        account_ids: accounts.map((acc) => acc.id),
        tab_key: tab,
      },
      {
        preserveScroll: true,
        preserveState: true,
        only: ["posts", "tab"],
      }
    );
  };


  const handleSelectedAccountsChange = (accounts) => {
    router.get(
      route("user.calender.index"),
      {
        account_ids: accounts.map((acc) => acc.id),
        tab_key: activePostTab,
      },
      {
        preserveScroll: true,
        preserveState: true,
        only: ["posts"],
        onError: (errors) => console.error(errors),
      }
    );
  };


  const handleActivePlatformChange = (platform) => {
    setActivePlatform(platform)

    // Optionally refresh posts when platform changes
    router.get(
      route("user.calender.index"),
      {
        account_ids: selectedAccounts.map((acc) => acc.id),
        tab_key: activePostTab,
        platform: platform,
      },
      {
        preserveScroll: true,
        preserveState: true,
        only: ["posts"],
        onError: (errors) => console.error(errors),
      }
    )
  }

  const toggleMenu = (postId, event) => {
    event?.stopPropagation()
    setOpenMenus((prevMenus) => {
      // If the clicked menu is already open, close it
      if (prevMenus[postId]) {
        return {}
      }
      // Otherwise, close all menus and open only the clicked one
      return { [postId]: true }
    })
  }

  const handleDelete = (postId) => {

  };

  const handlePublish = (postId) => {
    router.post(route("user.post.send"), {
      id: postId,
    })
  };



  const handleMenuAction = (postId, action) => {
    // Close the menu first
    setOpenMenus({})

    switch (action) {
      case 'delete':
        handleDelete(postId);
        break;
      case 'publish':
        handlePublish(postId);
        break;
      case 'preview':
        handlePreview(postId);
        break;
      case 'edit':
        handleEdit(postId);
        break;
      default:
        console.warn(`Unknown action "${action}" for post ${postId}`);
    }
  };

  const handlePreview = (postId) => {
    router.get(route("user.post.preview", postId))
  }

  const handleEdit =(postId) => {
    router.get(route("user.post.edit", postId))
  }

  const handleDragStart = (e, post) => {

    e.dataTransfer.setData("text/plain", post.id)
    setDraggedPost(post)
  }

  const handleScheduleChange = async (postId, newDateString) => {
    // Validate the new date
    const newDate = new Date(newDateString)
    const today = new Date()
    today.setHours(0, 0, 0, 0)

    // Check if trying to schedule in the past
    if (newDate < today) {
      // Show error notification
      const errorMessage = "Cannot schedule post in the past. Please select a future date."

      // Create toast 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>${errorMessage}</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)

      return Promise.reject(new Error(errorMessage))
    }

    // Optimistically update the UI
    setPostList((prev) =>
      prev.map((post) =>
        post.id === postId
          ? { ...post, dateGroup: newDateString, date: newDateString, schedule_time: newDateString }
          : post
      )
    )

    return new Promise((resolve, reject) => {
      router.post(route("user.post.reschedule"), {
        id: postId,
        schedule_time: newDateString,
      }, {
        preserveScroll: true,
        preserveState: false,
        onSuccess: (page) => {
          // Show success notification
          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>Post rescheduled 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)

          resolve()
        },
        onError: (errors) => {
          console.error('Reschedule error:', errors)

          // Revert the optimistic update
          setPostList((prev) =>
            prev.map((post) => {
              if (post.id === postId) {
                const originalPost = posts.find(p => p.id === postId)
                return originalPost || post
              }
              return post
            })
          )

          // 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 reschedule post. 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)

          reject(errors)
        },
      })
    })
  }


  const handleLoadMore = () => {
    if (!pagination || !pagination.next_page_url || isLoadingMore) return

    setIsLoadingMore(true)

    router.get(
      pagination.next_page_url,
      {
        account_ids: selectedAccounts.map((acc) => acc.id),
        tab_key: activePostTab,
      },
      {
        preserveScroll: true,
        preserveState: true,
        only: ["posts", "pagination"],
        onSuccess: (page) => {
          setPostList((prevPosts) => [...prevPosts, ...page.props.posts])
          setIsLoadingMore(false)
        },
        onError: (errors) => {
          console.error(errors)
          setIsLoadingMore(false)
        },
      }
    )
  }



  return (
    <AppLayout breadcrumbs={breadcrumbs}>
      <div className="flex-1 p-3 sm:p-4 lg:p-6 overflow-auto bg-gradient-to-br from-gray-50 to-gray-100 dark:from-zinc-950 dark:to-black min-h-screen">
        {/* Header */}
        <div className="mb-4 sm:mb-6">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-2 gap-3 sm:gap-0">
            <div className="flex items-center gap-2 sm:gap-3">
              <div>
                <Calendar className="h-5 w-5 sm:h-6 sm:w-6 text-primary" />
              </div>
              <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">
                {t("Content Calendar")}
              </h1>
            </div>
            {posts && posts.length > 0 && (
              <button
                onClick={() => router.get(route("user.post.create"))}
                className="flex items-center gap-2 px-3 sm:px-4 py-2 bg-gradient-to-r from-primary to-secondary hover:from-primary-dark hover:to-secondary-dark text-white font-medium text-xs sm:text-sm rounded-lg shadow-sm hover:shadow-md transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:ring-offset-2 w-full sm:w-auto justify-center sm:justify-start"
              >
                <Plus className="h-3 w-3 sm:h-4 sm:w-4" />
                {t("Add Campaign")}
              </button>
            )}
          </div>
          <p className="text-xs sm:text-sm text-gray-500 dark:text-gray-200">
            {t("Plan, schedule, and manage your social media content across all platforms")}
          </p>
        </div>

        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-4 sm:mb-6 gap-4 sm:gap-0">
          <div className="flex gap-1 overflow-x-auto">
            <Tabs defaultValue="calendar" onValueChange={setActiveTab} className="w-full sm:w-auto">
              <TabsList className="inline-flex bg-white dark:bg-zinc-900 rounded-lg p-1 gap-1 min-w-max">
                <TabsTrigger
                  value="calendar"
                  className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-3 sm:px-4 py-1.5 sm:py-2 text-xs sm:text-sm font-medium transition-colors whitespace-nowrap"
                >
                  {t("Calendar")}
                </TabsTrigger>
                <TabsTrigger
                  value="postlist"
                  className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-3 sm:px-4 py-1.5 sm:py-2 text-xs sm:text-sm font-medium transition-colors whitespace-nowrap"
                >
                  {t("Post List")}
                </TabsTrigger>
              </TabsList>
            </Tabs>
          </div>

          <Button
            onClick={() => router.get(route("user.post.create"))}
            className="bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary shadow-sm hover:shadow-md transition-all duration-200"
          >
            <Plus className="w-5 h-5 mr-2" />
            {t("Create Post")}
          </Button>
        </div>
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.2 }}>
          <div className="flex flex-col xl:flex-row gap-4 sm:gap-6">
            <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(acc => acc.id)}
                showAllPlatforms={true}
              />
            </div>

            {activeTab === "calendar" && (
              <CalendarView
                currentDate={currentDate}
                setCurrentDate={setCurrentDate}
                dateRange={dateRange}
                setDateRange={setDateRange}
                posts={postList}
                onMenuAction={handleMenuAction}
                openMenus={openMenus}
                onToggleMenu={toggleMenu}
                onDragStart={handleDragStart}
                handleScheduleChange={handleScheduleChange}
                draggedPost={draggedPost}
              />
            )}

            {activeTab === "postlist" && (
              <ListView
                posts={postList}
                onMenuAction={handleMenuAction}
                openMenus={openMenus}
                onToggleMenu={toggleMenu}
                t={t}
                onActiveTabChange={handleActivePostTabChange}
                activePostTab={activePostTab}
                pagination={pagination}
                onLoadMore={handleLoadMore}
                isLoadingMore={isLoadingMore}
              />
            )}
          </div>
        </motion.div>
      </div>
    </AppLayout>
  )
}

export default CalendarIndex