import React, { useEffect, useRef, useState, useContext } from "react";
import { useRouter } from "next/router";
import Seo from "../components/common/Seo";
import DefaulHeader2 from "../components/header/DefaulHeader2";
import MobileMenu from "../components/header/MobileMenu";
import { useCheckSubscriptionStatus } from "../utils/hooks/useCheckSubscriptionStatus";
import { AxiosResponse } from "axios";
import { AuthContext } from "../contexts/auth";
import { AuthContextType } from "..";
import Swal from "sweetalert2";
import Footer from "../components/footer/Footer";
import { usePurchaseSubscription } from "../utils/hooks/usePurchaseSubscription";

interface Feature {
  title: string;
  description: string;
  icon: string;
}

interface SubscriptionResponse {
  has_active_subscription: boolean;
  expiry_date: string | null;
}

const SubscriptionDetails: React.FC = () => {
  const router = useRouter();
  const { isAuthenticated } = useContext(AuthContext) as AuthContextType;
  const [isSubscribed, setIsSubscribed] = useState(false);

  const subscriptionDetails = {
    planName: "Jobrator Plus",
    price: "NGN 199 / month",
    image: "https://cdn-icons-png.flaticon.com/512/3135/3135715.png",
    features: [
      {
        title: "Unlimited Access",
        description:
          "Unlock unrestricted access to thousands of job listings across industries and regions. Gain the freedom to explore top companies, remote opportunities, and exclusive hiring drives without any limitations. Perfect for active job seekers who want complete visibility and flexibility.",
        icon: "https://cdn-icons-png.flaticon.com/512/3208/3208750.png",
      },
      {
        title: "Job Applications",
        description:
          "Apply seamlessly to up to 50 curated job postings each month. Our streamlined system allows you to track all your applications, receive updates in real-time, and manage your job search effectively — all in one place. Get priority access to trending roles and featured companies.",
        icon: "https://cdn-icons-png.flaticon.com/512/3135/3135720.png",
      },
      {
        title: "Resume Builder",
        description:
          "Create, manage, and customize up to five professionally designed resumes optimized for different job roles. Our smart resume builder helps you highlight your achievements, tailor your profile to specific industries, and stand out from the crowd with recruiter-friendly formats.",
        icon: "https://cdn-icons-png.flaticon.com/512/3135/3135730.png",
      },
      {
        title: "Profile Insights",
        description:
          "Gain exclusive insights into who viewed your profile, when they viewed it, and which parts caught their attention. Understand your reach, target employers strategically, and improve your visibility with real-time analytics designed to give you a competitive edge.",
        icon: "https://cdn-icons-png.flaticon.com/512/3135/3135740.png",
      },
      {
        title: "Smart Notifications",
        description:
          "Stay updated with personalized alerts for new job opportunities, skill-based recommendations, and company news. Receive notifications for application updates, interviews, and important career events — ensuring you never miss a valuable opportunity.",
        icon: "https://cdn-icons-png.flaticon.com/512/3135/3135750.png",
      },
      {
        title: "Career Insights Dashboard",
        description:
          "Access a data-driven dashboard that tracks your progress, highlights growth opportunities, and suggests relevant upskilling paths. Get AI-powered insights on market trends, salary benchmarks, and role-based recommendations to boost your professional development.",
        icon: "https://cdn-icons-png.flaticon.com/512/3135/3135760.png",
      },
    ] as Feature[],
  };

  const featureRefs = useRef<(HTMLDivElement | null)[]>([]);
  const [visibleFeatures, setVisibleFeatures] = useState<number[]>([]);

  const handleSubscription = async (packageId: number) => {
    const res = await Swal.fire({
      icon: "warning",
      title: "Are you sure?",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, Sure!",
      cancelButtonText: "Cancel",
    });

    if (!isAuthenticated && res.isConfirmed) {
      router.push("/login");
      return;
    }

    if (isAuthenticated && res.isConfirmed) {
      const response = await usePurchaseSubscription(packageId);
      console.log("response>>>", response);
      const { data } = response as any;

      // Redirect user to Paystack
      // It internally verify payment status and then persists to DB
      if (data.payment.authorization_url) {
        window.location.href = data.payment.authorization_url;
      }
    }
  };

  // Check subscription status
  useEffect(() => {
    if (isAuthenticated) checkSubscriptionStatus();
  }, [isAuthenticated]);

  const checkSubscriptionStatus = async () => {
    try {
      const response = await useCheckSubscriptionStatus();
      const { data } = response as AxiosResponse<SubscriptionResponse>;
      setIsSubscribed(data.has_active_subscription);
    } catch (err) {
      console.error("Error checking subscription:", err);
    }
  };

  // Scroll animation for features
  useEffect(() => {
    featureRefs.current = featureRefs.current.slice(
      0,
      subscriptionDetails.features.length
    );

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const index = entry.target.getAttribute("data-index");
            if (index !== null) {
              setVisibleFeatures((prev: number[]) => [
                ...Array.from(new Set([...prev, Number(index)])),
              ]);
            }
          }
        });
      },
      { threshold: 0.2 }
    );

    featureRefs.current.forEach((ref) => ref && observer.observe(ref));

    return () => observer.disconnect();
  }, [subscriptionDetails.features.length]);

  return (
    <>
      <Seo pageTitle="Subscription Details" />
      <span className="header-span"></span>
      <DefaulHeader2 />
      <MobileMenu />

      {/* Top Banner */}
      <div
        className="plan-header d-flex justify-content-between align-items-center px-5 py-5"
        style={{ background: "#055875", color: "#fff" }}
      >
        {/* Left: Plan info */}
        <div className="d-flex align-items-center">
          <div className="d-flex align-items-center p-4 rounded">
            <img
              src={subscriptionDetails.image}
              alt={subscriptionDetails.planName}
              className="rounded-circle border border-2 border-white"
              style={{ width: "200px", height: "200px", objectFit: "cover" }}
            />
            <div style={{ marginLeft: "25px" }}>
              <h2
                className="mb-1 fw-bold"
                style={{ color: "#fff", fontSize: "2.1rem" }}
              >
                {subscriptionDetails.planName}
              </h2>
              <p
                className="mb-0"
                style={{ color: "#fff", fontWeight: "600", fontSize: "1.4rem" }}
              >
                {subscriptionDetails.price}
              </p>
            </div>
          </div>
        </div>

        {/* Right: Dynamic Subscription Button */}
        <div className="align-items-center d-flex justify-content-center pt-4">
          {isAuthenticated ? (
            isSubscribed ? (
              <button className="theme-btn btn-style-three mb-4" disabled>
                Already Subscribed!
              </button>
            ) : (
              <button
                onClick={() => handleSubscription(1)}
                className="theme-btn btn-style-three mb-4"
              >
                Subscribe Now
              </button>
            )
          ) : (
            <button
              onClick={() => handleSubscription(1)}
              className="theme-btn btn-style-three mb-4"
            >
              Subscribe Now
            </button>
          )}
        </div>
      </div>

      {/* Features Section */}
      <div className="features-section py-0" style={{ background: "#ffffff" }}>
        {subscriptionDetails.features.map((feature, index) => (
          <div
            key={index}
            ref={(el) => (featureRefs.current[index] = el)}
            data-index={index}
            className={`feature-row d-flex align-items-center my-6 rounded-3 p-5 hover-effect ${
              visibleFeatures.includes(index) ? "visible" : ""
            }`}
            style={{
              flexDirection: index % 2 === 0 ? "row" : "row-reverse",
              background: "#ffffff", // inner card background also white
              transition: "all 0.5s ease",
              opacity: 0,
              transform: "translateY(20px)",
            }}
          >
            {/* Feature Image */}
            <div
              className="feature-image flex-shrink-0"
              style={{ margin: "0 40px" }}
            >
              <img
                src={feature.icon}
                alt={feature.title}
                width={300}
                height={300}
                style={{ borderRadius: "25px" }}
              />
            </div>

            {/* Feature Text */}
            <div className="feature-text" style={{ maxWidth: "850px" }}>
              <h2 className="mb-4" style={{ fontSize: "2rem" }}>
                {feature.title}
              </h2>
              <p
                className="mb-0 text-muted"
                style={{ fontSize: "1.1rem", lineHeight: "1.8rem" }}
              >
                {feature.description}
              </p>
            </div>
          </div>
        ))}
      </div>
      <style jsx>{`
        .hover-effect:hover {
          transform: translateY(-8px);
          box-shadow: 0 12px 25px rgba(0, 0, 0, 0.15);
        }

        .feature-row.visible {
          opacity: 1 !important;
          transform: translateY(0) !important;
        }

        @media (max-width: 768px) {
          .plan-header {
            flex-direction: column;
            text-align: center;
            gap: 15px;
          }
          .feature-row {
            flex-direction: column !important;
            text-align: center;
          }
          .feature-image {
            margin: 0 0 20px 0 !important;
          }
        }
      `}</style>
      <Footer />
    </>
  );
};

export default SubscriptionDetails;
