'use client';

import Image from 'next/image';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { stripeService, AgentSubscription } from '@/services/stripe.service';

interface PlanFeature {
  icon: string;
  label: string;
}

const PLAN_FEATURES: PlanFeature[] = [
  { icon: '/assets/icons/gem-icon.svg', label: 'Agent -Co-Marketing' },
  { icon: '/assets/icons/tick-circle-icon.svg', label: 'Priority 24/7 Support' },
  { icon: '/assets/icons/tick-circle-icon.svg', label: 'Whitelabel Client Portals' },
  { icon: '/assets/icons/tick-circle-icon.svg', label: 'Advanced CRM Tools & Analytics' },
];

export function SubscriptionForm() {
  const [subscription, setSubscription] = useState<AgentSubscription | null>(null);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);

  useEffect(() => {
    loadSubscription();
  }, []);

  const loadSubscription = async () => {
    try {
      const subData = await stripeService.getSubscription();
      setSubscription(subData);
    } catch (error) {
      console.error('Failed to load subscription data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleGetPremium = async () => {
    setActionLoading(true);
    try {
      // Fetch plan ID on-demand when user clicks the button
      const plans = await stripeService.getPlans();
      if (!plans.length) {
        alert('No subscription plans available. Please try again later.');
        return;
      }
      const { url } = await stripeService.createCheckoutSession(plans[0].id);
      window.location.href = url;
    } catch (error: any) {
      console.error('Failed to create checkout session:', error);
      alert(error.response?.data?.message || 'Failed to start checkout. Please try again.');
    } finally {
      setActionLoading(false);
    }
  };

  const handleManageSubscription = async () => {
    setActionLoading(true);
    try {
      const { url } = await stripeService.createPortalSession();
      window.location.href = url;
    } catch (error) {
      console.error('Failed to open billing portal:', error);
    } finally {
      setActionLoading(false);
    }
  };

  const handleCancelSubscription = async () => {
    if (!confirm('Are you sure you want to cancel your subscription? You will retain access until the end of your billing period.')) {
      return;
    }
    setActionLoading(true);
    try {
      await stripeService.cancelSubscription();
      await loadSubscription();
    } catch (error) {
      console.error('Failed to cancel subscription:', error);
    } finally {
      setActionLoading(false);
    }
  };

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '';
    return new Date(dateStr).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  const isActive = subscription?.status === 'ACTIVE';

  return (
    <>
      {/* Page Title */}
      <div className="mb-6">
        <h1 className="font-fractul font-bold text-[20px] text-[#00293D] mb-2">
          Subscription & Payments
        </h1>
        <p className="font-serif text-[14px] text-[#00293D]/70">
          Manage Your billing cycles , upgrade your plan , or boost individual listings
        </p>
      </div>

      {/* Active Subscription Status */}
      {isActive && (
        <div className="mb-8 border border-green-300 bg-green-50 rounded-[10px] p-6">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-3 h-3 bg-green-500 rounded-full" />
            <h3 className="font-fractul font-bold text-[18px] text-[#00293D]">
              Active Subscription
            </h3>
          </div>
          {subscription.currentPeriodEnd && (
            <p className="font-serif text-[14px] text-[#00293D] mb-1">
              {subscription.cancelAtPeriodEnd
                ? `Cancels on: ${formatDate(subscription.currentPeriodEnd)}`
                : `Renews on: ${formatDate(subscription.currentPeriodEnd)}`}
            </p>
          )}
          <div className="flex gap-3 mt-4">
            <button
              onClick={handleManageSubscription}
              disabled={actionLoading}
              className="bg-[#e58625] border border-[#e58625] text-white font-fractul font-bold text-[14px] px-6 py-3 rounded-[15px] hover:bg-[#d47920] transition-colors disabled:opacity-50"
            >
              {actionLoading ? 'Loading...' : 'Manage Subscription'}
            </button>
            {!subscription.cancelAtPeriodEnd && (
              <button
                onClick={handleCancelSubscription}
                disabled={actionLoading}
                className="border border-red-400 text-red-500 font-fractul font-bold text-[14px] px-6 py-3 rounded-[15px] hover:bg-red-50 transition-colors disabled:opacity-50"
              >
                Cancel Subscription
              </button>
            )}
          </div>
        </div>
      )}

      {/* Annual Membership Plans */}
      <div className="mb-8">
        <h2 className="font-fractul font-bold text-[20px] text-[#00293D] mb-4">
          Annual Membership Plans
        </h2>

        {/* Plan Card */}
        <div className="border border-[#00293D] rounded-[10px] p-8 relative overflow-hidden">
          {/* Best Value Ribbon */}
          <div className="absolute top-0 right-0 w-[100px] h-[100px] overflow-hidden">
            <div className="absolute top-[18px] right-[-28px] bg-[#e58625] text-white text-[12px] font-fractul py-1 px-8 rotate-45 transform origin-center shadow-sm">
              Best Value
            </div>
          </div>

          <div className="flex flex-col lg:flex-row gap-8">
            {/* Left Side - Plan Details */}
            <div className="flex-1">
              {/* Annual Subscription Badge */}
              <div className="inline-block bg-[#e58625] rounded-[15px] px-4 py-2 mb-6">
                <span className="font-serif text-[14px] text-white">
                  Annual Subscription
                </span>
              </div>

              {/* Plan Name */}
              <h3 className="font-fractul font-bold text-[20px] text-[#00293D] mb-3">
                Professional Annual Plan
              </h3>

              {/* Plan Description */}
              <p className="font-serif text-[14px] text-[#00293D] mb-6 max-w-[230px] leading-[22px]">
                Complete solutions for real estate agents and lenders to grow their business.
              </p>

              {/* Price */}
              <div className="mb-6">
                <span className="font-fractul font-bold text-[35px] text-black">$499</span>
                <span className="font-fractul font-bold text-[20px] text-black"> / </span>
                <span className="font-fractul font-bold text-[20px] text-black/50">Year</span>
              </div>

              {/* CTA Button */}
              {loading ? (
                <div className="h-[52px] w-[180px] rounded-[15px] shimmer-loading" />
              ) : isActive ? (
                <span className="inline-block bg-green-100 text-green-700 font-fractul font-bold text-[14px] px-6 py-3 rounded-[15px]">
                  Current Plan
                </span>
              ) : (
                <button
                  onClick={handleGetPremium}
                  disabled={actionLoading}
                  className="bg-[#e58625] border border-[#e58625] text-white font-fractul font-bold text-[14px] px-10 py-4 rounded-[15px] hover:bg-[#d47920] transition-colors disabled:opacity-50"
                >
                  {actionLoading ? 'Processing...' : 'Get Premium Access'}
                </button>
              )}
            </div>

            {/* Right Side - Features + Illustration */}
            <div className="flex-1 flex flex-col lg:flex-row gap-6">
              {/* Features */}
              <div className="flex-1">
                <h4 className="font-fractul font-bold text-[20px] text-[#00293D] mb-6">
                  Include Features
                </h4>

                <div className="space-y-[18px]">
                  {PLAN_FEATURES.map((feature) => (
                    <div key={feature.label} className="flex items-center gap-3">
                      <Image
                        src={feature.icon}
                        alt=""
                        width={21}
                        height={21}
                        className="flex-shrink-0"
                      />
                      <span className="font-serif text-[14px] text-black">
                        {feature.label}
                      </span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Illustration */}
              <div className="hidden lg:flex items-start justify-end">
                <div className="w-[166px] h-[166px] rounded-[200px] overflow-hidden">
                  <img
                    src="/assets/images/subscription-plan-illustration.png"
                    alt="Professional plan"
                    className="w-full h-full object-cover"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Need Help Section */}
      <div className="border border-[#00293D]/70 rounded-[15px] p-8 flex flex-col lg:flex-row items-center gap-8">
        {/* Left Side - Help Content */}
        <div className="flex-1 text-center lg:text-left">
          {/* Question Icon */}
          <div className="flex justify-center lg:justify-start mb-3">
            <Image
              src="/assets/icons/question-circle-icon.svg"
              alt="Help"
              width={35}
              height={35}
            />
          </div>

          {/* Title */}
          <h3 className="font-fractul font-bold text-[20px] text-[#00293D] mb-3">
            Need Help ?
          </h3>

          {/* Description */}
          <p className="font-serif text-[14px] text-[#00293D] mb-4 max-w-[257px] mx-auto lg:mx-0 leading-[22px]">
            Our billing experts are here to help you with any questions about your plan.
          </p>

          {/* Support Email */}
          <Link
            href="mailto:support@example.com"
            className="font-serif font-bold text-[14px] text-[#e58625] underline hover:text-[#d47920] transition-colors"
          >
            support@example.com
          </Link>
        </div>

        {/* Right Side - Illustration */}
        <div className="hidden lg:block">
          <div className="w-[261px] h-[261px] rounded-[57px] overflow-hidden">
            <img
              src="/assets/images/need-help-illustration.png"
              alt="Need help illustration"
              className="w-full h-full object-cover"
            />
          </div>
        </div>
      </div>
    </>
  );
}
