'use client';

import { useState, useEffect } from 'react';
import { X, Copy, Users, Gift, CheckCircle2, Link as LinkIcon, Coins, Share2 } from 'lucide-react';
import { getReferralCode, getReferralDashboard } from '@/services/referral/referral.service';
import { Button } from '@/components/ui/button';
import { useSystemConfig } from '@/hooks/useSystemConfig';

interface ReferralPopupProps {
  open: boolean;
  onClose: () => void;
  onAccept?: () => void;
}

export default function ReferralPopup({ open, onClose, onAccept }: ReferralPopupProps) {
  const sysConfig = useSystemConfig();
  const [code, setCode] = useState<string>('');
  const [referralLink, setReferralLink] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState(false);
  const [copiedLink, setCopiedLink] = useState(false);
  const [totalReferrals, setTotalReferrals] = useState<number>(0);
  const [totalEarned, setTotalEarned] = useState<number>(0);

  useEffect(() => {
    if (open) {
      setLoading(true);
      setCopied(false);
      setCopiedLink(false);
      Promise.all([
        getReferralCode().catch(() => ({ code: '', referralLink: '' })),
        getReferralDashboard().catch(() => null),
      ])
        .then(([codeRes, dashboardRes]) => {
          setCode(codeRes.code);
          setReferralLink(codeRes.referralLink);
          if (dashboardRes) {
            setTotalReferrals(Number(dashboardRes.totalReferrals) || 0);
            setTotalEarned(Number(dashboardRes.referralIncome) || 0);
          }
        })
        .catch(() => {
          setCode('');
          setReferralLink('');
        })
        .finally(() => setLoading(false));
    }
  }, [open]);

  const handleCopyCode = () => {
    if (code) {
      navigator.clipboard.writeText(code);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const handleCopyLink = () => {
    if (referralLink) {
      navigator.clipboard.writeText(referralLink);
      setCopiedLink(true);
      setTimeout(() => setCopiedLink(false), 2000);
    }
  };

  const handleShare = () => {
    if (referralLink) {
      const text = `Join me on this platform! Use my referral code: ${code}\n\n${referralLink}`;
      if (navigator.share) {
        navigator.share({ title: 'Referral', text });
      } else {
        navigator.clipboard.writeText(text);
        setCopiedLink(true);
        setTimeout(() => setCopiedLink(false), 2000);
      }
    }
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
      <div className="max-h-[90vh] w-full max-w-lg overflow-auto rounded-2xl border border-line bg-surface p-6">
        <div className="mb-4 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Gift className="h-6 w-6 text-primary-600" />
            <h2 className="text-xl font-bold text-ink">Referral Program</h2>
          </div>
          <button
            onClick={onClose}
            className="rounded-lg p-1 text-ink-faint hover:text-ink"
            aria-label="Close"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        <div className="rounded-xl border border-primary-500/30 bg-primary-500/10 p-4 mb-4">
          <div className="flex items-start gap-3">
            <Users className="h-5 w-5 text-primary-600 mt-0.5 shrink-0" />
            <div>
              <p className="text-sm font-medium text-ink">
                Earn extra money by inviting friends!
              </p>
              <p className="text-xs text-ink-muted mt-1">
                Share your unique referral code with friends. When they sign up and trade, you automatically earn commission on their activities. The more friends you invite, the more you earn!
              </p>
            </div>
          </div>
        </div>

        {/* Referral code */}
        <div className="rounded-xl border border-line bg-surface-raised p-4 mb-4">
          <p className="text-xs text-ink-faint mb-2">Your Unique Referral Code</p>
          {loading ? (
            <div className="h-10 w-full rounded-lg bg-surface-sunken animate-pulse" />
          ) : (
            <div className="flex items-center gap-2">
              <div className="flex-1 rounded-lg bg-surface-sunken px-4 py-2.5 text-center">
                <span className="text-2xl font-bold tracking-widest text-primary-600">
                  {code || '------'}
                </span>
              </div>
              <button
                onClick={handleCopyCode}
                className="rounded-lg border border-line bg-surface px-3 py-2.5 hover:bg-surface-raised transition-colors"
                title="Copy code"
              >
                {copied ? <CheckCircle2 className="h-5 w-5 text-emerald-500" /> : <Copy className="h-5 w-5 text-ink-muted" />}
              </button>
            </div>
          )}
        </div>

        {/* Referral link */}
        <div className="rounded-xl border border-line bg-surface-raised p-4 mb-4">
          <div className="flex items-center justify-between mb-2">
            <p className="text-xs text-ink-faint">Your Referral Link</p>
            <button
              onClick={handleCopyLink}
              className="flex items-center gap-1 text-xs text-ink-muted hover:text-ink"
              title="Copy link"
            >
              {copiedLink ? <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" /> : <Copy className="h-3.5 w-3.5" />}
              {copiedLink ? 'Copied!' : 'Copy'}
            </button>
          </div>
          {loading ? (
            <div className="h-8 w-full rounded-lg bg-surface-sunken animate-pulse" />
          ) : (
            <div className="flex items-center gap-2">
              <LinkIcon className="h-4 w-4 text-ink-faint shrink-0" />
              <code className="break-all text-sm font-mono text-ink">
                {referralLink || sysConfig.signupUrl}
              </code>
            </div>
          )}
        </div>

        {/* Referral rewards info */}
        <div className="rounded-xl border border-line bg-surface-raised p-4 mb-4">
          <p className="text-xs text-ink-faint mb-3">Referral Rewards</p>
          <div className="grid grid-cols-2 gap-4">
            <div className="flex items-center gap-3">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-500/10 text-emerald-500">
                <Users className="h-4 w-4" />
              </div>
              <div>
                <p className="text-xs text-ink-faint">Total Referrals</p>
                <p className="text-lg font-bold text-ink">{loading ? '—' : totalReferrals}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-amber-500/10 text-amber-500">
                <Coins className="h-4 w-4" />
              </div>
              <div>
                <p className="text-xs text-ink-faint">Total Earned</p>
                <p className="text-lg font-bold text-ink">{loading ? '—' : `${totalEarned.toFixed(2)} ${sysConfig.currency}`}</p>
              </div>
            </div>
          </div>
          <div className="mt-3 space-y-1.5 text-xs text-ink-muted">
            <div className="flex items-center gap-2">
              <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
              <span>{sysConfig.referralPerTradeRate} {sysConfig.currency} commission for every completed trade by your referrals</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
              <span>Earn up to {sysConfig.referralFirstBuyRate}% commission on first buy of referred users</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
              <span>Multi-level: earn from up to {sysConfig.referralLevels} levels of referrals</span>
            </div>
          </div>
        </div>

        <div className="flex justify-between gap-3">
          <Button variant="outline" size="sm" onClick={handleShare}>
            <Share2 className="h-4 w-4" />
            Share Link
          </Button>
          <Button onClick={onClose} className="min-w-[120px]">
            Got it
          </Button>
        </div>
      </div>
    </div>
  );
}
