import AppLayout from "@/Layouts/AppLayout"
import { useState, useMemo } from "react"
import useTranslate from "@/hooks/useTranslate"
import PerformanceSummary from "@/Components/Analytics/PerformanceSummary"
import PostCard from "@/Components/Analytics/PostCard"
import PremiumPreloader from "@/Components/PremiumPreloader"
import usePreloader from "@/hooks/usePreloader"
import TypingAnimation from "@/Components/UI/TypingAnimation"
import EngagementChart from "@/Components/Analytics/EngagementChart"
import AccountPerformanceChart from "@/Components/Analytics/AccountPerformanceChart"
import SocialAccounts from "@/Components/Analytics/SocialAccounts"
import { route } from "ziggy-js"
import { router, usePage } from "@inertiajs/react"
import { motion, AnimatePresence } from "framer-motion"
import { BarChart3, Sun, Moon, CloudSun, Sunrise } from "lucide-react"

export default function DashboardPage({ platforms, AnalyticalData }) {
  const t = useTranslate()
  const { showPreloader, siteName, siteLogo, primaryColor, secondaryColor, onComplete } = usePreloader();
  const { props } = usePage();
  const { auth } = props;

  // Get user name (prefer name over email username)
  const userName = auth?.user?.name || auth?.user?.email?.split('@')[0] || 'User';

  // Get time-based greeting
  const getGreeting = () => {
    const hour = new Date().getHours();

    if (hour >= 5 && hour < 12) {
      return { text: "Good Morning", emoji: "☀️", icon: Sunrise };
    } else if (hour >= 12 && hour < 17) {
      return { text: "Good Afternoon", emoji: "🌤️", icon: CloudSun };
    } else if (hour >= 17 && hour < 21) {
      return { text: "Good Evening", emoji: "🌅", icon: Sun };
    } else {
      return { text: "Good Night", emoji: "🌙", icon: Moon };
    }
  };

  const greeting = useMemo(() => getGreeting(), []);
  const fullGreeting = `${greeting.text} ${greeting.emoji}, ${userName}`;

  const breadcrumbs = [
    { label: "Dashboard", href: route("user.home") },
  ]


  const [activePlatform, setActivePlatform] = useState(route().params.slug || null)

  const handleTabChange = (platform) => {
    if (platform === "all") {
      router.get(route("user.home"))
      setActivePlatform(null)
    } else {
      router.get(route("user.home"), {
        slug: platform
      })
      setActivePlatform(platform)
    }
  }

  return (
    <>
      {showPreloader && (
        <PremiumPreloader
          siteName={siteName}
          siteLogo={siteLogo}
          primaryColor={primaryColor}
          secondaryColor={secondaryColor}
          onComplete={onComplete}
        />
      )}

      <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>
                  <BarChart3 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("Dashboard")}
                </h1>
              </div>

              {/* Greeting - Stack on mobile */}
              <motion.div
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.5, delay: 0.2 }}
                className="flex items-center gap-2"
              >
                <greeting.icon className="h-4 w-4 sm:h-5 sm:w-5 text-yellow-500 dark:text-yellow-400" />
                <TypingAnimation
                  text={fullGreeting}
                  speed={60}
                  className="text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-300"
                />
              </motion.div>
            </div>

            <p className="text-xs sm:text-sm text-gray-500 dark:text-gray-400">
              {t("Monitor your social media performance in real-time")}
            </p>
          </div>

          <div className="space-y-6 sm:space-y-6">
            {/* Enhanced Platform Tabs - Responsive */}
            <div className="w-full overflow-x-auto">
              <div className="inline-flex min-w-full">
                <div className="bg-white dark:bg-zinc-900 rounded-lg p-1 inline-flex gap-1 border border-gray-200 dark:border-zinc-800">
                  <button
                    key="all"
                    onClick={() => handleTabChange("all")}
                    className={`relative inline-block rounded-lg px-3 sm:px-6 py-2 sm:py-2 text-xs sm:text-sm font-semibold transition-all duration-200 whitespace-nowrap ${
                      activePlatform === null
                        ? "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"
                    }`}
                  >
                    All Platforms
                    {activePlatform === null && (
                      <motion.div
                        layoutId="activeTab"
                        className="absolute inset-0 bg-gradient-to-r from-primary to-secondary rounded-lg -z-10"
                        transition={{ type: "spring", bounce: 0.2, duration: 0.5 }}
                      />
                    )}
                  </button>
                  {platforms.map((platform) => (
                    <button
                      key={platform.slug}
                      onClick={() => handleTabChange(platform.slug)}
                      className={`relative inline-block rounded-lg px-3 sm:px-6 py-2 sm:py-2 text-xs sm:text-sm font-semibold transition-all duration-200 whitespace-nowrap ${
                        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}
                      {activePlatform === platform.slug && (
                        <motion.div
                          layoutId="activeTab"
                          className="absolute inset-0 bg-gradient-to-r from-primary to-secondary rounded-lg -z-10"
                          transition={{ type: "spring", bounce: 0.2, duration: 0.5 }}
                        />
                      )}
                    </button>
                  ))}
                </div>
              </div>
            </div> 

            <AnimatePresence mode="wait">
              <motion.div
                key={activePlatform || "all"}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.15, ease: "easeInOut" }}
                className="space-y-6 sm:space-y-6"
              >
                {/* Performance Summary */}
                <PerformanceSummary
                  data={AnalyticalData.postSummary}
                  metrics={AnalyticalData.postSummary.metrics}
                />

                {/* First Row - Social Accounts & Top Posts - Mobile stack, Desktop side-by-side */}
                <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 sm:gap-6 lg:gap-6">
                  <div className="xl:col-span-1">
                    <SocialAccounts data={AnalyticalData.socialAccounts} />
                  </div>

                  <div className="xl:col-span-2">
                    <PostCard data={AnalyticalData.topPosts} col="3" />
                  </div>
                </div>

                {/* Second Row - Engagement Chart & Account Performance - Mobile stack, Desktop side-by-side */}
                <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 sm:gap-6 lg:gap-6">
                  <div className="xl:col-span-2 order-2 xl:order-1">
                    <EngagementChart data={AnalyticalData.engagementAnalytics} />
                  </div>

                  <div className="xl:col-span-1 order-1 xl:order-2">
                    <AccountPerformanceChart
                      data={AnalyticalData.accountPerformance}
                      accounts={AnalyticalData.accountPerformance.accounts}
                    />
                  </div>
                </div>
              </motion.div>
            </AnimatePresence>
          </div>
        </div>  
      </AppLayout>
    </>
  )
}