import * as React from 'react';
import { useState, useEffect } from 'react';
import { motion } from 'motion/react';
import { Shield, Smartphone, ArrowRight, CheckCircle2, AlertCircle } from 'lucide-react';
import { Language, TranslationSet } from '../types';

interface MitIDModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (fullName: string) => void;
  t: TranslationSet;
}

export default function MitIDModal({ isOpen, onClose, onSuccess, t }: MitIDModalProps) {
  const [step, setStep] = useState<'username' | 'swipe' | 'success'>('username');
  const [username, setUsername] = useState('');
  const [errorString, setErrorString] = useState('');
  const [progress, setProgress] = useState(100);

  // Timer for the simulated swipe. It counts down 30 seconds for the notification to be swiped.
  useEffect(() => {
    if (step !== 'swipe') return;

    setProgress(100);
    const interval = setInterval(() => {
      setProgress((prev) => {
        if (prev <= 1) {
          clearInterval(interval);
          setStep('username');
          setErrorString('MitID session timed out. Please try again.');
          return 0;
        }
        return prev - 1;
      });
    }, 300);

    // Auto-approve after 3.5 seconds to keep it fluid, but also support instant user click
    const autoApproveTimer = setTimeout(() => {
      handleApprove();
    }, 3500);

    return () => {
      clearInterval(interval);
      clearTimeout(autoApproveTimer);
    };
  }, [step]);

  if (!isOpen) return null;

  const handleUsernameSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!username.trim()) {
      setErrorString(t.emailLabel ? 'User ID is required' : 'Bruger-ID er påkrævet');
      return;
    }
    setErrorString('');
    setStep('swipe');
  };

  const handleApprove = () => {
    setStep('success');
    setTimeout(() => {
      onSuccess(username.trim() || 'Danish License Holder');
    }, 1500);
  };

  return (
    <div id="mitid-overlay" className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-xs p-4">
      <motion.div
        id="mitid-modal-box"
        initial={{ opacity: 0, scale: 0.95, y: 10 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{ opacity: 0, scale: 0.95, y: 10 }}
        className="w-full max-w-md bg-[#ffffff] rounded-2xl shadow-2xl overflow-hidden border border-neutral-200 font-sans text-neutral-800"
      >
        {/* MitID Top Header Banner */}
        <div className="bg-[#002f6c] px-6 py-4 flex items-center justify-between text-white">
          <div className="flex items-center gap-2">
            {/* MitID-like logo layout */}
            <div className="h-7 w-7 rounded-md bg-white flex items-center justify-center text-[#002f6c] font-black tracking-tighter text-sm">
              Mit
            </div>
            <span className="font-bold tracking-tight text-lg">ID</span>
          </div>
          <button
            onClick={onClose}
            className="text-white/75 hover:text-white text-xs font-mono tracking-wider uppercase bg-white/10 hover:bg-white/20 px-3 py-1 rounded-sm transition-colors duration-150"
          >
            Annuller
          </button>
        </div>

        <div className="p-8">
          {step === 'username' && (
            <motion.div
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              className="space-y-6"
            >
              <div className="text-center">
                <div className="w-12 h-12 bg-[#002f6c]/5 rounded-full flex items-center justify-center mx-auto mb-4 border border-[#002f6c]/10">
                  <Shield className="w-6 h-6 text-[#002f6c]" />
                </div>
                <h3 className="text-xl font-bold text-neutral-900 tracking-tight">{t.mitIdTitle}</h3>
                <p className="text-sm text-neutral-500 mt-1.5 leading-relaxed">{t.mitIdSub}</p>
              </div>

              {errorString && (
                <div className="p-3 bg-red-50 border border-red-200 rounded-xl flex items-center gap-2.5 text-xs text-red-600">
                  <AlertCircle className="w-4 h-4 shrink-0" />
                  <span>{errorString}</span>
                </div>
              )}

              <form onSubmit={handleUsernameSubmit} className="space-y-4">
                <div className="space-y-2">
                  <label htmlFor="mitid-user" className="block text-xs font-semibold uppercase tracking-wider text-neutral-500 font-mono">
                    {t.mitIdUserLabel}
                  </label>
                  <input
                    id="mitid-user"
                    type="text"
                    required
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    placeholder={t.mitIdUserPlaceholder}
                    className="w-full bg-neutral-50 border border-neutral-300 focus:border-[#002f6c] rounded-xl px-4 py-3 text-sm font-medium outline-hidden transition-all duration-150"
                  />
                </div>

                <button
                  type="submit"
                  className="w-full bg-[#002f6c] hover:bg-[#00214a] text-white font-semibold py-3.5 px-4 rounded-xl flex items-center justify-center gap-2 transition-all duration-200 shadow-md group"
                >
                  <span>{t.mitIdBtnAuthenticate}</span>
                  <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                </button>
              </form>
            </motion.div>
          )}

          {step === 'swipe' && (
            <motion.div
              initial={{ opacity: 0, x: 10 }}
              animate={{ opacity: 1, x: 0 }}
              className="space-y-6 text-center"
            >
              <div className="relative w-16 h-16 mx-auto mb-4">
                {/* Pulsing ring animation */}
                <div className="absolute inset-0 rounded-full bg-[#002f6c]/10 animate-ping" />
                <div className="relative w-16 h-16 bg-[#002f6c]/5 rounded-full flex items-center justify-center border border-[#002f6c]/10">
                  <Smartphone className="w-8 h-8 text-[#002f6c] animate-bounce" />
                </div>
              </div>

              <div className="space-y-2">
                <h4 className="text-lg font-bold text-neutral-900 tracking-tight">{t.mitIdLoadingText}</h4>
                <p className="text-sm text-neutral-500 max-w-xs mx-auto leading-relaxed">
                  {t.mitIdStatusSwipe}
                </p>
                <div className="inline-block mt-1 px-3 py-1 rounded-full bg-slate-100 text-xs text-slate-600 font-medium">
                  {t.mitIdAppPrompt}
                </div>
              </div>

              {/* Progress timer bar */}
              <div className="w-full h-1 bg-neutral-100 rounded-full overflow-hidden">
                <div
                  className="h-full bg-[#002f6c] transition-all duration-300"
                  style={{ width: `${progress}%` }}
                />
              </div>

              <div className="pt-2">
                {/* Instant validation to bypass wait */}
                <button
                  onClick={handleApprove}
                  className="text-xs text-[#002f6c] hover:underline font-bold bg-[#002f6c]/5 hover:bg-[#002f6c]/10 px-4 py-2 rounded-full transition-all"
                >
                  🇩🇰 Send Instant Simulated Approved Event
                </button>
              </div>
            </motion.div>
          )}

          {step === 'success' && (
            <motion.div
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              className="space-y-4 text-center py-4"
            >
              <div className="w-16 h-16 bg-emerald-50 rounded-full flex items-center justify-center mx-auto mb-2 border border-emerald-100">
                <CheckCircle2 className="w-9 h-9 text-emerald-500" />
              </div>
              <h4 className="text-lg font-bold text-neutral-900 tracking-tight">
                {t.mitIdSuccessText}
              </h4>
              <p className="text-xs text-neutral-400 font-mono">
                Security session verified
              </p>
            </motion.div>
          )}
        </div>
      </motion.div>
    </div>
  );
}
