/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { toast } from 'sonner';
import Cookies from 'js-cookie';

interface CheckoutButtonProps {
  priceId: string;
  className?: string;
  children: React.ReactNode;
  style?: React.CSSProperties;
}

export default function CheckoutButton({ priceId, className, children, style }: CheckoutButtonProps) {
  const [loading, setLoading] = useState(false);
  const [isSubscribed, setIsSubscribed] = useState(false);
  const [isChecking, setIsChecking] = useState(true);
  const timeoutRef = useRef<any>(null);

  useEffect(() => {
    const timer = setTimeout(() => {
      if (Cookies.get('isPayment') === 'true') {
        setIsSubscribed(true);
      }
      setIsChecking(false);
    }, 0);
    return () => clearTimeout(timer);
  }, []);

  useEffect(() => {
    const handlePageShow = (e: PageTransitionEvent) => {
      if (e.persisted) {
        setLoading(false);
      }
    };
    window.addEventListener('pageshow', handlePageShow);
    return () => {
      window.removeEventListener('pageshow', handlePageShow);
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  const handleCheckout = async (e: React.MouseEvent) => {
    if (isSubscribed || isChecking) {
      e.preventDefault();
      return;
    }
    
    e.preventDefault();
    setLoading(true);

    try {
      const { data } = await axios.post('/api/stripe/checkout', { priceId });
      
      if (data.url) {
        window.location.href = data.url;
        // Reset loading state after a brief timeout so that it doesn't get stuck
        // if navigation is slow or the user comes back.
        timeoutRef.current = setTimeout(() => {
          setLoading(false);
        }, 2000);
      } else {
        throw new Error('No checkout URL received');
      }
    } catch (error: any) {
      console.error('Checkout error:', error);
      toast.error(error.response?.data?.error || 'Failed to initiate checkout. Please try again.');
      setLoading(false);
    }
  };

  const cursorClass = isSubscribed 
    ? 'opacity-60' 
    : (loading || isChecking)
      ? 'opacity-70 cursor-not-allowed' 
      : '';
  const tooltipText = isSubscribed ? 'Already Subscribed' : undefined;

  // Enforce cursor using inline styles to prevent CSS class specificity issues overriding it
  const buttonStyle: React.CSSProperties = {
    ...style,
    ...((isSubscribed || isChecking) ? { cursor: 'not-allowed' } : {})
  };

  return (
    <button
      onClick={handleCheckout}
      disabled={loading || isChecking}
      aria-disabled={isSubscribed || isChecking}
      title={tooltipText}
      className={`${className} ${cursorClass} flex items-center justify-center gap-2`}
      style={buttonStyle}
    >
      {loading ? (
        <svg className="animate-spin h-5 w-5 text-current" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
      ) : null}
      {loading ? 'Redirecting...' : children}
    </button>
  );
}
