"use client"

import { useState, useEffect } from "react"
import { FileText, PenTool, Clock, CheckCircle2, Plus } from "lucide-react"
import AppLayout from "@/Layouts/AppLayout"
import AccountSelection from "@/Components/Post/AccountSelection"
import ListView from "@/Components/Calendar/ListView"
import { Card, CardContent } from "@/Components/UI/Card"
import { Button } from "@/Components/UI/Button"
import { router } from "@inertiajs/react"
import { route } from "ziggy-js"
import useTranslate from "@/hooks/useTranslate"
import { motion, AnimatePresence } from "framer-motion";

const AllPostsIndex = ({ platforms, accounts, posts, pagination }) => {
  const t = useTranslate()
  const breadcrumbs = [
    { label: t("Home"), href: route("user.home") },
    { label: t("All Posts") }
  ]

  const [searchQuery, setSearchQuery] = useState("")
  const [openMenus, setOpenMenus] = useState({})
  const [activePostTab, setActivePostTab] = useState("all")
  const [postList, setPostList] = useState(posts)
  const [isLoadingMore, setIsLoadingMore] = useState(false)
  const [selectedAccounts, setSelectedAccounts] = useState([])
  const [activePlatform, setActivePlatform] = useState("all")

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

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

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

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

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

  const handleSelectedAccountsChange = (accounts) => {
    setSelectedAccounts(accounts)

    router.get(
      route("user.posts.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)

    router.get(
      route("user.posts.index"),
      {
        account_ids: selectedAccounts.map((acc) => acc.id),
        tab_key: activePostTab,
        search: searchQuery,
        platform: platform === "all" ? null : 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 = () => {
    // Add delete logic here
  }

  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 handleSearch = (e) => {
    setSearchQuery(e.target.value)

    router.get(
      route("user.posts.index"),
      {
        search: e.target.value,
        account_ids: selectedAccounts.map((acc) => acc.id),
        tab_key: activePostTab,
      },
      {
        preserveScroll: true,
        preserveState: true,
        only: ["posts"],
        onError: (errors) => console.error(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,
        search: searchQuery,
      },
      {
        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-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-6">
          <div className="flex items-center justify-between flex-wrap gap-4 mb-2">
            <div className="flex items-center gap-3">
              <div>
                <FileText className="h-6 w-6 text-primary" />
              </div>
              <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">
                {t("All Posts")}
              </h1>
            </div>

            {/* Create Post Button */}
            <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>
          <p className="text-gray-500 dark:text-gray-200">
            {t("View and manage all your social media posts across different platforms")}
          </p>
        </div>
      {/* Platform Tabs */}
      <div className="mb-6 overflow-x-auto">
        <div className="inline-flex bg-white dark:bg-zinc-900 rounded-lg p-1 gap-1 border border-gray-200 dark:border-zinc-800">
          <button
            onClick={() => handleActivePlatformChange("all")}
            className={`rounded-md px-4 py-2 text-sm font-medium transition-colors ${
              activePlatform === "all"
                ? "bg-gradient-to-r from-primary to-secondary text-white shadow-sm"
                : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
            }`}
          >
            {t("All Platforms")}
          </button>
          {platforms.map((platform) => (
            <button
              key={platform.slug}
              onClick={() => handleActivePlatformChange(platform.slug)}
              className={`rounded-md px-4 py-2 text-sm font-medium transition-colors ${
                activePlatform === platform.slug
                  ? "bg-gradient-to-r from-primary to-secondary text-white shadow-sm"
                  : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              }`}
            >
              {platform.name}
            </button>
          ))}
        </div>
      </div>
      <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          {/* Stats Cards */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
              <Card className="bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 hover:shadow-md transition-shadow">
                <CardContent className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-blue-100 dark:bg-blue-900/20 rounded-lg">
                      <FileText className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 dark:text-gray-400">{t("Total Posts")}</p>
                      <p className="text-xl font-bold text-gray-900 dark:text-white">{postList?.length || 0}</p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card className="bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 hover:shadow-md transition-shadow">
                <CardContent className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-amber-100 dark:bg-amber-900/20 rounded-lg">
                      <Clock className="w-5 h-5 text-amber-600 dark:text-amber-400" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 dark:text-gray-400">{t("Scheduled")}</p>
                      <p className="text-xl font-bold text-gray-900 dark:text-white">
                        {postList?.filter(post =>
                          post.status === 'SCHEDULE' ||
                          post.status === 'SCHEDULED'
                        )?.length || 0}
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card className="bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 hover:shadow-md transition-shadow">
                <CardContent className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-green-100 dark:bg-green-900/20 rounded-lg">
                      <CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 dark:text-gray-400">{t("Published")}</p>
                      <p className="text-xl font-bold text-gray-900 dark:text-white">
                        {postList?.filter(post =>
                          post.status === 'SUCCESS' ||
                          post.status === 'PUBLISHED'
                        )?.length || 0}
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card className="bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 hover:shadow-md transition-shadow">
                <CardContent className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
                      <PenTool className="w-5 h-5 text-gray-600 dark:text-gray-400" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 dark:text-gray-400">{t("Pending")}</p>
                      <p className="text-xl font-bold text-gray-900 dark:text-white">
                        {postList?.filter(post =>
                          post.status === 'PENDING'
                        )?.length || 0}
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
          </div> 

          {/* Main Layout: Always consistent structure */}
          <div className="flex flex-col lg:flex-row gap-6">
            {/* Account Filter Sidebar - Always visible */}
            <div className="w-full lg:w-80 flex-shrink-0 overflow-hidden max-h-[565px]">
              <Card className="bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 h-full overflow-y-auto rounded-2xl">
                <CardContent className="p-4">
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                    {t("Filter by Accounts")}
                  </h3>
                  <AccountSelection
                    t={t}
                    mode="simple"
                    onSelectedAccountsChange={handleSelectedAccountsChange}
                    accounts={accounts.filter(
                      activePlatform === "all" ? () => true : (acc) => acc.platform?.slug === activePlatform
                    )}
                    selectedAccountIds={selectedAccounts.map(acc => acc.id)}
                  />
                </CardContent>
              </Card>
            </div>

            {/* Main Content Area */}
            <div className="flex-1">
              {postList && postList.length > 0 ? (
                /* Posts List */
                <ListView
                  posts={postList}
                  onMenuAction={handleMenuAction}
                  openMenus={openMenus}
                  onToggleMenu={toggleMenu}
                  t={t}
                  onActiveTabChange={handleActivePostTabChange}
                  activePostTab={activePostTab}
                  pagination={pagination}
                  onLoadMore={handleLoadMore}
                  isLoadingMore={isLoadingMore}
                  searchQuery={searchQuery}
                  onSearch={handleSearch}
                />
              ) : !isLoadingMore ? (
                /* Professional Empty State */
                <div className="bg-white dark:bg-zinc-900 rounded-xl border border-gray-200 dark:border-zinc-800">
                  <div className="flex flex-col items-center justify-center py-20 px-8 text-center">
                    {/* Modern Illustration */}
                    <div className="relative mb-8">
                      <div className="w-32 h-32 bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-900/20 dark:to-indigo-900/20 rounded-full flex items-center justify-center mb-4">
                        <div className="w-20 h-20 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center transform rotate-6">
                          <FileText className="w-10 h-10 text-white" />
                        </div>
                      </div>
                      {/* Floating Elements */}
                      <div className="absolute -top-2 -right-2 w-6 h-6 bg-gradient-to-r from-amber-400 to-orange-500 rounded-full opacity-80"></div>
                      <div className="absolute -bottom-1 -left-3 w-4 h-4 bg-gradient-to-r from-green-400 to-emerald-500 rounded-full opacity-70"></div>
                      <div className="absolute top-1/2 -left-4 w-3 h-3 bg-gradient-to-r from-purple-400 to-pink-500 rounded-full opacity-60"></div>
                    </div>

                    {/* Content */}
                    <div className="max-w-md mx-auto">
                      <h3 className="text-2xl font-bold text-gray-900 dark:text-white mb-3">
                        {searchQuery || selectedAccounts.length > 0 || activePlatform !== "all"
                          ? t("No Posts Found")
                          : t("Ready to Create?")}
                      </h3>

                      <p className="text-gray-600 dark:text-gray-400 mb-8 text-lg leading-relaxed">
                        {searchQuery || selectedAccounts.length > 0 || activePlatform !== "all"
                          ? t("No posts match your current filters. Try adjusting your search criteria or creating a new post.")
                          : t("Your content journey starts here. Create engaging posts and watch your social media presence grow!")}
                      </p>

                      {/* Action Buttons */}
                      <div className="flex flex-col sm:flex-row gap-4 justify-center">
                        <Button
                          onClick={() => router.get(route("user.post.create"))}
                          className="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-105"
                          size="lg"
                        >
                          <Plus className="w-5 h-5 mr-2" />
                          {searchQuery || selectedAccounts.length > 0 || activePlatform !== "all"
                            ? t("Create New Post")
                            : t("Create Your First Post")
                          }
                        </Button>

                        {(searchQuery || selectedAccounts.length > 0 || activePlatform !== "all") && (
                          <Button
                            variant="outline"
                            onClick={() => {
                              setSearchQuery("")
                              setSelectedAccounts([])
                              setActivePlatform("all")
                              router.get(route("user.posts.index"))
                            }}
                            className="border-gray-300 dark:border-zinc-600 hover:bg-gray-50 dark:hover:bg-zinc-800 transition-all duration-200"
                            size="lg"
                          >
                            {t("Clear All Filters")}
                          </Button>
                        )}
                      </div>

                      {/* Additional Context for New Users */}
                      {!searchQuery && selectedAccounts.length === 0 && activePlatform === "all" && (
                        <div className="mt-8 pt-6 border-t border-gray-200 dark:border-zinc-700">
                          <p className="text-sm text-gray-500 dark:text-gray-400 mb-4">
                            {t("Need inspiration? Here's what you can do:")}
                          </p>
                          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-xs">
                            <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                              <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                              <span>{t("Share updates")}</span>
                            </div>
                            <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                              <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                              <span>{t("Schedule content")}</span>
                            </div>
                            <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                              <div className="w-2 h-2 bg-purple-500 rounded-full"></div>
                              <span>{t("Engage audience")}</span>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              ) : null}
            </div>
          </div>

        </motion.div>
      </div>
    </AppLayout>
  )
}

export default AllPostsIndex