import { useState, useEffect, useRef } from 'react';
import { Star, Gift, Users, Trophy, Copy, Check, Loader2, Calendar, ArrowUpRight, ArrowDownRight, ChevronRight } from 'lucide-react';
import { useLoyalty } from '@/hooks/useLoyalty';
import { toast } from 'sonner';
import { useT, useLang, locale } from '@/lib/i18n';

const TIER_COLORS: Record<string, string> = {
  Bronze: 'from-amber-700 to-amber-500',
  Silver: 'from-slate-400 to-slate-300',
  Gold: 'from-yellow-500 to-amber-400',
};

const LoyaltyDashboard = () => {
  const t = useT();
  const lang = useLang();
  const { loyalty, isLoading, redeemPoints, redeemLoading, setBirthday, claimRegistrationBonus } = useLoyalty();
  const [copied, setCopied] = useState(false);
  const [birthdayInput, setBirthdayInput] = useState('');
  const [redeemAmount, setRedeemAmount] = useState('');

  const [justUnlocked, setJustUnlocked] = useState(false);
  const prevCanRedeemRef = useRef<boolean | null>(null);
  const unlockFromRef = useRef<number>(0.6);
  useEffect(() => {
    if (!loyalty) return;
    const prev = prevCanRedeemRef.current;
    if (prev === false && loyalty.canRedeem === true) {
      unlockFromRef.current = 0.85;
      setJustUnlocked(true);
      const t = setTimeout(() => setJustUnlocked(false), 1100);
      prevCanRedeemRef.current = loyalty.canRedeem;
      return () => clearTimeout(t);
    }
    prevCanRedeemRef.current = loyalty.canRedeem;
  }, [loyalty]);

  if (isLoading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3].map(i => <div key={i} className="h-32 bg-muted/50 rounded-2xl animate-pulse" />)}
      </div>
    );
  }

  if (!loyalty) {
    return (
      <div className="text-center py-12 bg-card border border-border/50 rounded-2xl">
        <Star className="w-10 h-10 text-muted-foreground mx-auto mb-3" />
        <p className="text-sm text-muted-foreground">{t('Loyaliteitsprogramma kon niet worden geladen.', 'Loyalty programme could not be loaded.')}</p>
      </div>
    );
  }

  const tierColor = TIER_COLORS[loyalty.tier] || TIER_COLORS.Bronze;
  const progressToNext = loyalty.nextTier
    ? ((loyalty.lifetime - (loyalty.config.TIERS.find(t => t.name === loyalty.tier)?.minPoints || 0)) /
       (loyalty.nextTier.pointsNeeded + loyalty.lifetime - (loyalty.config.TIERS.find(t => t.name === loyalty.tier)?.minPoints || 0))) * 100
    : 100;

  const handleCopyReferral = async () => {
    const link = `${window.location.origin}?ref=${loyalty.referralCode}`;
    await navigator.clipboard.writeText(link);
    setCopied(true);
    toast.success(t('Verwijzingslink gekopieerd!', 'Referral link copied!'));
    setTimeout(() => setCopied(false), 2000);
  };

  const handleRedeem = async () => {
    const points = parseInt(redeemAmount, 10);
    if (!points || points < loyalty.minRedemption) {
      toast.error(t(`Minimaal ${loyalty.minRedemption} punten vereist`, `Minimum ${loyalty.minRedemption} points required`));
      return;
    }
    if (points > loyalty.availableBalance) {
      toast.error(t('Onvoldoende beschikbare punten', 'Insufficient available points'));
      return;
    }
    try {
      const result = await redeemPoints(points) as { discount?: number };
      toast.success(t(`${points} punten ingewisseld voor €${(result.discount ?? points * loyalty.pointsToEuro).toFixed(2)} korting!`, `${points} points redeemed for €${(result.discount ?? points * loyalty.pointsToEuro).toFixed(2)} discount!`));
      setRedeemAmount('');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : t('Inwisselen mislukt', 'Redemption failed'));
    }
  };

  const handleSetBirthday = async () => {
    if (!birthdayInput) return;
    try {
      await setBirthday(birthdayInput);
      toast.success(t('Geboortedatum opgeslagen!', 'Date of birth saved!'));
    } catch (err) {
      toast.error(err instanceof Error ? err.message : t('Opslaan mislukt', 'Saving failed'));
    }
  };

  const handleClaimRegistration = async () => {
    try {
      await claimRegistrationBonus();
      toast.success(t(`${loyalty.config.REGISTRATION_BONUS} welkomstpunten ontvangen!`, `${loyalty.config.REGISTRATION_BONUS} welcome points received!`));
    } catch (err) {
      if (err instanceof Error && err.message.includes('already')) {
        toast.info(t('Welkomstbonus is al eerder geclaimd', 'Welcome bonus has already been claimed'));
      } else {
        toast.error(t('Claimen mislukt', 'Claiming failed'));
      }
    }
  };

  return (
    <div className="space-y-6">
      <div className={`relative overflow-hidden rounded-2xl bg-gradient-to-br ${tierColor} p-6 text-white shadow-lg`}>
        <div className="absolute top-0 right-0 opacity-10">
          <Trophy className="w-32 h-32 -mt-4 -mr-4" />
        </div>
        <div className="relative">
          <div className="flex items-center gap-2 mb-1">
            <Trophy className="w-5 h-5" />
            <span className="text-sm font-bold uppercase tracking-wider opacity-90">{loyalty.tier} {t('Lid', 'Member')}</span>
          </div>
          <p className="text-4xl font-black mb-1">{loyalty.availableBalance.toLocaleString()}</p>
          <p className="text-sm opacity-80">
            {t('beschikbare punten', 'available points')}
            {loyalty.reserved > 0 && (
              <span className="opacity-70"> · {loyalty.reserved.toLocaleString()} {t('gereserveerd', 'reserved')}</span>
            )}
          </p>
          {loyalty.canRedeem && (
            <p className="text-sm mt-2 bg-white/20 inline-block px-3 py-1 rounded-full font-semibold">
              = €{loyalty.redeemableEuros.toFixed(2)} {t('korting', 'discount')}
            </p>
          )}
        </div>
        {loyalty.nextTier && (
          <div className="mt-5">
            <div className="flex justify-between text-xs font-medium opacity-80 mb-1">
              <span>{loyalty.tier}</span>
              <span>{loyalty.nextTier.name}</span>
            </div>
            <div className="h-2 bg-white/20 rounded-full overflow-hidden">
              <div className="h-full bg-white rounded-full transition-all duration-500" style={{ width: `${Math.min(progressToNext, 100)}%` }} />
            </div>
            <p className="text-xs opacity-70 mt-1">
              {t('Nog', 'Still')} {loyalty.nextTier.pointsNeeded.toLocaleString()} {t('punten tot', 'points until')} {loyalty.nextTier.name}
            </p>
          </div>
        )}
      </div>

      <div className="grid grid-cols-3 gap-3">
        <div className="bg-card border border-border/50 rounded-xl p-4 text-center">
          <p className="text-2xl font-black">{loyalty.lifetime.toLocaleString()}</p>
          <p className="text-xs text-muted-foreground">{t('Totaal verdiend', 'Total earned')}</p>
        </div>
        <div className="bg-card border border-border/50 rounded-xl p-4 text-center">
          <p className="text-2xl font-black">{loyalty.tierMultiplier}x</p>
          <p className="text-xs text-muted-foreground">{t('Verdiensnelheid', 'Earning rate')}</p>
        </div>
        <div className={`bg-card border rounded-xl p-4 text-center ${justUnlocked ? 'border-primary/60' : 'border-border/50'}`}>
          <p className="text-2xl font-black">{loyalty.canRedeem ? `€${loyalty.redeemableEuros.toFixed(2)}` : Math.max(0, loyalty.minRedemption - loyalty.availableBalance).toLocaleString()}</p>
          <p className="text-xs text-muted-foreground">{loyalty.canRedeem ? t('Inwisselbaar', 'Redeemable') : t('Punten tot inwisselbaar', 'Points until redeemable')}</p>
        </div>
      </div>

      {loyalty.canRedeem && (
        <div className="bg-card border border-border/50 rounded-2xl p-5 shadow-card">
          <h3 className="font-bold text-sm mb-3 flex items-center gap-2">
            <Gift className="w-4 h-4 text-primary" /> {t('Punten Inwisselen', 'Redeem Points')}
          </h3>
          <p className="text-xs text-muted-foreground mb-3">
            {loyalty.config.MIN_REDEMPTION} {t('punten = ', 'points = ')}€{(loyalty.config.MIN_REDEMPTION * loyalty.config.POINTS_TO_EURO).toFixed(2)} {t('korting.', 'discount.')}
          </p>
          <div className="flex gap-2">
            <input
              type="number"
              value={redeemAmount}
              onChange={(e) => setRedeemAmount(e.target.value)}
              placeholder={t(`Min. ${loyalty.minRedemption}`, `Min. ${loyalty.minRedemption}`)}
              min={loyalty.minRedemption}
              max={loyalty.availableBalance}
              className="flex-1 px-3 py-2.5 border border-border/50 rounded-xl bg-background text-sm focus:ring-2 focus:ring-primary/20 outline-none"
            />
            <button onClick={handleRedeem} disabled={redeemLoading} className="px-4 py-2.5 gradient-primary text-white font-bold rounded-xl text-sm disabled:opacity-50">
              {redeemLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('Inwisselen', 'Redeem')}
            </button>
          </div>
        </div>
      )}

      {!loyalty.history?.some((h) => h.type === 'registration') && (
        <button onClick={handleClaimRegistration} className="w-full bg-card border border-border/50 rounded-2xl p-5 shadow-card text-left hover:shadow-card-hover transition-all group">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-success/10 rounded-xl flex items-center justify-center">
                <Star className="w-5 h-5 text-success" />
              </div>
              <div>
                <p className="font-bold text-sm">{t('Welkomstbonus', 'Welcome bonus')}</p>
                <p className="text-xs text-muted-foreground">{t(`Claim ${loyalty.config.REGISTRATION_BONUS} gratis punten!`, `Claim ${loyalty.config.REGISTRATION_BONUS} free points!`)}</p>
              </div>
            </div>
            <ChevronRight className="w-4 h-4 text-muted-foreground group-hover:text-primary transition-colors" />
          </div>
        </button>
      )}

      <div className="bg-card border border-border/50 rounded-2xl p-5 shadow-card">
        <h3 className="font-bold text-sm mb-1 flex items-center gap-2">
          <Users className="w-4 h-4 text-primary" /> {t('Vrienden Verwijzen', 'Refer Friends')}
        </h3>
        <p className="text-xs text-muted-foreground mb-3">
          {t(`Deel uw code en ontvang ${loyalty.config.REFERRAL_BONUS_REFERRER} punten. Uw vriend krijgt ${loyalty.config.REFERRAL_BONUS_NEW} punten!`, `Share your code and receive ${loyalty.config.REFERRAL_BONUS_REFERRER} points. Your friend gets ${loyalty.config.REFERRAL_BONUS_NEW} points!`)}
        </p>
        <div className="flex gap-2">
          <div className="flex-1 px-3 py-2.5 bg-surface rounded-xl text-sm font-mono font-bold tracking-wider">
            {loyalty.referralCode}
          </div>
          <button onClick={handleCopyReferral} className="px-4 py-2.5 border border-border rounded-xl text-sm font-medium hover:bg-muted transition-colors flex items-center gap-1.5">
            {copied ? <Check className="w-4 h-4 text-success" /> : <Copy className="w-4 h-4" />}
            {copied ? t('Gekopieerd', 'Copied') : t('Kopieer', 'Copy')}
          </button>
        </div>
      </div>

      {!loyalty.birthday && (
        <div className="bg-card border border-border/50 rounded-2xl p-5 shadow-card">
          <h3 className="font-bold text-sm mb-1 flex items-center gap-2">
            <Calendar className="w-4 h-4 text-primary" /> {t('Geboortedatum', 'Date of Birth')}
          </h3>
          <p className="text-xs text-muted-foreground mb-3">
            {t(`Voeg uw geboortedatum toe en ontvang ${loyalty.config.BIRTHDAY_BONUS} punten op uw verjaardag!`, `Add your date of birth and receive ${loyalty.config.BIRTHDAY_BONUS} points on your birthday!`)}
          </p>
          <div className="flex gap-2">
            <input type="date" value={birthdayInput} onChange={(e) => setBirthdayInput(e.target.value)}
              className="flex-1 px-3 py-2.5 border border-border/50 rounded-xl bg-background text-sm focus:ring-2 focus:ring-primary/20 outline-none" />
            <button onClick={handleSetBirthday} className="px-4 py-2.5 gradient-primary text-white font-bold rounded-xl text-sm">{t('Opslaan', 'Save')}</button>
          </div>
        </div>
      )}

      {loyalty.history && loyalty.history.length > 0 && (
        <div className="bg-card border border-border/50 rounded-2xl p-5 shadow-card">
          <h3 className="font-bold text-sm mb-3">{t('Puntenhistorie', 'Points History')}</h3>
          <div className="space-y-2">
            {loyalty.history.map((entry, i) => (
              <div key={i} className="flex items-center justify-between text-sm py-2 border-b border-border/30 last:border-0">
                <div className="flex items-center gap-2">
                  {entry.points > 0 ? (
                    <ArrowUpRight className="w-4 h-4 text-success" />
                  ) : (
                    <ArrowDownRight className="w-4 h-4 text-destructive" />
                  )}
                  <div>
                    <p className="text-xs">{entry.description}</p>
                    <p className="text-xs text-muted-foreground">{new Date(entry.date).toLocaleDateString(locale(lang))}</p>
                  </div>
                </div>
                <span className={`font-bold ${entry.points > 0 ? 'text-success' : 'text-destructive'}`}>
                  {entry.points > 0 ? '+' : ''}{entry.points}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default LoyaltyDashboard;
