"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import axios from "axios";
import { ApiServerBaseUrl } from "@/utils/baseurl.utils";
import {
    Instagram,
    UserCircle2,
    TrendingUp,
    BarChart3,
    MessageSquare,
    Image as ImageIcon,
    Shield,
    CheckCircle,
    AlertCircle,
    Sparkles,
    Zap,
    Users,
    Clock,
    Globe
} from "lucide-react";

const DashboardPage = () => {
    const [connectionStatus, setConnectionStatus] = useState<"connected" | "not_connected" | "loading" | "error">("loading");
    const [instagramUsername, setInstagramUsername] = useState<string | null>(null);
    const [stats, setStats] = useState({
        posts: 0,
        comments: 0,
        followers: 0
    });

    // Check Instagram connection status
    useEffect(() => {
        async function checkConnection() {
            try {
                const userId = localStorage.getItem("user_email");
                const res = await axios.get(
                    `${ApiServerBaseUrl}/social/auth/status`,
                    { params: { userId }, withCredentials: true }
                );

                if (res.data.connected) {
                    setConnectionStatus("connected");
                    if (res.data.username) {
                        setInstagramUsername(res.data.username);
                    }
                    // Fetch basic stats if connected
                    fetchInstagramStats();
                } else {
                    setConnectionStatus("not_connected");
                }
            } catch (err) {
                console.error(err);
                setConnectionStatus("error");
            }
        }

        async function fetchInstagramStats() {
            try {
                // This would be replaced with your actual API call
                // For now, using mock data
                setStats({
                    posts: 42,
                    comments: 156,
                    followers: 1250
                });
            } catch (err) {
                console.error("Failed to fetch stats:", err);
            }
        }

        checkConnection();
    }, []);

    const cards = [
        {
            name: "Instagram Media",
            icon: <ImageIcon size={32} className="text-pink-500" />,
            description:
                "Browse and manage your Instagram posts, stories, and media library.",
            link: "/social-media-posts",
            title: "View and organize your Instagram media content",
            status: connectionStatus === "connected" ? "active" : "requires-connection",
            badge: connectionStatus === "connected" ? "Connected" : "Connect Required"
        },
        {
            name: "Social Media Channels",
            icon: <Globe size={32} className="text-cyan-400" />,
            description:
                "Manage all your connected social media profiles and channels in one place.",
            link: "/social-media-channels",
            title: "Toggle and manage your connected social media channels",
            status: "active",
            badge: "Manage"
        },
        {
            name: "Performance Insights",
            icon: <BarChart3 size={32} className="text-green-500" />,
            description:
                "Track engagement, reach, and growth metrics for your Instagram content.",
            link: "/insights",
            title: "View analytics and performance insights",
            status: connectionStatus === "connected" ? "active" : "requires-connection",
            badge: connectionStatus === "connected" ? "Available" : "Connect Required"
        },
        {
            name: "Comment Management",
            icon: <MessageSquare size={32} className="text-blue-500" />,
            description:
                "Reply, hide, or delete comments across your Instagram posts efficiently.",
            link: "/comments",
            title: "Manage Instagram comments from one dashboard",
            status: connectionStatus === "connected" ? "active" : "requires-connection",
            badge: connectionStatus === "connected" ? "Ready" : "Connect Required"
        },
        {
            name: "Account Settings",
            icon: <UserCircle2 size={32} className="text-purple-400" />,
            description: "Manage your profile, billing, subscription, and preferences.",
            link: "/account-settings",
            title: "Account configuration and settings",
            status: "active",
            badge: "Settings"
        },
        {
            name: "Quick Actions",
            icon: <Zap size={32} className="text-yellow-500" />,
            description:
                "Quick access to common tasks and time-saving features.",
            link: "/quick-actions",
            title: "Quick action shortcuts",
            status: "active",
            badge: "New"
        },
    ];

    const quickStats = [
        {
            label: "Instagram Posts",
            value: stats.posts || "-",
            icon: <ImageIcon className="w-5 h-5 text-pink-400" />,
            color: "from-pink-500/20 to-pink-600/10"
        },
        {
            label: "Total Comments",
            value: stats.comments || "-",
            icon: <MessageSquare className="w-5 h-5 text-blue-400" />,
            color: "from-blue-500/20 to-blue-600/10"
        },
        {
            label: "Followers",
            value: stats.followers ? `${stats.followers}` : "-",
            icon: <Users className="w-5 h-5 text-green-400" />,
            color: "from-green-500/20 to-green-600/10"
        }
    ];

    const benefits = [
        {
            icon: <Clock className="w-5 h-5" />,
            text: "Save hours weekly on social media management"
        },
        {
            icon: <Users className="w-5 h-5" />,
            text: "Engage with your audience more effectively"
        },
        {
            icon: <BarChart3 className="w-5 h-5" />,
            text: "Make data-driven decisions with insights"
        },
        {
            icon: <Shield className="w-5 h-5" />,
            text: "Complete control over your content and interactions"
        }
    ];

    return (
        <div className="min-h-screen bg-gradient-to-b from-[#0a0a0a] to-[#111111] p-4 md:p-6 relative overflow-x-hidden">
            {/* Floating background bubbles */}
            <div className="absolute top-20 left-[5%] w-24 h-24 rounded-full bg-pink-500/20 blur-xl animate-float"></div>
            <div className="absolute top-40 right-[10%] w-32 h-32 rounded-full bg-blue-500/15 blur-xl animate-float-slow"></div>
            <div className="absolute bottom-40 left-[20%] w-20 h-20 rounded-full bg-purple-500/20 blur-xl animate-float"></div>
            <div className="absolute bottom-20 right-[15%] w-28 h-28 rounded-full bg-cyan-500/15 blur-xl animate-float-slow"></div>

            {/* Main container */}
            <div className="max-w-7xl mx-auto relative z-10">
                {/* Header Section */}
                <div className="mb-10">
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
                        <div className="flex items-center gap-4">
                            <div className="relative">
                                <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-blue-600 to-purple-600 flex items-center justify-center shadow-lg shadow-blue-500/30">
                                    <Instagram className="w-8 h-8 text-white" />
                                </div>
                                <div className="absolute -top-2 -right-2 w-6 h-6 rounded-full bg-green-500 border-2 border-[#111111] flex items-center justify-center">
                                    <div className="w-2 h-2 rounded-full bg-white"></div>
                                </div>
                            </div>
                            <div>
                                <h1 className="text-3xl md:text-4xl font-bold text-white">
                                    Social Buddy Dashboard
                                </h1>
                                <p className="text-gray-300 mt-1">
                                    Welcome back! Manage your social presence effortlessly.
                                </p>
                            </div>
                        </div>

                        {/* Connection Status Badge */}
                        <div className={`px-6 py-3 rounded-xl border backdrop-blur-sm ${
                            connectionStatus === "connected" 
                                ? "bg-green-900/20 border-green-500/30" 
                                : connectionStatus === "not_connected"
                                ? "bg-orange-900/20 border-orange-500/30"
                                : "bg-gray-900/20 border-gray-500/30"
                        }`}>
                            <div className="flex items-center gap-3">
                                <div className={`w-3 h-3 rounded-full animate-pulse ${
                                    connectionStatus === "connected" 
                                        ? "bg-green-500" 
                                        : connectionStatus === "not_connected"
                                        ? "bg-orange-500"
                                        : "bg-gray-500"
                                }`}></div>
                                <div>
                                    <p className="text-white font-medium">
                                        {connectionStatus === "connected" 
                                            ? "Instagram Connected" 
                                            : connectionStatus === "not_connected"
                                            ? "Instagram Not Connected"
                                            : "Checking Connection..."}
                                    </p>
                                    {connectionStatus === "connected" && instagramUsername && (
                                        <p className="text-gray-400 text-sm">@{instagramUsername}</p>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Quick Stats */}
                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-10">
                        {quickStats.map((stat, index) => (
                            <div 
                                key={index}
                                className={`bg-gradient-to-br ${stat.color} backdrop-blur-sm rounded-xl p-5 border border-white/10`}
                            >
                                <div className="flex items-center justify-between mb-3">
                                    <span className="text-gray-300 text-sm">{stat.label}</span>
                                    {stat.icon}
                                </div>
                                <div className="text-2xl font-bold text-white">{stat.value}</div>
                                {connectionStatus !== "connected" && stat.value === "-" && (
                                    <p className="text-gray-400 text-xs mt-2">Connect Instagram to view</p>
                                )}
                            </div>
                        ))}
                    </div>
                </div>

                {/* Main Content Grid */}
                <div className="grid lg:grid-cols-3 gap-8">
                    {/* Left Column - Features Grid */}
                    <div className="lg:col-span-2">
                        <div className="mb-8">
                            <h2 className="text-2xl font-bold text-white mb-6 flex items-center gap-3">
                                <Sparkles className="w-6 h-6 text-yellow-400" />
                                Available Features
                            </h2>
                            <p className="text-gray-300 mb-6">
                                All the tools you need to manage your Instagram presence efficiently.
                            </p>
                            
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                {cards.map((card) => (
                                    <Link
                                        key={card.name}
                                        href={card.link}
                                        title={card.title}
                                        className={`
                                            relative group
                                            bg-gradient-to-br from-gray-900/90 to-black/90
                                            p-6 
                                            rounded-2xl 
                                            shadow-lg 
                                            border border-white/10 
                                            transition-all 
                                            duration-300
                                            hover:scale-[1.02] 
                                            hover:shadow-2xl
                                            hover:border-blue-500/30
                                            min-h-[180px]
                                            flex flex-col
                                            overflow-hidden
                                            ${card.status === "requires-connection" ? "opacity-80" : ""}
                                        `}
                                    >
                                        {/* Status Badge */}
                                        <div className={`absolute top-4 right-4 px-3 py-1 rounded-full text-xs font-medium ${
                                            card.status === "requires-connection"
                                                ? "bg-orange-500/20 text-orange-400 border border-orange-500/30"
                                                : "bg-blue-500/20 text-blue-400 border border-blue-500/30"
                                        }`}>
                                            {card.badge}
                                        </div>

                                        {/* Icon */}
                                        <div className="w-12 h-12 rounded-xl flex items-center justify-center mb-4 bg-gradient-to-br from-white/10 to-white/5 backdrop-blur-sm">
                                            {card.icon}
                                        </div>

                                        {/* Content */}
                                        <div className="flex-grow">
                                            <h2 className="text-xl font-bold text-white mb-2">
                                                {card.name}
                                            </h2>
                                            <p className="text-gray-300 text-sm leading-relaxed">
                                                {card.description}
                                            </p>
                                        </div>

                                        {/* Arrow indicator */}
                                        <div className="mt-4 flex justify-between items-center">
                                            {card.status === "requires-connection" && connectionStatus === "not_connected" ? (
                                                <span className="text-sm text-orange-400 flex items-center gap-2">
                                                    <AlertCircle className="w-4 h-4" />
                                                    Connect Instagram first
                                                </span>
                                            ) : (
                                                <span className="text-sm text-gray-400">Click to access</span>
                                            )}
                                            <div className={`
                                                w-8 h-8 
                                                rounded-full 
                                                flex items-center justify-center
                                                transition-colors duration-300
                                                ${card.status === "requires-connection" && connectionStatus === "not_connected"
                                                    ? "bg-gray-500/20 text-gray-400"
                                                    : "bg-white/10 text-white/60 group-hover:bg-blue-500/20 group-hover:text-white"
                                                }
                                            `}>
                                                <svg 
                                                    className="w-4 h-4" 
                                                    fill="none" 
                                                    stroke="currentColor" 
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
                                                </svg>
                                            </div>
                                        </div>

                                        {/* Hover overlay */}
                                        <div
                                            className="
                                            absolute inset-0 rounded-2xl 
                                            bg-gradient-to-br from-blue-500/5 via-transparent to-pink-500/5 
                                            opacity-0 group-hover:opacity-100 
                                            transition-opacity duration-500 pointer-events-none
                                        "
                                        ></div>
                                    </Link>
                                ))}
                            </div>
                        </div>

                        {/* Connection Prompt */}
                        {connectionStatus === "not_connected" && (
                            <div className="bg-gradient-to-r from-blue-900/20 to-purple-900/20 rounded-2xl p-8 border border-blue-500/30 backdrop-blur-xl mb-8">
                                <div className="flex items-start gap-4">
                                    <div className="w-12 h-12 rounded-xl bg-blue-500/20 flex items-center justify-center flex-shrink-0">
                                        <Instagram className="w-6 h-6 text-blue-400" />
                                    </div>
                                    <div>
                                        <h3 className="text-xl font-bold text-white mb-3">Connect Your Instagram Account</h3>
                                        <p className="text-gray-300 mb-4">
                                            Unlock the full potential of Social Buddy by connecting your Instagram account. 
                                            Access media management, insights, and comment tools in one dashboard.
                                        </p>
                                        <Link
                                            href="/social-media-connect"
                                            className="inline-flex items-center gap-2 px-6 py-3 rounded-xl bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-semibold transition-all duration-300 hover:scale-105"
                                        >
                                            <Sparkles className="w-5 h-5" />
                                            Connect Instagram Now
                                        </Link>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Right Column - Sidebar */}
                    <div className="space-y-8">
                        {/* Benefits Card */}
                        <div className="bg-gradient-to-br from-gray-900/90 to-black/90 backdrop-blur-xl rounded-2xl p-6 border border-white/10 shadow-2xl">
                            <h3 className="text-xl font-bold text-white mb-6 flex items-center gap-3">
                                <Zap className="w-5 h-5 text-yellow-400" />
                                Why Social Buddy?
                            </h3>
                            <div className="space-y-4">
                                {benefits.map((benefit, index) => (
                                    <div key={index} className="flex items-start gap-3">
                                        <div className="w-6 h-6 rounded-full bg-green-500/20 flex items-center justify-center flex-shrink-0 mt-1">
                                            <div className="text-green-400">
                                                {benefit.icon}
                                            </div>
                                        </div>
                                        <p className="text-gray-300 text-sm">{benefit.text}</p>
                                    </div>
                                ))}
                            </div>
                        </div>

                        {/* Connection Status Card */}
                        <div className="bg-gradient-to-br from-gray-900/90 to-black/90 backdrop-blur-xl rounded-2xl p-6 border border-white/10 shadow-2xl">
                            <h3 className="text-xl font-bold text-white mb-4">Connection Status</h3>
                            <div className="space-y-4">
                                <div className="flex items-center justify-between p-4 rounded-xl bg-white/5">
                                    <div className="flex items-center gap-3">
                                        <Instagram className={`w-6 h-6 ${
                                            connectionStatus === "connected" ? "text-green-400" : "text-gray-400"
                                        }`} />
                                        <span className="text-white">Instagram</span>
                                    </div>
                                    <div className={`px-3 py-1 rounded-full text-sm font-medium ${
                                        connectionStatus === "connected"
                                            ? "bg-green-500/20 text-green-400"
                                            : connectionStatus === "not_connected"
                                            ? "bg-orange-500/20 text-orange-400"
                                            : "bg-gray-500/20 text-gray-400"
                                    }`}>
                                        {connectionStatus === "connected" ? "Connected" : 
                                         connectionStatus === "not_connected" ? "Not Connected" : 
                                         "Checking..."}
                                    </div>
                                </div>
                                <div className="space-y-3">
                                    <div className="flex items-center justify-between text-sm">
                                        <span className="text-gray-400">Media Access</span>
                                        <span className={`${connectionStatus === "connected" ? "text-green-400" : "text-gray-500"}`}>
                                            {connectionStatus === "connected" ? "✓ Available" : "—"}
                                        </span>
                                    </div>
                                    <div className="flex items-center justify-between text-sm">
                                        <span className="text-gray-400">Insights Access</span>
                                        <span className={`${connectionStatus === "connected" ? "text-green-400" : "text-gray-500"}`}>
                                            {connectionStatus === "connected" ? "✓ Available" : "—"}
                                        </span>
                                    </div>
                                    <div className="flex items-center justify-between text-sm">
                                        <span className="text-gray-400">Comment Management</span>
                                        <span className={`${connectionStatus === "connected" ? "text-green-400" : "text-gray-500"}`}>
                                            {connectionStatus === "connected" ? "✓ Available" : "—"}
                                        </span>
                                    </div>
                                </div>
                                {connectionStatus === "not_connected" && (
                                    <Link
                                        href="/social-media-connect"
                                        className="block w-full text-center py-3 rounded-xl bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-medium transition-all duration-300 hover:scale-105 mt-4"
                                    >
                                        Connect Instagram
                                    </Link>
                                )}
                                {connectionStatus === "connected" && (
                                    <Link
                                        href="/social-media-connect"
                                        className="block w-full text-center py-3 rounded-xl bg-gradient-to-r from-gray-700 to-gray-800 hover:from-gray-800 hover:to-gray-900 text-white font-medium transition-all duration-300 mt-4"
                                    >
                                        Manage Connection
                                    </Link>
                                )}
                            </div>
                        </div>

                        {/* Quick Tips */}
                        <div className="bg-gradient-to-br from-purple-900/20 to-pink-900/20 rounded-2xl p-6 border border-purple-500/30 backdrop-blur-xl">
                            <h4 className="text-lg font-semibold text-white mb-4">Quick Tips</h4>
                            <ul className="space-y-3">
                                <li className="flex items-start gap-3 text-sm">
                                    <div className="w-5 h-5 rounded-full bg-blue-500/30 flex items-center justify-center flex-shrink-0 mt-0.5">
                                        <span className="text-blue-400 text-xs">1</span>
                                    </div>
                                    <span className="text-gray-300">Connect Instagram to unlock all features</span>
                                </li>
                                <li className="flex items-start gap-3 text-sm">
                                    <div className="w-5 h-5 rounded-full bg-blue-500/30 flex items-center justify-center flex-shrink-0 mt-0.5">
                                        <span className="text-blue-400 text-xs">2</span>
                                    </div>
                                    <span className="text-gray-300">Check your media library for post management</span>
                                </li>
                                <li className="flex items-start gap-3 text-sm">
                                    <div className="w-5 h-5 rounded-full bg-blue-500/30 flex items-center justify-center flex-shrink-0 mt-0.5">
                                        <span className="text-blue-400 text-xs">3</span>
                                    </div>
                                    <span className="text-gray-300">Use insights to track content performance</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            {/* Animation Styles */}
            <style jsx>{`
                @keyframes float {
                    0%, 100% {
                        transform: translateY(0) translateX(0);
                    }
                    50% {
                        transform: translateY(-20px) translateX(10px);
                    }
                }
                @keyframes float-slow {
                    0%, 100% {
                        transform: translateY(0) translateX(0);
                    }
                    50% {
                        transform: translateY(-30px) translateX(-15px);
                    }
                }
                .animate-float {
                    animation: float 8s ease-in-out infinite;
                }
                .animate-float-slow {
                    animation: float-slow 10s ease-in-out infinite;
                }
            `}</style>
        </div>
    );
};

export default DashboardPage;