"use client";

import { RefreshCw, WalletIcon, CirclePlus, MoreHorizontal } from 'lucide-react';
import Link from 'next/link';
import { Typography } from '@/components/atoms/typogrpahy';
import { useWallet } from '../../hooks/useWallet';
import { formatBalanceCurrency } from '@/lib/transactionUtil';
import { usePathname } from 'next/navigation';
import { useEffect, useRef } from 'react';
import { useProfile } from '@/modules/profileModule/hook/useProfile';
import { User } from '@/types/auth';

interface WalletBalanceSectionProps {
  balance: number;
  currency: string;
  initialProfile: User | null;
}

export const WalletBalanceSection: React.FC<WalletBalanceSectionProps> = ({ 
  balance, 
  currency,
  initialProfile
}) => {
  const pathname = usePathname();
  const isWalletPage = pathname === '/wallet';
  const { currentBalance, currentCurrency, loading, handleRefresh, setCurrentBalance, setCurrentCurrency } = useWallet({ 
    initialBalance: balance,
    initialCurrency: currency,
  }); 
  const { profile, refreshProfile } = useProfile({initialProfile: initialProfile});
  const hasFetchedBalance = useRef(false);
  
  useEffect(() => {
    if (!isWalletPage && (!profile || !balance || balance === 0)) {
      refreshProfile();
    }
  }, [isWalletPage, profile, balance, refreshProfile]);

  useEffect(() => {
    if (!isWalletPage) {
      setCurrentBalance(profile?.wallet?.balance || 0);
      setCurrentCurrency(profile?.wallet?.currency || currency);
    }
  }, [isWalletPage, profile, currency, setCurrentBalance, setCurrentCurrency]);

  useEffect(() => {
    if (isWalletPage && !hasFetchedBalance.current) {
      hasFetchedBalance.current = true;
      handleRefresh();
    }
  }, [isWalletPage, handleRefresh]);

  return (
    <>
      <div className="
          group relative w-full h-56 md:h-64
          bg-gradient-to-br from-brand-600 to-brand-800 
          rounded-2xl shadow-lg overflow-hidden
          transition-all duration-300 ease-in-out
          transform hover:scale-102 hover:shadow-2xl hover:shadow-brand-500/40
        ">
          <div className="relative flex flex-col justify-between h-full p-6 md:p-8 text-white z-10">
            {/* Header */}
            <div className="flex items-center space-x-2">
              <WalletIcon className="w-7 h-7 text-white/80"/>
              <Typography variant="h5" className="text-white/90">My Wallet</Typography>
            </div>

          {/* Balance */}
          <div className="flex-grow flex flex-col justify-center">
            <Typography variant='b5' className="text-brand-100/80">Balance</Typography>
            <div className="flex items-center gap-2">
              <Typography variant='h2' className="font-bold tracking-tight">
                {formatBalanceCurrency(currentBalance, currentCurrency)}
              </Typography>
              {pathname === '/wallet' && (
                <button
                  type="button"
                  onClick={handleRefresh}
                  disabled={loading}
                  aria-label={loading ? 'Refreshing balance' : 'Refresh balance'}
                  className="
                    inline-flex items-center justify-center
                    w-7 h-7 rounded-full
                    transition-colors duration-300
                    hover:opacity-80
                    disabled:opacity-50
                  "
                >
                  <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
                </button>
              )}
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center space-x-4">
            <Link 
              href="/topup"
              className="
                flex items-center justify-center space-x-2 w-full
                bg-white/20 hover:bg-white/30 backdrop-blur-sm
                font-semibold text-sm text-center
                px-4 py-3 rounded-full transition-colors duration-300"
            >
              <CirclePlus className='w-4 h-4' />
              <span>Top Up</span>
            </Link>
            {pathname === '/profile' && (
              <Link
                href="/wallet"
                className="
                    flex items-center justify-center space-x-2 w-full
                    bg-white/20 hover:bg-white/30 backdrop-blur-sm
                    font-semibold text-sm text-center
                    px-4 py-3 rounded-full transition-colors duration-300"
              >
                <MoreHorizontal className="w-4 h-4" />
                <span>More</span>
              </Link>
            )}
          </div>
        </div>
        
          <div className="absolute top-0 left-0 w-full h-full bg-black/10 z-0"></div>
          <div className="absolute -top-1/4 -right-1/4 w-1/2 h-1/2 bg-brand-400/40 rounded-full filter blur-3xl opacity-50 group-hover:opacity-80 transition-opacity duration-500"></div>
        </div>
    </>
  );
}
