import BottomNav from '@/Components/Ck44/BottomNav';
import React, { useEffect, useMemo, useState } from 'react';

const tabs = ['Overview', 'Rewards', 'Incomes', 'Records', 'Invited List'];

const rewardCards = [
  { icon: '🏅', title: 'Over 3 valid referral in total.', amount: '৳ 30.00', count: '0', target: '/3' },
  { icon: '🥈', title: 'Over 7 valid referral in total.', amount: '৳ 40.00', count: '0', target: '/7' },
  { icon: '💎', title: 'Over 12 valid referral in total.', amount: '৳ 50.00', count: '0', target: '/12' },
  { icon: '🎖️', title: 'Over 20 valid referral in total.', amount: '৳ 100.00', count: '0', target: '/20' },
  { icon: '⭐', title: 'Over 50 valid referral in total.', amount: '৳ 300.00', count: '0', target: '/50' },
  { icon: '🌟', title: 'Over 100 valid referral in total.', amount: '৳ 500.00', count: '0', target: '/100' },
  { icon: '🏆', title: 'Over 200 valid referral in total.', amount: '৳ 1,000.00', count: '0', target: '/200' },
  { icon: '💠', title: 'Over 500 valid referral in total.', amount: '৳ 3,000.00', count: '0', target: '/500' },
  { icon: '👑', title: 'Over 1000 valid referral in total.', amount: '৳ 5,000.00', count: '0', target: '/1000' },
  { icon: '👑', title: 'Over 2000 valid referral in total.', amount: '৳ 10,000.00', count: '0', target: '/2000' },
  { icon: '👑', title: 'Over 3000 valid referral in total.', amount: '৳ 15,000.00', count: '0', target: '/3000' },
  { icon: '👑', title: 'Over 5000 valid referral in total.', amount: '৳ 30,000.00', count: '0', target: '/5000' },
];

const vipRows = [
  { vip: 'VIP0', bonus: '100TK', request: 'Deposit 100TK & Bet 200TK', how: '' },
  { vip: 'VIP1-2', bonus: '150TK', request: 'Deposit 100TK & Bet 2000TK', how: '' },
  { vip: 'VIP3-5', bonus: '200TK', request: 'Deposit 100TK & Bet 2000TK', how: '' },
  { vip: 'VIP6-8', bonus: '300TK & Golden EGG', request: 'Deposit 200TK & Bet 4000TK', how: 'Noon the next day before 12 o\'clock automatic transfer to account' },
  { vip: 'VIP9-18', bonus: '400TK & Golden EGG', request: 'Deposit 300TK & Bet 6000TK', how: '' },
  { vip: 'VIP18-25', bonus: '700TK & Golden EGG', request: 'Deposit 500TK & Bet 10000TK', how: '' },
  { vip: 'VIP26-30', bonus: '1000TK & Golden EGG', request: 'Deposit 500TK & Bet 10000TK', how: '' },
];

const releasedRewards = [
  { title: 'Invitation Rewards', amount: '৳ 36,591,440.00', claimed: '71391 claimed', icon: '⭐' },
  { title: 'Achievement Rewards', amount: '৳ 939,010.00', claimed: '14123 claimed', icon: '🏅' },
  { title: 'Deposit Rebate', amount: '৳ 48,928,161.14', claimed: '195925 claimed', icon: '💰' },
  { title: 'Betting Rebate', amount: '৳ 74,168,467.68', claimed: '311290 claimed', icon: '💵' },
];

const leaderboard = [
  { place: '2nd', name: '01******1', amount: '৳ 16,030,503.20', emoji: '🧑‍💼' },
  { place: '1st', name: '01******3', amount: '৳ 19,090,763.34', emoji: '👨' },
  { place: '3rd', name: '01******8', amount: '৳ 10,566,960.67', emoji: '👩' },
];

const rewardFeed = [
  { user: '01******3', type: 'Received', value: 'Golden Egg' },
  { user: '01******5', type: 'Received', value: '৳ 360.00' },
  { user: '01******5', type: 'Received', value: 'Golden Egg' },
  { user: 'pu****g', type: 'Received', value: '৳ 120.00' },
];

const incomeRows = [
  ['Invitation Rewards', '৳ 0.00'],
  ['Achievement Rewards', '৳ 0.00'],
  ['Deposit Rebate', '৳ 0.00'],
  ['Betting Rebate', '৳ 0.00'],
  ['Registers', '0'],
  ['Valid Referral', '0'],
  ['Depositors', '0'],
];

const recordTypes = ['Invitation Rewards', 'Achievement Rewards', 'Deposit Rebate', 'Betting Rebate'];
const invitedStatuses = ['All', 'Qualified', 'Not Qualified'];

