'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import DashboardLayout from '@/components/DashboardLayout'
import { 
  MdArrowUpward, 
  MdArrowDownward, 
  MdSwapHoriz, 
  MdAccountBalanceWallet, 
  MdTrendingUp, 
  MdPeople, 
  MdStar, 
  MdTimer 
} from 'react-icons/md'
import { useMockWallet } from '@/context/MockWalletContext'
import { useReadContract } from 'wagmi'
import { formatEther } from 'viem'

const erc20BalanceOfAbi = [
  {
    name: 'balanceOf',
    type: 'function',
    stateMutability: 'view',
    inputs: [{ name: 'owner', type: 'address' }],
    outputs: [{ name: '', type: 'uint256' }]
  }
] as const

export default function Dashboard() {
  const { isConnected, address, isDemo } = useMockWallet()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [data, setData] = useState<any>(null)

  const { data: mtcRawBalance } = useReadContract({
    address: '0xA7E60EAFc976C46ee168939a0b4f85d659f8C5d7',
    abi: erc20BalanceOfAbi,
    functionName: 'balanceOf',
    args: address ? [address as `0x${string}`] : undefined,
    query: {
      enabled: !!address,
      refetchInterval: 5000
    }
  })

  const mtcBalance = mtcRawBalance ? Number(formatEther(mtcRawBalance)) : 0
  const [demoMtcBalance, setDemoMtcBalance] = useState(100.00)

  const displayMtcBalance = isDemo ? demoMtcBalance : mtcBalance

  useEffect(() => {
    const session = localStorage.getItem('memberSession')
    if (!session) {
      window.location.href = '/'
      return
    }

    let memberId = ''
    try {
      const parsed = JSON.parse(session)
      memberId = parsed.memberId
      
      // Load user-specific MTC balance in demo mode
      if (isDemo && typeof window !== 'undefined') {
        const key = `demoMtcBalance_${memberId}`
        const stored = localStorage.getItem(key)
        if (!stored) {
          localStorage.setItem(key, '100.00')
          setDemoMtcBalance(100.00)
        } else {
          setDemoMtcBalance(Number(stored))
        }
      }
    } catch (e) {
      console.error(e)
      setError('Failed to parse user session.')
      setLoading(false)
      return
    }

    const fetchDashboardData = async () => {
      try {
        const res = await fetch(`/api/dashboard?memberId=${memberId}`)
        const json = await res.json()
        if (json.success) {
          setData(json)
        } else {
          setError(json.error || 'Failed to load dashboard data')
        }
      } catch (err) {
        console.error(err)
        setError('Error fetching dashboard values')
      } finally {
        setLoading(false)
      }
    }

    fetchDashboardData()
  }, [])

  if (loading) {
    return (
      <DashboardLayout>
        <div className="flex flex-col items-center justify-center h-[60vh] text-slate-400">
          <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-violet-500 mb-4"></div>
          <p className="text-sm">Loading your decentralized dashboard...</p>
        </div>
      </DashboardLayout>
    )
  }

  if (error || !data) {
    return (
      <DashboardLayout>
        <div className="p-6 rounded-2xl bg-rose-500/10 border border-rose-500/20 text-rose-300 text-sm max-w-xl mx-auto text-center mt-12">
          <p className="font-bold mb-2">Error Loading Dashboard</p>
          <p className="text-xs mb-4">{error || 'Unable to fetch data.'}</p>
          <button 
            onClick={() => window.location.reload()}
            className="px-4 py-2 bg-rose-600 hover:bg-rose-500 text-white text-xs rounded-lg transition-colors font-medium"
          >
            Retry
          </button>
        </div>
      </DashboardLayout>
    )
  }

  const { member, wallets, earnings, teamBusiness, incomeDetails } = data

  // Generate SVG path for smooth line chart based on earnings history
  const generateChartPath = (points: { date: string; amount: number }[], width: number, height: number) => {
    if (!points || points.length < 2) {
      return { linePath: `M 0 ${height / 2} L ${width} ${height / 2}`, areaPath: `M 0 ${height / 2} L ${width} ${height / 2} L ${width} ${height} L 0 ${height} Z` }
    }
    const maxVal = Math.max(...points.map(p => p.amount), 10)
    const minVal = Math.min(...points.map(p => p.amount), 0)
    const valRange = maxVal - minVal

    const coords = points.map((p, i) => {
      const x = (i / (points.length - 1)) * width
      // Invert Y coordinate since SVG (0,0) is top-left
      const y = height - ((p.amount - minVal) / valRange) * (height - 20) - 10
      return { x, y }
    })

    // Create bezier curve path
    let linePath = `M ${coords[0].x} ${coords[0].y}`
    for (let i = 0; i < coords.length - 1; i++) {
      const cpX1 = coords[i].x + (coords[i+1].x - coords[i].x) / 2
      const cpY1 = coords[i].y
      const cpX2 = coords[i].x + (coords[i+1].x - coords[i].x) / 2
      const cpY2 = coords[i+1].y
      linePath += ` C ${cpX1} ${cpY1}, ${cpX2} ${cpY2}, ${coords[i+1].x} ${coords[i+1].y}`
    }

    const areaPath = `${linePath} L ${coords[coords.length - 1].x} ${height} L ${coords[0].x} ${height} Z`
    return { linePath, areaPath }
  }

  const { linePath, areaPath } = generateChartPath(earnings.history, 400, 120)

  // Wallet/Asset List Mapper
  const assetList = [
    { name: 'Earning Wallet', amount: wallets.ewallet, symbol: 'USDT', desc: 'Accrued system earnings', color: 'text-violet-400', isCrypto: false },
    { name: 'Trading Wallet', amount: wallets.tradingWallet, symbol: 'USDT', desc: 'Trading capital wallet', color: 'text-sky-400', isCrypto: false },
    { name: 'Royalty Wallet', amount: wallets.royaltyWallet, symbol: 'USDT', desc: 'Pool share earnings', color: 'text-purple-400', isCrypto: false },
    { name: 'Topup Wallet', amount: wallets.cwallet, symbol: 'USDT', desc: 'Activation and topup balance', color: 'text-emerald-400', isCrypto: false },
    { name: 'MTC Coin Balance', amount: displayMtcBalance, symbol: 'MTC', desc: 'MTE7 Utility Coin Balance', color: 'text-amber-400', isCrypto: true },
  ]

  // Mock recents details derived from logs
  const recentPayments = earnings.history.slice(-4).map((p: any, idx: number) => ({
    name: p.date,
    amount: `+$${p.amount.toFixed(2)}`,
    type: 'ROI Earning',
    initials: 'E',
    bg: 'bg-indigo-500/20 text-indigo-300'
  }))

  return (
    <DashboardLayout>
      
      {/* Top Greeting Block */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 className="text-3xl font-extrabold text-white tracking-tight">Hello, {member.name}!</h1>
          <p className="text-slate-400 text-sm mt-1">Here is your decentralized earnings and downline summary.</p>
        </div>
        
        {/* Status badges */}
        <div className="flex items-center gap-3">
          <div className="px-3.5 py-1.5 rounded-full bg-violet-500/10 border border-violet-500/20 text-xs font-semibold text-violet-300 flex items-center gap-1.5">
            <MdStar size={16} />
            <span>Rank: {member.rank}</span>
          </div>
          <div className={`px-3.5 py-1.5 rounded-full text-xs font-bold border flex items-center gap-1.5 ${
            member.active === 'y' 
              ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400' 
              : 'bg-rose-500/10 border-rose-500/20 text-rose-400'
          }`}>
            <span className={`w-2 h-2 rounded-full ${member.active === 'y' ? 'bg-emerald-400' : 'bg-rose-400'}`}></span>
            <span>{member.active === 'y' ? 'Active' : 'Inactive'}</span>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        {/* LEFT COLUMN: Main Balance & Quick Actions & Assets */}
        <div className="lg:col-span-8 flex flex-col gap-8">
          
          {/* Main Balance & MTC Balance Side-By-Side Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            
            {/* Main Balance Premium Card (Violet/Indigo Gradient Flow) */}
            <div className="bg-gradient-to-br from-violet-950/70 via-indigo-950/60 to-slate-950 border border-violet-500/20 rounded-[32px] p-6 shadow-2xl relative overflow-hidden backdrop-blur-3xl flex flex-col justify-between">
              <div className="absolute top-0 right-0 w-48 h-48 bg-violet-600/10 rounded-full blur-3xl pointer-events-none"></div>
              
              <div className="relative z-10 flex justify-between items-start">
                <div>
                  <p className="text-xs uppercase font-bold text-violet-400 tracking-wider mb-1">Total Earnings</p>
                  <h2 className="text-3xl md:text-4xl font-black text-white tracking-tight mb-1">
                    ${earnings.total.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                  </h2>
                  <div className="flex items-center gap-1 text-emerald-400 text-[10px] font-semibold">
                    <MdTrendingUp size={14} />
                    <span>+{((earnings.total / (wallets.cwallet || 1)) * 100).toFixed(1)}% total ROI efficiency</span>
                  </div>

                  {/* Earnings Breakdown */}
                  <div className="grid grid-cols-2 gap-x-4 gap-y-2 mt-4 text-[11px] bg-slate-950/45 p-3 rounded-2xl border border-violet-500/10 relative z-10">
                    <div className="flex justify-between items-center border-r border-violet-950/30 pr-2">
                      <span className="text-slate-400">Daily ROI:</span>
                      <span className="font-bold text-white">${(earnings.trading || 0).toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between items-center pl-2">
                      <span className="text-slate-400">Direct Refer:</span>
                      <span className="font-bold text-white">${(earnings.sponsor || 0).toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between items-center border-r border-violet-950/30 pr-2 border-t border-violet-950/10 pt-1.5 mt-0.5">
                      <span className="text-slate-400">Level Income:</span>
                      <span className="font-bold text-white">${(earnings.level || 0).toFixed(2)}</span>
                    </div>
                    <div className="flex justify-between items-center pl-2 border-t border-violet-950/10 pt-1.5 mt-0.5">
                      <span className="text-slate-400">Royalty:</span>
                      <span className="font-bold text-white">${(earnings.royalty || 0).toFixed(2)}</span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Smooth Custom SVG Line Chart */}
              <div className="w-full h-24 mt-4 relative z-10">
                <svg className="w-full h-full" viewBox="0 0 400 120" preserveAspectRatio="none">
                  <defs>
                    <linearGradient id="chartGradient" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#8b5cf6" stopOpacity="0.3"/>
                      <stop offset="100%" stopColor="#8b5cf6" stopOpacity="0.0"/>
                    </linearGradient>
                  </defs>
                  
                  {/* Fill Area */}
                  <path d={areaPath} fill="url(#chartGradient)" />
                  
                  {/* Glowing Stroke */}
                  <path d={linePath} fill="none" stroke="#a78bfa" strokeWidth="2.5" strokeLinecap="round" />
                </svg>
              </div>

              {/* Quick Action Shortcuts */}
              <div className="flex justify-around items-center mt-6 pt-4 border-t border-violet-900/30 relative z-10">
                <Link href="/topup" className="flex flex-col items-center gap-1 group">
                  <div className="w-10 h-10 rounded-full bg-violet-600/20 border border-violet-500/30 flex items-center justify-center text-violet-400 group-hover:bg-violet-600 group-hover:text-white transition-all shadow-lg">
                    <MdArrowUpward size={18} />
                  </div>
                  <span className="text-[10px] font-semibold text-slate-300">Deposit</span>
                </Link>
                
                <Link href="/withdrawal" className="flex flex-col items-center gap-1 group">
                  <div className="w-10 h-10 rounded-full bg-indigo-600/20 border border-indigo-500/30 flex items-center justify-center text-indigo-400 group-hover:bg-indigo-600 group-hover:text-white transition-all shadow-lg">
                    <MdArrowDownward size={18} />
                  </div>
                  <span className="text-[10px] font-semibold text-slate-300">Withdraw</span>
                </Link>
                
                <Link href="/withdrawal" className="flex flex-col items-center gap-1 group">
                  <div className="w-10 h-10 rounded-full bg-purple-600/20 border border-purple-500/30 flex items-center justify-center text-purple-400 group-hover:bg-purple-600 group-hover:text-white transition-all shadow-lg">
                    <MdSwapHoriz size={18} />
                  </div>
                  <span className="text-[10px] font-semibold text-slate-300">Transfer</span>
                </Link>
              </div>
            </div>

            {/* MTC Coin Premium Card (Amber/Gold Gradient Flow) */}
            <div className="bg-gradient-to-br from-amber-950/40 via-slate-950 to-slate-950 border border-amber-500/20 rounded-[32px] p-6 shadow-2xl relative overflow-hidden backdrop-blur-3xl flex flex-col justify-between">
              <div className="absolute top-0 right-0 w-48 h-48 bg-amber-500/10 rounded-full blur-3xl pointer-events-none"></div>
              
              <div className="relative z-10 flex-1 flex flex-col justify-between">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="text-xs uppercase font-bold text-amber-400 tracking-wider mb-1">MTC Token Balance</p>
                    <h2 className="text-3xl font-black text-white tracking-tight mb-1 flex items-baseline gap-2">
                      {displayMtcBalance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                      <span className="text-xs font-bold text-amber-400 font-mono">MTC</span>
                    </h2>
                    <p className="text-[10px] text-slate-400 font-medium">MTE7 Utility & Staking Coin</p>
                  </div>
                  <div className="w-10 h-10 rounded-2xl bg-amber-500/10 border border-amber-500/30 flex items-center justify-center text-amber-400 shadow-md">
                    <span className="font-mono text-sm font-bold">MTC</span>
                  </div>
                </div>

                {/* Staking / Blockchain Info Section */}
                <div className="mt-4 p-3 rounded-2xl bg-slate-950/50 border border-amber-500/10 flex flex-col gap-1.5">
                  <div className="flex justify-between items-center text-[10px]">
                    <span className="text-slate-400">Network</span>
                    <span className="font-semibold text-white">BSC Testnet</span>
                  </div>
                  <div className="flex justify-between items-center text-[10px]">
                    <span className="text-slate-400">Contract</span>
                    <a 
                      href={`https://testnet.bscscan.com/token/0xA7E60EAFc976C46ee168939a0b4f85d659f8C5d7`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="font-mono font-medium text-amber-400 hover:underline flex items-center gap-1"
                    >
                      0xA7E60...8C5d7
                    </a>
                  </div>
                  <div className="flex justify-between items-center text-[10px] border-t border-amber-950/40 pt-1.5 mt-1">
                    <span className="text-slate-400">Mock Mode</span>
                    <span className={`px-2 py-0.5 rounded-md text-[8px] font-bold ${
                      isDemo ? 'bg-amber-500/10 text-amber-400 border border-amber-500/20' : 'bg-slate-900 text-slate-500 border border-slate-800'
                    }`}>
                      {isDemo ? 'Demo Session' : 'Web3 Active'}
                    </span>
                  </div>
                </div>
              </div>

              {/* Action buttons for MTC */}
              <div className="flex justify-around items-center mt-6 pt-4 border-t border-amber-950/30 relative z-10">
                <Link href="/topup" className="flex flex-col items-center gap-1 group">
                  <div className="w-10 h-10 rounded-full bg-amber-500/15 border border-amber-500/30 flex items-center justify-center text-amber-400 group-hover:bg-amber-500 group-hover:text-black transition-all shadow-lg">
                    <MdArrowUpward size={18} />
                  </div>
                  <span className="text-[10px] font-semibold text-slate-300">Stake MTC</span>
                </Link>
                
                <a href="https://testnet.bscscan.com/token/0xA7E60EAFc976C46ee168939a0b4f85d659f8C5d7" target="_blank" rel="noopener noreferrer" className="flex flex-col items-center gap-1 group">
                  <div className="w-10 h-10 rounded-full bg-slate-900 border border-slate-800 flex items-center justify-center text-slate-400 group-hover:bg-slate-800 group-hover:text-white transition-all shadow-lg">
                    <MdSwapHoriz size={18} />
                  </div>
                  <span className="text-[10px] font-semibold text-slate-300">Explorer</span>
                </a>
              </div>
            </div>

          </div>

          {/* Asset Wallets List */}
          <div className="glass-panel rounded-3xl p-6 md:p-8">
            <div className="flex justify-between items-center mb-6">
              <h3 className="text-lg font-bold text-white">My Wallet Balances</h3>
              <MdAccountBalanceWallet size={20} className="text-violet-400" />
            </div>

            <div className="flex flex-col gap-4">
              {assetList.map((asset, i) => (
                <div key={i} className="flex justify-between items-center p-4 rounded-2xl bg-slate-950/30 border border-violet-950/20 hover:border-violet-500/10 transition-colors">
                  <div className="flex items-center gap-4">
                    <div className="w-10 h-10 rounded-xl bg-violet-950/50 border border-violet-500/10 flex items-center justify-center">
                      <span className={`font-mono text-xs font-bold ${asset.color}`}>{asset.symbol}</span>
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-white">{asset.name}</p>
                      <p className="text-[10px] text-slate-500 font-medium">{asset.desc}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-base font-bold text-white">
                      {asset.isCrypto 
                        ? `${asset.amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} MTC`
                        : `$${asset.amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
                      }
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* RIGHT COLUMN: MLM Stats, Limits & Recent Logs */}
        <div className="lg:col-span-4 flex flex-col gap-8">
          
          {/* Income details limit progress card */}
          <div className="glass-panel rounded-3xl p-6 border border-violet-500/10 relative overflow-hidden">
            <div className="absolute top-0 right-0 w-32 h-32 bg-violet-600/5 rounded-full blur-xl"></div>
            
            <div className="flex justify-between items-start mb-4">
              <div>
                <p className="text-xs uppercase font-bold text-slate-500 tracking-wider">Income Limits</p>
                <h4 className="text-sm font-semibold text-violet-400 mt-1">Earnings Cap Progress</h4>
              </div>
              <MdTimer className="text-violet-400 animate-pulse" size={20} />
            </div>

            {/* Limits stats */}
            <div className="flex justify-between items-end mb-2">
              <span className="text-xs font-semibold text-slate-400">Total Earned: ${incomeDetails.earned.toFixed(2)}</span>
              <span className="text-xs font-mono font-bold text-white">Limit: ${incomeDetails.limit.toFixed(2)}</span>
            </div>

            {/* Custom progress bar */}
            <div className="h-2 w-full bg-slate-900 rounded-full overflow-hidden border border-violet-950/40 mb-3">
              <div 
                className="h-full bg-gradient-to-r from-violet-600 to-indigo-500 rounded-full" 
                style={{ width: `${Math.min(100, (incomeDetails.earned / (incomeDetails.limit || 1)) * 100)}%` }}
              ></div>
            </div>

            <div className="flex justify-between items-center text-[10px] font-bold text-slate-500 uppercase tracking-wider">
              <span>{((incomeDetails.earned / (incomeDetails.limit || 1)) * 100).toFixed(1)}% reached</span>
              <span className="text-violet-400">${incomeDetails.left.toFixed(2)} left</span>
            </div>
          </div>

          {/* Team Business Summary Stats */}
          <div className="glass-panel rounded-3xl p-6">
            <h3 className="text-base font-bold text-white mb-4">Team Business Summary</h3>
            
            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 rounded-xl bg-slate-950/20 border border-violet-950/20 text-center">
                <p className="text-[10px] text-slate-500 uppercase font-bold tracking-wider mb-1">Total Team</p>
                <p className="text-xl font-extrabold text-white">${teamBusiness.total.toLocaleString()}</p>
              </div>

              <div className="p-4 rounded-xl bg-slate-950/20 border border-violet-950/20 text-center">
                <p className="text-[10px] text-slate-500 uppercase font-bold tracking-wider mb-1">Max Branch</p>
                <p className="text-xl font-extrabold text-violet-400">${teamBusiness.maxTeam.toLocaleString()}</p>
              </div>

              <div className="p-4 rounded-xl bg-slate-950/20 border border-violet-950/20 text-center">
                <p className="text-[10px] text-slate-500 uppercase font-bold tracking-wider mb-1">2nd Max Branch</p>
                <p className="text-xl font-extrabold text-indigo-400">${teamBusiness.maxTeam2.toLocaleString()}</p>
              </div>

              <div className="p-4 rounded-xl bg-slate-950/20 border border-violet-950/20 text-center">
                <p className="text-[10px] text-slate-500 uppercase font-bold tracking-wider mb-1">Rest Team</p>
                <p className="text-xl font-extrabold text-emerald-400">${teamBusiness.restTeam.toLocaleString()}</p>
              </div>
            </div>

            {/* Sponsor info card */}
            <div className="mt-4 p-4 rounded-2xl bg-indigo-950/15 border border-indigo-900/10 flex justify-between items-center">
              <div>
                <p className="text-[10px] text-indigo-400 font-bold uppercase tracking-wider">Sponsor Wallet Address</p>
                <p className="text-sm font-mono font-semibold text-white mt-1 select-all" title={`Sponsor ID: ${member.sponsorId}`}>
                  {(() => {
                    const mId = member.sponsorId || 'MTE123456'
                    const hash = mId.split('').reduce((acc: string, char: string) => acc + char.charCodeAt(0).toString(16), '')
                    const padded = (hash + 'abcdef01234567890123456789abcdef0123456789').substring(0, 40)
                    const fullAddress = `0x${padded}`
                    return `${fullAddress.slice(0, 8)}...${fullAddress.slice(-6)}`
                  })()}
                </p>
              </div>
              <span className="text-[9px] uppercase font-bold text-slate-500 bg-slate-900/60 px-2.5 py-1 rounded-lg border border-violet-950/20 font-mono">
                Sponsor Active
              </span>
            </div>
          </div>

          {/* Recent Income Logs (Recents bubble list like reference image) */}
          <div className="glass-panel rounded-3xl p-6">
            <h3 className="text-base font-bold text-white mb-4">Recent Incomes</h3>
            
            <div className="flex flex-col gap-4">
              {recentPayments.length > 0 ? (
                recentPayments.map((log: any, i: number) => (
                  <div key={i} className="flex justify-between items-center">
                    <div className="flex items-center gap-3">
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-xs ${log.bg}`}>
                        {log.initials}
                      </div>
                      <div>
                        <p className="text-xs font-bold text-white">{log.name}</p>
                        <p className="text-[10px] text-slate-500 font-medium">{log.type}</p>
                      </div>
                    </div>
                    <span className="text-xs font-bold text-emerald-400">{log.amount}</span>
                  </div>
                ))
              ) : (
                <div className="text-xs text-slate-500 text-center py-4">No recent earnings logged.</div>
              )}
            </div>
          </div>

        </div>
      </div>
    </DashboardLayout>
  )
}
