'use client';

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

export function PaymentSuccessForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const sessionId = searchParams.get('session_id');

  const [subscription, setSubscription] = useState<AgentSubscription | null>(null);
  const [loading, setLoading] = useState(true);

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

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

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

  const formatAmount = (amount: number) => {
    return `$${(amount / 100).toFixed(2)}`;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-[#e58625]" />
      </div>
    );
  }

  const transactionDetails = [
    { label: 'Transaction ID', value: sessionId ? sessionId.slice(0, 16) + '...' : 'N/A', bold: true },
    { label: 'Amount Paid', value: subscription?.plan ? formatAmount(subscription.plan.amount) : '$499.00', bold: true },
    { label: 'Date', value: formatDate(subscription?.createdAt || new Date().toISOString()), bold: true },
  ];

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

      {/* Payment Success Card */}
      <div className="border border-[#00293D] rounded-[10px] py-10 px-8">
        {/* Success Icon */}
        <div className="flex justify-center mb-5">
          <Image
            src="/assets/icons/payment-success-icon.svg"
            alt="Success"
            width={40}
            height={40}
          />
        </div>

        {/* Success Title */}
        <h2 className="font-fractul font-bold text-[20px] text-[#00293D] text-center mb-3">
          Payment Successful !
        </h2>

        {/* Success Description */}
        <p className="font-serif text-[14px] text-[#00293D] text-center mb-8 max-w-[329px] mx-auto leading-[22px]">
          Your annual membership is now active. You have full access to all premium features
        </p>

        {/* Transaction Details Section */}
        <div className="max-w-[430px] mx-auto">
          {/* Header Row */}
          <div className="flex items-center justify-between mb-5">
            <span className="font-serif text-[15px] text-[#00293D]">
              Transaction Details
            </span>
            <div className="flex items-center gap-2">
              <Image
                src="/assets/icons/verified-shield-green-icon.svg"
                alt="Verified"
                width={20}
                height={20}
              />
              <span className="font-serif text-[14px] text-[#00293D]">
                Verified User
              </span>
            </div>
          </div>

          {/* Detail Rows */}
          <div className="space-y-5 mb-6">
            {transactionDetails.map((detail) => (
              <div key={detail.label} className="flex items-center justify-between">
                <span className="font-serif text-[15px] text-[#00293D]/50">
                  {detail.label}
                </span>
                <span className={`font-serif text-[14px] text-[#00293D] ${detail.bold ? 'font-bold' : ''}`}>
                  {detail.value}
                </span>
              </div>
            ))}
          </div>

          {/* Divider */}
          <div className="border-b border-[#00293D]/20 mb-5" />

          {/* Next Renewal Date */}
          <div className="flex items-center justify-between mb-8">
            <span className="font-serif text-[15px] text-[#00293D]">
              Next Renewal Date
            </span>
            <span className="font-serif font-bold text-[14px] text-[#e58625]">
              {formatDate(subscription?.currentPeriodEnd)}
            </span>
          </div>

          {/* Action Buttons */}
          <div className="flex gap-4 mb-6">
            <button
              onClick={() => window.location.href = '/agent/dashboard'}
              className="flex-1 bg-[#e58625] border border-[#e58625] text-white font-fractul font-bold text-[14px] py-4 rounded-[15px] hover:bg-[#d47920] transition-colors flex items-center justify-center gap-2"
            >
              <Image
                src="/assets/icons/dashboard-white-icon.svg"
                alt=""
                width={20}
                height={20}
              />
              Go To Dashboard
            </button>
            <button
              onClick={() => router.push('/agent/settings/billings')}
              className="flex-1 bg-[#e58625] border border-[#e58625] text-white font-fractul font-bold text-[14px] py-4 rounded-[15px] hover:bg-[#d47920] transition-colors flex items-center justify-center gap-2"
            >
              <Image
                src="/assets/icons/download-white-icon.svg"
                alt=""
                width={20}
                height={20}
              />
              View Subscription
            </button>
          </div>

          {/* Trust Badges */}
          <div className="flex items-center justify-center gap-8">
            <div className="flex items-center gap-2">
              <Image
                src="/assets/icons/verified-shield-green-icon.svg"
                alt="Verified"
                width={20}
                height={20}
              />
              <span className="font-serif text-[14px] text-[#00293D]">
                Verified User
              </span>
            </div>
            <div className="flex items-center gap-2">
              <Image
                src="/assets/icons/lock-icon.svg"
                alt="Secure"
                width={20}
                height={20}
              />
              <span className="font-serif text-[14px] text-[#00293D]">
                Secure Checkout
              </span>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
