import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Copy, Clock, Plus, Crown, RefreshCw, Sparkles } from "lucide-react";
import { useTimer } from "@/hooks/use-timer";
import { useLanguage } from "@/contexts/LanguageContext";
import { useEffect, useRef, useState } from "react";
import { QRCodeGenerator } from "./qr-code-generator";

interface EmailDisplayProps {
  email: string;
  onCopy: () => void;
  onExtend: () => void;
  onExpired: () => void;
  onRefresh?: () => void;
  onGenerateNew?: () => void;
  expiresAt?: Date;
  isPremium?: boolean;
}

export function EmailDisplay({ email, onCopy, onExtend, onExpired, onRefresh, onGenerateNew, expiresAt, isPremium = false }: EmailDisplayProps) {
  const initialTime = expiresAt ? Math.max(0, Math.floor((expiresAt.getTime() - Date.now()) / 1000)) : (isPremium ? 86400 : 600); // 24 hours for premium, 10 minutes for free
  const { formattedTime, isExpired, extendTime, resetTimer } = useTimer(initialTime);
  const { t } = useLanguage();

  const hasExpired = useRef(false);
  const lastEmailRef = useRef(email);
  const [showCelebration, setShowCelebration] = useState(false);

  // Reset timer when email changes (new email generated)
  useEffect(() => {
    if (email !== lastEmailRef.current && email) {
      const newTime = expiresAt ? Math.max(0, Math.floor((expiresAt.getTime() - Date.now()) / 1000)) : (isPremium ? 86400 : 600);
      resetTimer(newTime);
      hasExpired.current = false;
      lastEmailRef.current = email;
      // Trigger celebration animation
      setShowCelebration(true);
      const timer = setTimeout(() => setShowCelebration(false), 2000);
      return () => clearTimeout(timer);
    }
  }, [email, expiresAt, isPremium, resetTimer]);



  useEffect(() => {
    if (isExpired && !hasExpired.current) {
      hasExpired.current = true;
      // Add a small delay to ensure the UI updates before regeneration
      setTimeout(() => {
        onExpired();
      }, 1000);
    }
    if (!isExpired) {
      hasExpired.current = false;
    }
  }, [isExpired, onExpired]);

  const handleExtend = () => {
    extendTime(300); // Add 5 minutes
    onExtend();
  };

  return (
    <div className="relative">
      {/* Premium glow effect */}
      {isPremium && (
        <div className="absolute inset-0 bg-gradient-to-r from-yellow-400/20 to-amber-400/20 rounded-2xl blur-xl" />
      )}
      
      <Card className="relative shadow-xl border-0 bg-gradient-to-br from-white to-slate-50/80 backdrop-blur-sm">
        <CardContent className="p-4 sm:p-6 lg:p-8">
          <div className="text-center">
            {/* Header with premium badge */}
            <div className="flex items-center justify-center mb-4 sm:mb-6 relative">
              <div className="text-center flex-1">
                <h2 className="text-lg sm:text-xl lg:text-2xl font-semibold text-slate-700 mb-1">{t.yourTempEmail}</h2>
                <p className="text-sm sm:text-base text-slate-500">{t.clickToCopy}</p>
              </div>
              {isPremium && (
                <div className="absolute top-0 right-0 sm:relative sm:ml-4">
                  <Badge className="bg-gradient-to-r from-yellow-400 to-amber-500 text-yellow-900 border-0 shadow-lg">
                    <Crown className="h-3 w-3 mr-1" />
                    <span className="hidden sm:inline">{t.premium}</span>
                  </Badge>
                </div>
              )}
            </div>

            {/* How it works - only show if no email yet */}
            {!email && (
              <div className="mb-6 p-4 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl border border-blue-200">
                <h3 className="text-lg font-semibold text-blue-900 mb-3 text-center">📧 How TempMail Works</h3>
                <div className="space-y-2 text-sm text-blue-800">
                  <div className="flex items-center">
                    <span className="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-xs font-bold mr-3">1</span>
                    <span>Click "Generate New Email" button below</span>
                  </div>
                  <div className="flex items-center">
                    <span className="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-xs font-bold mr-3">2</span>
                    <span>We create a random temporary email (like abc123@maildrop.cc)</span>
                  </div>
                  <div className="flex items-center">
                    <span className="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-xs font-bold mr-3">3</span>
                    <span>Copy it and use on any website</span>
                  </div>
                  <div className="flex items-center">
                    <span className="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-xs font-bold mr-3">4</span>
                    <span>Check inbox below to see received emails</span>
                  </div>
                </div>
              </div>
            )}

            {/* Email display area */}
            <div className="relative mb-6">
              {/* Celebration overlay */}
              {showCelebration && (
                <div className="absolute inset-0 z-20 flex items-center justify-center pointer-events-none">
                  <div className="absolute top-2 left-1/4 animate-bounce" style={{ animationDuration: '0.6s' }}>
                    <Sparkles className="h-6 w-6 text-yellow-400" />
                  </div>
                  <div className="absolute top-4 right-1/4 animate-bounce" style={{ animationDuration: '0.8s', animationDelay: '0.1s' }}>
                    <Sparkles className="h-5 w-5 text-purple-400" />
                  </div>
                  <div className="absolute bottom-6 left-1/3 animate-bounce" style={{ animationDuration: '0.7s', animationDelay: '0.2s' }}>
                    <Sparkles className="h-4 w-4 text-pink-400" />
                  </div>
                  <div className="absolute bottom-4 right-1/3 animate-bounce" style={{ animationDuration: '0.9s', animationDelay: '0.15s' }}>
                    <Sparkles className="h-5 w-5 text-blue-400" />
                  </div>
                </div>
              )}
              <div className={`bg-gradient-to-br from-slate-50 to-white rounded-xl p-4 sm:p-6 border-2 ${showCelebration ? 'border-yellow-300 shadow-yellow-100' : 'border-slate-100'} shadow-inner transition-all duration-500`}>
                <div className="flex flex-col gap-4">
                  <div className="w-full min-w-0 text-center overflow-hidden">
                    <span className="text-base sm:text-xl md:text-2xl lg:text-3xl font-bold text-slate-800 font-mono leading-relaxed block px-2 whitespace-nowrap overflow-x-auto">
                      {email || (
                        <span className="text-slate-400 animate-pulse">
                          {t.generatingEmail}
                        </span>
                      )}
                    </span>
                  </div>
                  <div className="flex flex-col sm:flex-row gap-3 items-center justify-center">
                    {email ? (
                      <Button
                        onClick={onCopy}
                        className="bg-gradient-to-r from-emerald-500 to-emerald-600 hover:from-emerald-600 hover:to-emerald-700 text-white px-6 py-3 rounded-xl shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-200 text-sm sm:text-base mobile-button touch-target"
                      >
                        <Copy className="h-4 w-4 sm:h-5 sm:w-5" />
                        <span className="ml-2">{t.copyEmail}</span>
                      </Button>
                    ) : (
                      <Button
                        onClick={onGenerateNew}
                        className="bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white px-8 py-4 rounded-xl shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-200 text-lg font-semibold mobile-button touch-target"
                        disabled={!onGenerateNew}
                      >
                        <Plus className="h-5 w-5 mr-2" />
                        Generate New Email
                      </Button>
                    )}
                    
                    <div className="flex gap-2">
                      <QRCodeGenerator email={email} />
                      {onRefresh && (
                        <Button
                          onClick={onRefresh}
                          variant="outline"
                          size="sm"
                          className="bg-white/90 hover:bg-gray-50 border-gray-200 text-gray-700 hover:text-gray-900"
                        >
                          <RefreshCw className="h-4 w-4 mr-2" />
                          {t.refresh}
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            {/* Timer and Extend button for non-premium users */}
            {!isPremium && (
              <div className="mt-6 space-y-4">
                {/* Main Timer Display */}
                <div className="flex flex-col items-center">
                  <div className="flex items-center justify-center px-4 sm:px-6 py-3 sm:py-4 bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-2xl shadow-xl min-w-0">
                    <Clock className="h-5 w-5 sm:h-6 sm:w-6 mr-2 sm:mr-3 flex-shrink-0" />
                    <span className="text-2xl sm:text-3xl md:text-4xl lg:text-5xl font-mono font-bold tracking-wider text-center min-w-0">{formattedTime}</span>
                  </div>
                  <p className="text-sm sm:text-base text-slate-500 mt-2 text-center">
                    {isExpired ? "Email expired" : t.autoExpires}
                  </p>
                </div>

                {/* Extend Button */}
                <div className="flex justify-center">
                  <Button
                    onClick={handleExtend}
                    className="bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white px-6 sm:px-8 py-3 sm:py-4 rounded-xl font-semibold shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none"
                    disabled={isExpired}
                  >
                    <Plus className="h-5 w-5 mr-2" />
                    <span className="text-base sm:text-lg">{t.extendTime}</span>
                  </Button>
                </div>
              </div>
            )}

            {/* Timer for premium users */}
            {isPremium && (
              <div className="mt-6">
                <div className="flex flex-col items-center">
                  <div className="flex items-center justify-center px-4 sm:px-6 py-3 sm:py-4 bg-gradient-to-r from-yellow-500 to-amber-500 text-white rounded-2xl shadow-xl min-w-0">
                    <Crown className="h-5 w-5 sm:h-6 sm:w-6 mr-2 sm:mr-3 flex-shrink-0" />
                    <span className="text-2xl sm:text-3xl md:text-4xl lg:text-5xl font-mono font-bold tracking-wider text-center min-w-0">{formattedTime}</span>
                  </div>
                  <p className="text-sm sm:text-base text-slate-500 mt-2 text-center">
                    {t.duration24h} • {t.premium} Active
                  </p>
                </div>
              </div>
            )}

            {/* Status indicator */}
            <div className="mt-4 sm:mt-6">
              <div className="flex items-center justify-center gap-2 text-xs text-slate-500">
                <div className={`w-2 h-2 rounded-full ${email ? 'bg-green-400 animate-pulse' : 'bg-slate-300'}`} />
                {email ? t.emailReady : t.settingUpEmail}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