function cx(...classes) {
  return classes.filter(Boolean).join(' ');
}

function Header() {
  const handleBack = () => {
    window.history.back();
  };

  return (
    <div className="sticky top-0 z-20 bg-[#0b5d5d] px-4 pb-3 pt-4 text-white shadow-sm">
      <div className="flex items-center gap-3">
        <button
          type="button"
          onClick={handleBack}
          className="text-3xl leading-none text-[#ffc233]"
        >
          ‹
        </button>

        <h1 className="flex-1 text-center text-[22px] font-bold tracking-tight text-[#ffc517]">
          Invite Friends
        </h1>

        <div className="w-6" />
      </div>
    </div>
  );
}

function TabBar({ active, setActive }) {
  return (
    <div className="sticky top-[60px] z-10 bg-white">
      <div className="overflow-x-auto whitespace-nowrap border-b border-slate-200 px-2">
        <div className="flex min-w-max gap-5 px-2">
          {tabs.map((tab) => (
            <button
              key={tab}
              onClick={() => setActive(tab)}
              className={cx(
                'relative py-4 text-[17px] font-medium',
                active === tab ? 'text-[#2990ff]' : 'text-slate-900'
              )}
            >
              {tab}
              {active === tab && (
                <span className="absolute bottom-0 left-0 right-0 h-[3px] rounded-full bg-[#2990ff]" />
              )}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function SummaryCard({ label, value, purple = false }) {
  return (
    <div className={cx(
      'rounded-md p-3 text-center text-white shadow-sm',
      purple ? 'bg-gradient-to-r from-[#ba8df4] to-[#7d62ed]' : 'bg-gradient-to-r from-[#8fd1f6] to-[#2896f3]'
    )}>
      <div className="text-[12px] font-semibold opacity-95">{label}</div>
      <div className="mt-1 text-[15px] font-bold leading-none">{value}</div>
    </div>
  );
}



function OverviewTab() {
  const [inviteCount, setInviteCount] = useState(1);
  const [copied, setCopied] = useState(false);

  const referralLink = 'https://bajikhelo.com/?r=bp8478';

  const calculatedAmount = useMemo(() => {
    const amountPerUser = 1000;
    return inviteCount * amountPerUser;
  }, [inviteCount]);

  const handleCopyReferralLink = async () => {
    try {
      await navigator.clipboard.writeText(referralLink);
      setCopied(true);
    } catch (error) {
      const textArea = document.createElement('textarea');
      textArea.value = referralLink;
      textArea.style.position = 'fixed';
      textArea.style.opacity = '0';
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();

      try {
        document.execCommand('copy');
        setCopied(true);
      } catch (fallbackError) {
        console.error('Copy failed:', fallbackError);
      }

      document.body.removeChild(textArea);
    }
  };

  useEffect(() => {
    if (!copied) return;

    const timer = setTimeout(() => {
      setCopied(false);
    }, 1800);

    return () => clearTimeout(timer);
  }, [copied]);

  return (
    <div className="space-y-5 px-3 py-4">
      <div className="grid grid-cols-2 gap-2">
        <SummaryCard label="Today's Income" value="৳ 0.00" />
        <SummaryCard label="Yesterday's Income" value="৳ 0.00" purple />
        <SummaryCard label="Registers" value="0" purple />
        <SummaryCard label="Valid Referral" value="0" />
      </div>

      <div className="rounded-lg bg-white p-3 shadow-sm">
        <div className="mb-2 text-sm font-bold text-[#46308c]">Share to your friends</div>

        <div className="flex gap-3">
          <div className="flex h-20 w-20 items-center justify-center rounded-md border bg-white text-xs font-semibold text-slate-500">
            QR
          </div>

          <div className="flex-1 space-y-2">
            <div className="flex items-center justify-between rounded-md bg-slate-100 px-3 py-2 text-[11px] text-slate-600">
              <span className="truncate">{referralLink}</span>

              <button
                type="button"
                onClick={handleCopyReferralLink}
                className="ml-3 rounded-full bg-[#5338a8] px-2 py-0.5 text-white"
              >
                ⎘
              </button>
            </div>

            {copied && (
              <div className="rounded-md bg-green-100 px-3 py-2 text-[12px] font-semibold text-green-700">
                Referral link copied successfully
              </div>
            )}

            <div className="flex flex-wrap gap-2 text-white">
              {['f', 'x', '↗', 'wa', '💬', 'line', '➦'].map((s, i) => (
                <span
                  key={i}
                  className={cx(
                    'flex h-9 w-9 items-center justify-center rounded-md text-xs font-bold',
                    i === 1
                      ? 'bg-black'
                      : i === 3
                      ? 'bg-[#28c15f]'
                      : i === 5
                      ? 'bg-[#16c655]'
                      : 'bg-[#3b82f6]'
                  )}
                >
                  {s}
                </span>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="text-center">
        <div className="text-[18px] font-bold text-[#29295e]">
          Invite 1 person and earn up to 1000TK
        </div>
        <div className="mt-2 text-[15px] font-semibold text-[#f69f1a]">
          Earn 2.2% on lower level deposits
        </div>
        <div className="mt-2 text-[15px] font-semibold text-[#f0a11a]">
          Lower level earns 1% on every bet
        </div>
      </div>

      <div className="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm">
        <div className="overflow-x-auto">
          <table className="min-w-full text-center text-[12px] text-slate-700">
            <thead className="bg-slate-50 text-[11px] font-semibold text-slate-900">
              <tr>
                <th className="border p-3">Inviter VIP level</th>
                <th className="border p-3">Referral bonus/person</th>
                <th className="border p-3">Recommend a friend request</th>
                <th className="border p-3">How to get it?</th>
              </tr>
            </thead>
            <tbody>
              {vipRows.map((row, idx) => (
                <tr key={idx}>
                  <td className="border p-3">{row.vip}</td>
                  <td className="border p-3">{row.bonus}</td>
                  <td className="border p-3">{row.request}</td>
                  <td className="border p-3">{row.how}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div>
        <h2 className="mb-3 text-center text-[18px] font-bold text-[#2b2d68]">
          Rewards Released to Date
        </h2>

        <div className="space-y-3">
          {releasedRewards.map((item) => (
            <div
              key={item.title}
              className="flex items-center gap-4 rounded-lg bg-[#eef2f7] p-4 shadow-sm"
            >
              <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-white text-3xl shadow-sm">
                {item.icon}
              </div>

              <div>
                <div className="text-[22px] font-bold leading-none text-[#5d5f8e]">
                  {item.title}
                </div>
                <div className="mt-2 text-[16px] font-bold text-[#3a3b8f]">
                  {item.amount}
                </div>
                <div className="mt-1 text-sm text-slate-500">{item.claimed}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div>
        <style>
          {`
            .reward-feed-wrap {
              position: relative !important;
              height: 150px !important;
              overflow: hidden !important;
            }

            .reward-feed-track {
              display: flex !important;
              flex-direction: column !important;
              gap: 8px !important;
              animation: rewardFeedUp 10s linear infinite !important;
              will-change: transform !important;
            }

            .reward-feed-wrap:hover .reward-feed-track {
              animation-play-state: paused !important;
            }

            @keyframes rewardFeedUp {
              0% {
                transform: translateY(0%);
              }
              100% {
                transform: translateY(-50%);
              }
            }

            .reward-row {
              display: grid !important;
              grid-template-columns: 1.2fr 0.9fr 1fr !important;
              align-items: center !important;
              border-radius: 9999px !important;
              background: rgba(255, 255, 255, 0.95) !important;
              padding: 10px 16px !important;
              font-size: 13px !important;
              font-weight: 600 !important;
              color: #475569 !important;
            }

            .reward-row-value {
              text-align: right !important;
              color: #4b4f8f !important;
            }
          `}
        </style>

        <h2 className="mb-3 text-center text-[18px] font-bold text-[#2b2d68]">
          Leaderboard
        </h2>

        <div className="rounded-2xl bg-gradient-to-b from-[#44b3ff] via-[#5176ff] to-[#9b17d6] p-4 text-white shadow-lg">
          <div className="grid grid-cols-3 gap-2 text-center">
            {leaderboard.map((item, idx) => (
              <div
                key={item.place}
                className={cx('rounded-2xl p-2', idx === 1 && 'scale-[1.03]')}
              >
                <div className="text-xl font-bold">{item.place}</div>

                <div className="mx-auto mt-2 flex h-20 w-20 items-center justify-center rounded-full border-4 border-[#ffe07f] bg-white text-4xl shadow-md">
                  <span>{item.emoji}</span>
                </div>

                <div className="mt-2 text-sm font-semibold">{item.name}</div>
                <div className="mt-1 text-sm font-bold">{item.amount}</div>
              </div>
            ))}
          </div>

          <div className="mt-4 text-center text-[18px] font-bold">
            Who received the rewards
          </div>

          <div className="reward-feed-wrap mt-3">
            <div className="reward-feed-track">
              {[...rewardFeed, ...rewardFeed].map((row, idx) => (
                <div key={idx} className="reward-row">
                  <div>{row.user}</div>
                  <div>{row.type}</div>
                  <div className="reward-row-value">{row.value}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="rounded-2xl bg-gradient-to-br from-[#e95982] to-[#1638d4] p-5 text-white shadow-lg">
        <div className="flex items-center gap-4">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-white/20 text-4xl">
            💸
          </div>

          <div>
            <div className="text-[20px] font-bold leading-none">Income</div>
            <div className="text-[20px] font-bold leading-none">calculator</div>
          </div>
        </div>

        <div className="mt-8 text-center text-[28px] font-bold">
          ৳ {calculatedAmount.toLocaleString('en-US', { minimumFractionDigits: 2 })}
        </div>

        <div className="mt-3 text-center text-sm font-medium">
          Invite {inviteCount} active users, expected revenue
        </div>

        <input
          type="range"
          min="1"
          max="10"
          value={inviteCount}
          onChange={(e) => setInviteCount(Number(e.target.value))}
          className="mt-6 w-full"
        />
      </div>
    </div>
  );
}


function RewardsTab() {
  return (
    <div className="space-y-3 px-3 py-4">
      <div className="text-right text-sm text-slate-600">no expiration</div>
      {rewardCards.map((item, idx) => (
        <div key={idx} className="flex items-center gap-4 rounded-lg bg-[#eef2f7] p-4 shadow-sm">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-white text-4xl shadow-sm">{item.icon}</div>
          <div className="flex-1">
            <div className="text-[15px] font-bold text-slate-500">{item.title}</div>
            <div className="mt-1 text-[26px] font-bold text-slate-400">{item.amount}</div>
          </div>
          <div className="text-center">
            <div className="text-[34px] font-bold leading-none text-[#6b59c8]">{item.count}</div>
            <div className="text-sm font-semibold text-slate-400">{item.target}</div>
            <button className="mt-2 rounded-md bg-gradient-to-r from-[#7bd2ff] to-[#a547ea] px-4 py-2 text-sm font-semibold text-white">Available</button>
          </div>
        </div>
      ))}
    </div>
  );
}

function IncomeBlock({ title }) {
  return (
    <div className="rounded-2xl bg-[#f5f5f5] p-4 shadow-sm">
      <div className="pb-4 text-center text-[18px] font-bold text-slate-700">{title} <span className="text-[#3c338b]">৳ 0.00</span></div>
      <div className="border-t border-slate-200 pt-5">
        <div className="rounded-xl bg-[#edf2f8] p-5">
          <div className="space-y-3 text-[16px] font-semibold text-slate-600">
            {incomeRows.map(([name, value]) => (
              <div key={name} className="flex items-center justify-between gap-4">
                <span>{name}</span>
                <span className="text-[#34338f]">{value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function IncomesTab() {
  return (
    <div className="space-y-6 px-3 py-4">
      <IncomeBlock title="Today's Income:" />
      <IncomeBlock title="Total Income" />
      <p className="text-[15px] text-slate-600">Note : The system updates the data every 15 minutes.</p>
    </div>
  );
}

function EmptyState() {
  return (
    <div className="flex min-h-[420px] flex-col items-center justify-center text-[#1e91df]">
      <div className="text-[120px] leading-none">📤</div>
      <div className="mt-2 text-[22px]">No data</div>
    </div>
  );
}

function BottomSheet({ title, items, selected, onSelect, onClose }) {
  return (
    <div className="fixed inset-0 z-30 flex items-end bg-black/35">
      <div className="w-full rounded-t-2xl bg-white p-5 shadow-2xl">
        <div className="mb-4 flex items-center justify-between">
          <h3 className="text-[20px] font-bold text-slate-700">{title}</h3>
          <button onClick={onClose} className="flex h-8 w-8 items-center justify-center rounded-full bg-slate-400 text-lg text-white">×</button>
        </div>
        <div className="divide-y">
          {items.map((item) => (
            <button
              key={item}
              onClick={() => {
                onSelect(item);
                onClose();
              }}
              className="flex w-full items-center justify-between py-4 text-left text-[18px] font-semibold text-slate-700"
            >
              <span>{item}</span>
              {selected === item ? <span className="text-2xl text-red-500">✓</span> : null}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function RecordsTab() {
  const [type, setType] = useState('Invitation Rewards');
  const [sheetOpen, setSheetOpen] = useState(false);

  return (
    <div className="px-3 py-4">
      <div className="grid grid-cols-2 gap-3">
        <button onClick={() => setSheetOpen(true)} className="flex items-center justify-between rounded-md border border-[#2f96ff] bg-white px-4 py-3 text-[16px] text-[#2486e6] shadow-sm">
          <span>{type}</span>
          <span>⌄</span>
        </button>
        <button className="rounded-md border border-[#2f96ff] bg-white px-4 py-3 text-[16px] text-[#2486e6] shadow-sm">🗓 04/03- 04/03</button>
      </div>

      <div className="mt-5 overflow-hidden rounded-lg border border-slate-200 bg-white">
        <div className="grid grid-cols-3 bg-slate-50 px-3 py-4 text-center text-[13px] font-semibold text-slate-600">
          <div>Registration date</div>
          <div>Username</div>
          <div>Amount</div>
        </div>
        <EmptyState />
        <div className="border-t bg-slate-50 px-6 py-4 text-center text-[18px] font-bold text-slate-600">Total <span className="ml-20">0.00</span></div>
      </div>

      {sheetOpen && (
        <BottomSheet
          title="Types"
          items={recordTypes}
          selected={type}
          onSelect={setType}
          onClose={() => setSheetOpen(false)}
        />
      )}
    </div>
  );
}

function InvitedListTab() {
  const [status, setStatus] = useState('All');
  const [sheetOpen, setSheetOpen] = useState(false);

  return (
    <div className="space-y-4 px-3 py-4">
      <div className="grid grid-cols-[1.3fr_.9fr] gap-2">
        <div className="rounded-2xl bg-[#dff0fb] p-4 shadow-sm">
          <div className="grid grid-cols-[72px_1fr] gap-3">
            <div className="flex flex-col items-center justify-center">
              <div className="text-5xl">💎</div>
              <div className="mt-1 text-[17px] font-bold italic text-[#103b67]">L1</div>
            </div>
            <div className="space-y-4">
              <div>
                <div className="flex items-center justify-between text-[15px] font-bold text-[#0d4b7b]">
                  <span>Registers</span>
                  <span>0</span>
                </div>
                <div className="mt-1 h-6 rounded-full bg-white/90" />
              </div>
              <div>
                <div className="flex items-center justify-between text-[15px] font-bold text-[#0d4b7b]">
                  <span>Valid Referral</span>
                  <span>0</span>
                </div>
                <div className="mt-1 h-6 rounded-full bg-white/90" />
              </div>
            </div>
          </div>
        </div>
        <div className="space-y-2">
          {['Today', 'Yesterday', 'Current Month'].map((label) => (
            <div key={label} className="rounded-xl border border-[#ecd9b8] bg-[#f6ebd9] px-4 py-3 text-[15px] font-semibold text-[#d18609] shadow-sm">
              <div className="flex items-center justify-between"><span>{label}</span><span className="text-slate-700">+0</span></div>
            </div>
          ))}
        </div>
      </div>

      <div className="grid grid-cols-[1fr_auto] gap-3">
        <div className="flex gap-0">
          <button onClick={() => setSheetOpen(true)} className="flex-1 rounded-l-md border border-[#2f96ff] bg-[#0e67b5] px-4 py-3 text-left text-[16px] text-white shadow-sm">
            {status} <span className="float-right">⌄</span>
          </button>
          <button className="rounded-r-md bg-[#168aef] px-4 py-3 text-[16px] font-medium text-white shadow-sm">◉ Today</button>
        </div>
        <button className="rounded-md border border-[#2f96ff] bg-white px-4 py-3 text-[16px] text-[#2486e6] shadow-sm">🗓 04/03- 04/03</button>
      </div>

      <div className="rounded-lg border border-slate-200 bg-white">
        <EmptyState />
      </div>

      {sheetOpen && (
        <BottomSheet
          title="Status"
          items={invitedStatuses}
          selected={status}
          onSelect={setStatus}
          onClose={() => setSheetOpen(false)}
        />
      )}
    </div>
  );
}

export default function InviteFriendsPage() {
  const [activeTab, setActiveTab] = useState('Overview');

  const content = useMemo(() => {
    switch (activeTab) {
      case 'Rewards':
        return <RewardsTab />;
      case 'Incomes':
        return <IncomesTab />;
      case 'Records':
        return <RecordsTab />;
      case 'Invited List':
        return <InvitedListTab />;
      default:
        return <OverviewTab />;
    }
  }, [activeTab]);

  return (
    <div className="min-h-screen bg-[#f6f7f9] text-slate-900 pb-20  ">
      <div className="mx-auto min-h-screen w-full max-w-md bg-[#f6f7f9] shadow-sm">
        <Header />
        <TabBar active={activeTab} setActive={setActiveTab} />
        {content}
      </div>
      {/* <BottomNav /> */}
    </div>
  );
}

 