"use client";

import React, { useEffect, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import axios from "axios";
import { ApiServerBaseUrl } from "@/utils/baseurl.utils";
import { 
  Instagram, 
  BarChart3, 
  MessageSquare, 
  Shield, 
  CheckCircle, 
  Zap,
  Users,
  Clock
} from "lucide-react";

type Status =
  | "checking"
  | "not_connected"
  | "finalizing"
  | "connected"
  | "error";

const SocialMediaConnect = () => {
  const [status, setStatus] = useState<Status>("checking");
  const [error, setError] = useState<string | null>(null);

  const searchParams = useSearchParams();
  const router = useRouter();

  // ---------------------- CHECK STATUS + FINALIZE AUTH ----------------------
  useEffect(() => {
    async function checkStatus() {
      try {
        setError(null);
        setStatus("checking");

        const userId = localStorage.getItem("user_email");

        const res = await axios.get(
          `${ApiServerBaseUrl}/social/auth/status`,
          { params: { userId }, withCredentials: true }
        );

        if (res.data.connected) {
          setStatus("connected");
        } else {
          setStatus("not_connected");
        }
      } catch (err: any) {
        console.error(err);
        setError("Failed to load status");
        setStatus("error");
      }
    }

    async function finalizeAuth(authToken: string) {
      try {
        setStatus("finalizing");
        setError(null);

        const userId = localStorage.getItem("user_email");

        const res = await axios.post(
          `${ApiServerBaseUrl}/social/auth/save-oauth`,
          { auth: authToken, userId },
          { withCredentials: true }
        );

        if (!res.data.ok) throw new Error("Failed to finalize auth");

        const url = new URL(window.location.href);
        url.searchParams.delete("auth");
        router.replace(url.pathname);

        await checkStatus();
      } catch (err: any) {
        console.error(err);
        setError("Error finalizing connection");
        setStatus("error");
      }
    }

    async function init() {
      const auth = searchParams.get("auth");

      if (auth) {
        await finalizeAuth(auth);
      } else {
        await checkStatus();
      }
    }

    init();
  }, [searchParams, router]);

  // ---------------------- DISCONNECT FB ACCOUNT ----------------------
  const handleDisconnect = async () => {
    try {
      const userId = localStorage.getItem("user_email");

      const res = await axios.post(
        `${ApiServerBaseUrl}/social/auth/disconnect`,
        { userId },
        { withCredentials: true }
      );

      if (res.data.ok) {
        setStatus("not_connected");
      }
    } catch (err: any) {
      console.error(err);
      setError("Failed to remove connected account");
      setStatus("error");
    }
  };

  // ---------------------- CONNECT BUTTON ----------------------
  const handleConnect = () => {
    window.location.href = `${ApiServerBaseUrl}/social/auth/login`;
  };

  // ---------------------- PAYMENT SESSION VALIDATION ----------------------
  useEffect(() => {
    const storedUser = localStorage.getItem("userDetails");
    if (!storedUser) return;

    const user = JSON.parse(storedUser);
    const role = user?.role;

    if (role === "admin" || role === "partner") {
      return;
    }

    const session = localStorage.getItem("payment_session");
    if (role === "customer" && !session) {
      router.push("/pricing");
    }
  }, [router]);

  // User-friendly features list
  const features = [
    {
      icon: <Instagram className="w-6 h-6" />,
      title: "View Instagram Profile & Posts",
      description: "See your Instagram profile details and browse your published posts directly inside Social Buddy."
    },
    {
      icon: <BarChart3 className="w-6 h-6" />,
      title: "Track Performance Insights",
      description: "Monitor key metrics like reach, impressions, and engagement to understand how your content is performing."
    },
    {
      icon: <MessageSquare className="w-6 h-6" />,
      title: "Manage Comments Easily",
      description: "Reply to comments, hide inappropriate messages, or remove spam — all from one centralized place."
    }
  ];

  // Benefits list
  const benefits = [
    {
      icon: <Zap className="w-5 h-5" />,
      text: "One dashboard for posts, insights, and comments"
    },
    {
      icon: <Clock className="w-5 h-5" />,
      text: "Saves time managing Instagram engagement"
    },
    {
      icon: <Users className="w-5 h-5" />,
      text: "Helps you respond faster to your audience"
    },
    {
      icon: <Shield className="w-5 h-5" />,
      text: "Designed for businesses, creators, and agencies"
    }
  ];

  return (
    <div className="min-h-screen bg-gradient-to-b from-[#111111] to-[#0a0a0a] px-4 py-8 md:py-12">
      {/* Floating background bubbles */}
      <div className="absolute top-20 left-5 w-20 h-20 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-20 left-1/4 w-24 h-24 rounded-full bg-purple-500/20 blur-xl animate-float"></div>
      <div className="absolute bottom-40 right-20 w-28 h-28 rounded-full bg-cyan-500/15 blur-xl animate-float-slow"></div>

      {/* Main Container */}
      <div className="max-w-6xl mx-auto relative z-10">
        {/* Header Section */}
        <div className="text-center mb-12">
          <div className="flex justify-center mb-6">
            <div className="w-20 h-20 rounded-2xl bg-gradient-to-r from-blue-500 to-purple-600 flex items-center justify-center shadow-lg shadow-blue-500/30">
              <Instagram className="w-10 h-10 text-white" />
            </div>
          </div>
          <h1 className="text-4xl md:text-5xl font-bold text-white mb-4">
            Social Buddy
          </h1>
          <p className="text-gray-300 text-lg md:text-xl max-w-2xl mx-auto">
            Connect your Facebook and Instagram accounts to manage your posts, track performance, and handle comments — all from one simple dashboard.
          </p>
        </div>

        <div className="grid lg:grid-cols-3 gap-8">
          {/* Left Column - Connection Status */}
          <div className="lg:col-span-2 space-y-8">
            {/* Connection Card */}
            <div className="bg-gradient-to-br from-gray-900/90 to-black/90 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/10">
              <h2 className="text-2xl font-bold text-white mb-6">Connection Status</h2>
              
              <div className="space-y-6">
                {/* Status Display */}
                <div className="flex items-center gap-4 p-4 rounded-xl bg-white/5 border border-white/10">
                  {status === "checking" && (
                    <>
                      <div className="w-4 h-4 rounded-full bg-yellow-500 animate-pulse"></div>
                      <p className="text-gray-300">Checking connection status...</p>
                    </>
                  )}
                  {status === "finalizing" && (
                    <>
                      <div className="w-4 h-4 rounded-full bg-blue-500 animate-pulse"></div>
                      <p className="text-blue-400">Finalizing connection...</p>
                    </>
                  )}
                  {status === "connected" && (
                    <>
                      <CheckCircle className="w-6 h-6 text-green-500" />
                      <div>
                        <p className="text-green-400 font-semibold">Instagram & Facebook connected successfully</p>
                        <p className="text-gray-400 text-sm mt-1">
                          Your accounts are linked and ready to use.
                        </p>
                      </div>
                    </>
                  )}
                  {status === "not_connected" && (
                    <>
                      <div className="w-4 h-4 rounded-full bg-gray-500"></div>
                      <p className="text-gray-300">No Facebook account connected</p>
                    </>
                  )}
                  {status === "error" && (
                    <>
                      <div className="w-4 h-4 rounded-full bg-red-500"></div>
                      <p className="text-red-400">{error || "Connection error occurred"}</p>
                    </>
                  )}
                </div>

                {/* Action Buttons */}
                <div className="space-y-4">
                  {status === "not_connected" && (
                    <button
                      onClick={handleConnect}
                      className="w-full py-4 px-6 rounded-xl bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-semibold text-lg transition-all duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 hover:shadow-blue-500/30"
                    >
                      Connect Facebook Business Account
                    </button>
                  )}

                  {status === "connected" && (
                    <>
                      <button
                        onClick={handleDisconnect}
                        className="w-full py-4 px-6 rounded-xl bg-gradient-to-r from-gray-700 to-gray-800 hover:from-gray-800 hover:to-gray-900 text-white font-semibold text-lg transition-all duration-300 shadow-lg hover:shadow-xl"
                      >
                        Disconnect Account
                      </button>
                      <p className="text-gray-400 text-sm text-center">
                        You can disconnect and reconnect your account anytime. Disconnecting will revoke Social Buddy's access to your Instagram data.
                      </p>
                    </>
                  )}
                </div>

                {/* Features Grid */}
                <div className="mt-8 pt-8 border-t border-white/10">
                  <h3 className="text-xl font-bold text-white mb-6">What You Can Do with Social Buddy</h3>
                  <p className="text-gray-300 mb-6">
                    Social Buddy helps you stay on top of your Instagram presence without switching between apps.
                  </p>
                  
                  <div className="grid md:grid-cols-3 gap-6">
                    {features.map((feature, index) => (
                      <div 
                        key={index}
                        className="p-6 rounded-xl bg-gradient-to-br from-white/5 to-white/0 border border-white/10 hover:border-blue-500/30 transition-all duration-300 hover:bg-white/10"
                      >
                        <div className="w-12 h-12 rounded-lg bg-blue-500/20 flex items-center justify-center mb-4">
                          <div className="text-blue-400">
                            {feature.icon}
                          </div>
                        </div>
                        <h4 className="font-semibold text-white mb-2">{feature.title}</h4>
                        <p className="text-gray-300 text-sm">{feature.description}</p>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Privacy & Control Section */}
            <div className="bg-gradient-to-r from-blue-900/20 to-indigo-900/20 rounded-2xl p-8 border border-blue-500/30 backdrop-blur-xl">
              <div className="flex items-start gap-4">
                <Shield className="w-8 h-8 text-blue-400 flex-shrink-0 mt-1" />
                <div>
                  <h3 className="text-xl font-bold text-white mb-4">Privacy & Control</h3>
                  <div className="space-y-4">
                    <p className="text-gray-300">
                      Social Buddy only accesses data needed to provide these features. All actions are performed manually by you, and you can disconnect your account at any time.
                    </p>
                    <div className="flex items-center gap-2 text-gray-300">
                      <CheckCircle className="w-5 h-5 text-green-400" />
                      <span>No automation — you stay fully in control</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Right Column - Benefits & Info */}
          <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-8 shadow-2xl border border-white/10">
              <h3 className="text-2xl font-bold text-white mb-6">Why Use Social Buddy?</h3>
              
              <div className="space-y-6">
                {benefits.map((benefit, index) => (
                  <div key={index} className="flex items-start gap-4">
                    <div className="w-8 h-8 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">{benefit.text}</p>
                  </div>
                ))}
              </div>

              {/* Stats Preview */}
              <div className="mt-8 pt-8 border-t border-white/10">
                <div className="grid grid-cols-2 gap-4">
                  <div className="text-center p-4 rounded-lg bg-white/5 border border-white/10">
                    <div className="text-2xl font-bold text-white">1</div>
                    <div className="text-sm text-gray-400">Dashboard</div>
                  </div>
                  <div className="text-center p-4 rounded-lg bg-white/5 border border-white/10">
                    <div className="text-2xl font-bold text-white">3</div>
                    <div className="text-sm text-gray-400">Core Features</div>
                  </div>
                </div>
              </div>
            </div>

            {/* Quick Start Guide */}
            <div className="bg-gradient-to-br from-purple-900/20 to-pink-900/20 rounded-2xl p-8 border border-purple-500/30 backdrop-blur-xl">
              <h4 className="text-lg font-semibold text-white mb-4">Get Started in 3 Steps</h4>
              <ol className="space-y-4">
                <li className="flex items-center gap-3">
                  <div className="w-6 h-6 rounded-full bg-blue-500/30 text-blue-400 flex items-center justify-center text-sm font-bold">1</div>
                  <span className="text-gray-300">Click "Connect Instagram Account"</span>
                </li>
                <li className="flex items-center gap-3">
                  <div className="w-6 h-6 rounded-full bg-blue-500/30 text-blue-400 flex items-center justify-center text-sm font-bold">2</div>
                  <span className="text-gray-300">Log in with your Facebook account</span>
                </li>
                <li className="flex items-center gap-3">
                  <div className="w-6 h-6 rounded-full bg-blue-500/30 text-blue-400 flex items-center justify-center text-sm font-bold">3</div>
                  <span className="text-gray-300">Select your Instagram account and permissions</span>
                </li>
              </ol>
            </div>

            {/* Footer Note */}
            <div className="text-center p-6 rounded-xl bg-white/5 border border-white/10">
              <p className="text-gray-400 text-sm">
                © 2026 SocialBuddy. All rights reserved.
              </p>
              <p className="text-gray-500 text-xs mt-2">
                Powered by MetatronCube · Privacy Policy · Terms of Use
              </p>
            </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 6s ease-in-out infinite;
        }
        .animate-float-slow {
          animation: float-slow 8s ease-in-out infinite;
        }
      `}</style>
    </div>
  );
};

export default SocialMediaConnect;