'use client';

import { useState } from 'react';
import { Typography } from '@/components/atoms/typogrpahy';
import Button from '@/components/ui/button/Button';
import { Modal } from '@/components/ui/modal';
import { CreditCardDetails } from '@/services/creditCard/creditCardService';
import { CreditCardForm } from '@/modules/topupModule/components/CreditCardForm';
import { ClientOnly } from '@/components/common/ClientOnly';
import { CreditCard } from 'lucide-react';
import { deleteCreditCard } from '@/modules/walletModule/actions/creditCard.action';

interface CreditCardSectionProps {
  creditCard?: CreditCardDetails | null;
  creditCardToken?: string | null;
  onCreditCardUpdated?: () => void;
}

export function CreditCardSection({ 
  creditCard, 
  creditCardToken,
}: CreditCardSectionProps) {

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [isLinkCardModalOpen, setIsLinkCardModalOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [linkCardData, setLinkCardData] = useState<any>(null);

  const handleDeleteCard = async () => {
    if (!creditCardToken) return;
    
    setIsDeleting(true);
    try {
      const result = await deleteCreditCard(creditCardToken);
      if (result.success) {
        setIsDeleteModalOpen(false);
        if (typeof window !== 'undefined') {
          window.location.reload();
        }
      } else {
        alert(result.message || 'Failed to delete credit card');
      }
    } catch (error) {
      console.error('Delete card error:', error);
      alert('Failed to delete credit card');
    } finally {
      setIsDeleting(false);
    }
  };

  const handleLinkCard = async () => {
    try {
      // Use the new API endpoint to create a session
      const response = await fetch('/api/creditcard/sessions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      
      const result = await response.json();
      
      
      if (result.ok && result.data?.payment_session_id) {
        // Use the session ID to show the card form
        setLinkCardData(result.data);
        setIsLinkCardModalOpen(true);
      } else {
        alert(result.message || 'Failed to create credit card session');
      }
    } catch (error) {
      console.error('Link card error:', error);
      alert('Failed to link credit card');
    }
  };

  const getCardIcon = (network: string) => {
    switch (network?.toUpperCase()) {
      case 'VISA':
        return (
          <div className="w-12 h-8 bg-blue-600 rounded flex items-center justify-center text-white text-xs font-bold">
            VISA
          </div>
        );
      case 'MASTERCARD':
        return (
          <div className="w-12 h-8 bg-red-600 rounded flex items-center justify-center text-white text-xs font-bold">
            MC
          </div>
        );
      case 'AMEX':
        return (
          <div className="w-12 h-8 bg-green-600 rounded flex items-center justify-center text-white text-xs font-bold">
            AMEX
          </div>
        );
      default:
        return (
          <div className="w-12 h-8 bg-gray-600 rounded flex items-center justify-center text-white text-xs font-bold">
            CARD
          </div>
        );
    }
  };

  if (!creditCard) {
    // No credit card linked
    return (
      <ClientOnly>
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
          <div className="flex items-center justify-between mb-4">
            <Typography variant="h6" className="font-semibold text-gray-900 dark:text-white">
              Credit Card
            </Typography>
          </div>

          <div className="flex flex-col items-center text-center py-8">
            <CreditCard className='size-10 text-gray-400 mb-4'/>
            
            <Typography variant="h6" className="text-gray-900 dark:text-white mb-2">
              No Credit Card Connected
            </Typography>
            
            <Typography variant="b2" className="text-gray-500 dark:text-gray-400 mb-6">
              Link your credit card for faster payments and easy top-ups
            </Typography>

            <Button
              variant="primary"
              size="sm"
              onClick={handleLinkCard}
              className="bg-brand-500 hover:bg-brand-600 text-white px-6"
            >
              Link Credit Card
            </Button>
          </div>

          <Modal 
            isOpen={isLinkCardModalOpen} 
            onClose={() => setIsLinkCardModalOpen(false)}
            className="max-w-2xl mx-auto"
          >
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <Typography variant="h5" className="font-semibold text-gray-900 dark:text-white">
                  Link Credit Card
                </Typography>
                <button
                  onClick={() => setIsLinkCardModalOpen(false)}
                  className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
              
              {linkCardData?.payment_session_id && (
                <CreditCardForm
                  paymentSessionId={linkCardData.payment_session_id}
                  amount={0}
                  currency="USD"
                  onBack={() => setIsLinkCardModalOpen(false)}
                  isLinkingMode={true}
                  onLinkSuccess={() => {
                    setIsLinkCardModalOpen(false);
                    // Refresh page to update data
                    if (typeof window !== 'undefined') {
                      window.location.reload();
                    }
                  }}
                />
              )}
            </div>
          </Modal>
        </div>
      </ClientOnly>
    );
  }

  const cardDetails = creditCard;

  return (
    <ClientOnly>
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center justify-between mb-6">
          <Typography variant="h6" className="font-semibold text-gray-900 dark:text-white">
            Credit Card
          </Typography>
          
          <Button
            variant="outline"
            size="sm"
            onClick={() => setIsDeleteModalOpen(true)}
            className="text-red-600 border-red-200 hover:bg-red-50 dark:text-red-400 dark:border-red-800 dark:hover:bg-red-900/20"
          >
            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
            Remove Card
          </Button>
        </div>

        {/* Credit Card Display */}
        <div className="bg-gradient-to-r from-gray-800 to-gray-900 dark:from-gray-700 dark:to-gray-800 rounded-xl p-4 md:p-6 text-white mb-6">
          <div className="flex justify-between items-start mb-8">
            <div>
              <Typography variant="b3" className="text-gray-300 mb-1">
                Card Number
              </Typography>
              <Typography variant="h6" className="font-mono tracking-wider">
                {cardDetails.channel_properties.card_details.masked_card_number}
              </Typography>
            </div>
            
            {getCardIcon(cardDetails.channel_properties.card_details.network)}
          </div>

          <div className="grid grid-cols-2 gap-6 mb-6">
            <div>
              <Typography variant="b3" className="text-gray-300 mb-1">
                Expires
              </Typography>
              <Typography variant="s2" className="font-mono">
                {cardDetails.channel_properties.card_details.expiry_month}/{cardDetails.channel_properties.card_details.expiry_year}
              </Typography>
            </div>
            
            <div>
              <Typography variant="b3" className="text-gray-300 mb-1">
                Network
              </Typography>
              <Typography variant="s2" className="uppercase">
                {cardDetails.channel_properties.card_details.network}
              </Typography>
            </div>
          </div>

          <div>
            <Typography variant="b3" className="text-gray-300 mb-1">
              Cardholder
            </Typography>
            <Typography variant="s2" className="tracking-wide">
              {cardDetails.channel_properties.card_details.cardholder_first_name} {cardDetails.channel_properties.card_details.cardholder_last_name}
            </Typography>
          </div>
        </div>

        {/* Card Details */}
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-3">


               <div>
                <Typography variant="b3" className="text-gray-500 dark:text-gray-400 mb-1">
                  Email
                </Typography>
                <Typography variant="s2" className="text-gray-900 dark:text-white">
                  {cardDetails.channel_properties.card_details.cardholder_email}
                </Typography>
              </div>
              
              <div>
                <Typography variant="b3" className="text-gray-500 dark:text-gray-400 mb-1">
                  Phone
                </Typography>
                <Typography variant="s2" className="text-gray-900 dark:text-white">
                  {cardDetails.channel_properties.card_details.cardholder_phone_number}
                </Typography>
              </div>
            </div>

            <div className="space-y-3">
              <div>
                <Typography variant="b3" className="text-gray-500 dark:text-gray-400 mb-1">
                  Issuer
                </Typography>
                <Typography variant="s2" className="text-gray-900 dark:text-white">
                  {cardDetails.channel_properties.card_details.issuer}
                </Typography>
              </div>
            </div>
          </div>
        </div>

        {/* Delete Confirmation Modal */}
        <Modal 
          isOpen={isDeleteModalOpen} 
          onClose={() => setIsDeleteModalOpen(false)}
          className="max-w-md mx-auto"
        >
          <div className="p-6">
            <div className="flex items-center justify-center w-12 h-12 mx-auto mb-4 bg-red-100 rounded-full dark:bg-red-900/20">
              <svg className="w-6 h-6 text-red-600 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>

            <div className="text-center">
              <Typography variant="h6" className="text-gray-900 dark:text-white mb-2">
                Remove Credit Card
              </Typography>
              
              <Typography variant="b2" className="text-gray-500 dark:text-gray-400 mb-6">
                Are you sure you want to remove this credit card? This action cannot be undone.
              </Typography>

              <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-3 mb-6">
                <Typography variant="s2" className="font-mono text-gray-900 dark:text-white">
                  {cardDetails.channel_properties.card_details.masked_card_number}
                </Typography>
              </div>

              <div className="flex gap-3">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setIsDeleteModalOpen(false)}
                  className="flex-1"
                  disabled={isDeleting}
                >
                  Cancel
                </Button>
                
                <Button
                  variant="primary"
                  size="sm"
                  onClick={handleDeleteCard}
                  className="flex-1 bg-red-600 hover:bg-red-700 text-white"
                  disabled={isDeleting}
                >
                  {isDeleting ? 'Removing...' : 'Remove Card'}
                </Button>
              </div>
            </div>
          </div>
        </Modal>
      </div>
    </ClientOnly>
  );
}
