'use client';

import React, { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import axios from "axios";
import IconCircleCheck from "@/components/icon/icon-circle-check";

interface PaymentDetails {
  email: string;
  amount: string;
  plan: string;
  stripeSessionId: string;
  status: string;
  createdAt: string;
}

const PaymentSuccess: React.FC = () => {
  const [payment, setPayment] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const router = useRouter();
  const searchParams = useSearchParams();
  const sessionId = searchParams.get("session_id");

  useEffect(() => {
    if (!sessionId) {
      setError("No session_id provided");
      setLoading(false);
      return;
    }

    const fetchPaymentDetails = async () => {
      try {
        const res: any = await axios.get(
          `https://ebay.backend.data4autos.com/api/payment/details`,
          { params: { session_id: sessionId } }
        );
        setPayment(res.data.payment);
        localStorage.setItem('payment_session', res.data.payment?.stripeSessionId);
      } catch (err: any) {
        console.error(err);
        setError(err.response?.data?.error || "Failed to fetch payment details");
      } finally {
        setLoading(false);
      }
    };

    fetchPaymentDetails();
  }, [sessionId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[83vh] text-gray-500">
        Loading payment details...
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[83vh] text-red-500">
        {error}
      </div>
    );
  }

  return (
    <div className="flex flex-col items-center justify-center min-h-[83vh] bg-gradient-to-br from-green-50 via-white to-green-100 px-4">

      {/* ✅ Success Icon */}
      <div className="animate-bounce mb-3">
        <IconCircleCheck className="w-24 h-24 text-green-500 drop-shadow-md" />
      </div>

      {/* ✅ Title */}
      <h1 className="text-3xl font-bold text-gray-800 mb-2 text-center">
        Payment Successful 🎉
      </h1>

      {/* ✅ Subtitle */}
      <p className="text-gray-600 mb-6 text-center max-w-md">
        Thank you for your purchase! Your payment has been processed successfully.
      </p>

      {/* Card with Details */}
      <div className="bg-white shadow-lg rounded-2xl p-6 w-full max-w-md border border-gray-100 transition-transform duration-300 hover:scale-[1.02] space-y-3">

        <div className="flex justify-between items-start mb-3">
          <span className="text-gray-500">Transaction ID:</span>
          <span className="font-semibold text-gray-800 break-all max-w-[60%]">
            {payment?.stripeSessionId}
          </span>
        </div>

        <div className="flex justify-between items-start mb-3">
          <span className="text-gray-500">Email:</span>
          <span className="font-semibold text-gray-800 break-words max-w-[60%]">
            {payment?.email}
          </span>
        </div>

        <div className="flex justify-between items-start mb-3">
          <span className="text-gray-500">Plan:</span>
          <span className="font-semibold text-gray-800 break-words max-w-[60%]">
            {payment?.plan}
          </span>
        </div>

        <div className="flex justify-between items-start mb-3">
          <span className="text-gray-500">Amount:</span>
          <span className="font-semibold text-gray-800 break-words max-w-[60%]">
            ${payment?.amount}
          </span>
        </div>

        <div className="flex justify-between items-start mb-3">
          <span className="text-gray-500">Payment Status:</span>
          <span className="font-semibold text-green-600 break-words max-w-[60%]">
            {payment?.status}
          </span>
        </div>

        <div className="flex justify-between">
          <span className="text-gray-500">Subscription:</span>
          <span className="font-semibold text-gray-800">
            {payment?.startDate
              ? `${new Date(payment.startDate).toLocaleDateString()} → ${new Date(payment.endDate).toLocaleDateString()}`
              : "Pending activation"}
          </span>
        </div>
      </div>

      {/* ✅ Button */}
      <button
        onClick={() => router.push("/")}
        className="mt-8 bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-xl shadow-md font-medium transition-all duration-200 hover:shadow-lg"
      >
        Go to Dashboard
      </button>

      {/* ✅ Footer Text */}
      <p className="mt-6 text-sm text-gray-400 text-center">
        You can view your payment history anytime from your dashboard.
      </p>
    </div>
  );
};

export default PaymentSuccess;
