"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,
    Lock
} from "lucide-react";

const DashboardPage = () => {
    const [connectionStatus, setConnectionStatus] = useState<"connected" | "not_connected" | "loading" | "error">("loading");
    const [instagramUsername, setInstagramUsername] = useState<string | null>(null);

    // 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);
                    }
                } else {
                    setConnectionStatus("not_connected");
                }
            } catch (err) {
                console.error(err);
                setConnectionStatus("error");
            }
        }

        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"
        },
        {
            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"
        },
        {
            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"
        },
        {
            name: "Comment Management",
            icon: <MessageSquare size={32} className="text-blue-500" />,
            description: "Reply, hide, or delete comments across your Instagram posts.",
            link: "/comments",
            title: "Manage Instagram comments from one dashboard",
            status: connectionStatus === "connected" ? "active" : "requires-connection"
        },
        {
            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"
        },
        {
            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"
        },
    ];

    const benefits = [
        {
            icon: <Clock className="w-5 h-5" />,
            text: "Save time managing Instagram engagement"
        },
        {
            icon: <Users className="w-5 h-5" />,
            text: "Easily respond to your audience"
        },
        {
            icon: <BarChart3 className="w-5 h-5" />,
            text: "Track content performance with insights"
        },
        {
            icon: <Shield className="w-5 h-5" />,
            text: "Complete control over your content"
        }
    ];

    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 border-2 border-[#111111] flex items-center justify-center ${
                                    connectionStatus === "connected" ? "bg-green-500" : "bg-gray-500"
                                }`}>
                                    <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 from one place.
                                </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 ${
                                    connectionStatus === "connected" 
                                        ? "bg-green-500" 
                                        : connectionStatus === "not_connected"
                                        ? "bg-orange-500"
                                        : "bg-gray-500 animate-pulse"
                                }`}></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>

                    {/* Connection Status Overview */}
                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-10">
                        <div className="bg-gradient-to-br from-gray-900/50 to-black/50 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">Instagram Status</span>
                                {connectionStatus === "connected" ? (
                                    <CheckCircle className="w-5 h-5 text-green-400" />
                                ) : (
                                    <Lock className="w-5 h-5 text-gray-400" />
                                )}
                            </div>
                            <div className="text-2xl font-bold text-white">
                                {connectionStatus === "connected" ? "Connected" : "Not Connected"}
                            </div>
                        </div>
                        
                        <div className="bg-gradient-to-br from-gray-900/50 to-black/50 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">Available Features</span>
                                <Sparkles className="w-5 h-5 text-yellow-400" />
                            </div>
                            <div className="text-2xl font-bold text-white">
                                {connectionStatus === "connected" ? "All" : "Basic"}
                            </div>
                        </div>
                        
                        <div className="bg-gradient-to-br from-gray-900/50 to-black/50 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">Media Access</span>
                                <ImageIcon className="w-5 h-5 text-pink-400" />
                            </div>
                            <div className="text-2xl font-bold text-white">
                                {connectionStatus === "connected" ? "Enabled" : "Connect to enable"}
                            </div>
                        </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">
                                Connect your Instagram account to unlock all management tools.
                            </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" && connectionStatus !== "connected" 
                                                ? "opacity-70 cursor-not-allowed" 
                                                : ""
                                            }
                                        `}
                                        onClick={(e) => {
                                            if (card.status === "requires-connection" && connectionStatus !== "connected") {
                                                e.preventDefault();
                                            }
                                        }}
                                    >
                                        {/* Lock icon for features requiring connection */}
                                        {card.status === "requires-connection" && connectionStatus !== "connected" && (
                                            <div className="absolute top-4 right-4 w-8 h-8 rounded-full bg-gray-800/80 flex items-center justify-center border border-gray-700">
                                                <Lock className="w-4 h-4 text-gray-400" />
                                            </div>
                                        )}

                                        {/* Icon */}
                                        <div className={`w-12 h-12 rounded-xl flex items-center justify-center mb-4 ${
                                            card.status === "requires-connection" && connectionStatus !== "connected"
                                                ? "bg-gray-800/50"
                                                : "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>

                                        {/* Status indicator */}
                                        <div className="mt-4 flex justify-between items-center">
                                            {card.status === "requires-connection" && connectionStatus !== "connected" ? (
                                                <span className="text-sm text-orange-400 flex items-center gap-2">
                                                    <AlertCircle className="w-4 h-4" />
                                                    Connect Instagram to access
                                                </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 !== "connected"
                                                    ? "bg-gray-800 text-gray-500"
                                                    : "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">
                                <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-6">
                                            Connect your Instagram account to access media management, insights, 
                                            and comment moderation tools. All features are user-controlled and 
                                            require manual action.
                                        </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 Account
                                        </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" />
                                What You Can Do
                            </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 Overview</h3>
                            <div className="space-y-6">
                                <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 Account</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 Management</span>
                                        <span className={`${connectionStatus === "connected" ? "text-green-400" : "text-gray-500"}`}>
                                            {connectionStatus === "connected" ? "Available" : "Requires connection"}
                                        </span>
                                    </div>
                                    <div className="flex items-center justify-between text-sm">
                                        <span className="text-gray-400">Performance Insights</span>
                                        <span className={`${connectionStatus === "connected" ? "text-green-400" : "text-gray-500"}`}>
                                            {connectionStatus === "connected" ? "Available" : "Requires connection"}
                                        </span>
                                    </div>
                                    <div className="flex items-center justify-between text-sm">
                                        <span className="text-gray-400">Comment Moderation</span>
                                        <span className={`${connectionStatus === "connected" ? "text-green-400" : "text-gray-500"}`}>
                                            {connectionStatus === "connected" ? "Available" : "Requires connection"}
                                        </span>
                                    </div>
                                </div>
                                
                                <div className="pt-4 border-t border-white/10">
                                    {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"
                                        >
                                            Connect Instagram Account
                                        </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"
                                        >
                                            Manage Connection Settings
                                        </Link>
                                    ) : null}
                                </div>
                            </div>
                        </div>

                        {/* Important Notes - For Meta Approval */}
                        <div className="bg-gradient-to-br from-blue-900/20 to-indigo-900/20 rounded-2xl p-6 border border-blue-500/30 backdrop-blur-xl">
                            <h4 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                                <Shield className="w-5 h-5 text-blue-400" />
                                Important Notes
                            </h4>
                            <ul className="space-y-3 text-sm">
                                <li className="flex items-start gap-2 text-gray-300">
                                    <div className="w-5 h-5 rounded-full bg-green-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                                        <CheckCircle className="w-3 h-3 text-green-400" />
                                    </div>
                                    <span>All actions are user-initiated and user-controlled</span>
                                </li>
                                <li className="flex items-start gap-2 text-gray-300">
                                    <div className="w-5 h-5 rounded-full bg-green-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                                        <CheckCircle className="w-3 h-3 text-green-400" />
                                    </div>
                                    <span>No automated commenting or AI-generated responses</span>
                                </li>
                                <li className="flex items-start gap-2 text-gray-300">
                                    <div className="w-5 h-5 rounded-full bg-green-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                                        <CheckCircle className="w-3 h-3 text-green-400" />
                                    </div>
                                    <span>Manual moderation tools only</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;