import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { Shield, Clock, MapPin, Loader, AlertTriangle, User, RotateCcw, QrCode, LogOut, LayoutDashboard } from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
import { visitorsApi, Visitor, VisitorLog } from '../lib/visitorsApi';

export default function BadgePage() {
    const { id } = useParams<{ id: string }>();
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [data, setData] = useState<{ visitor: Visitor; log: VisitorLog } | null>(null);
    const [currentTime, setCurrentTime] = useState(new Date());
    const [isFlipped, setIsFlipped] = useState(false);

    useEffect(() => {
        const timer = setInterval(() => setCurrentTime(new Date()), 1000);
        return () => clearInterval(timer);
    }, []);

    useEffect(() => {
        if (id) {
            loadBadgeData(id);
        }
    }, [id]);

    const loadBadgeData = async (visitId: string) => {
        try {
            const { visitors } = await visitorsApi.getActive();
            const match = visitors.find(v => v.logId === visitId);

            if (match) {
                const fullVisitor = await visitorsApi.getById(match.visitorId);
                const log = fullVisitor.logs.find(l => l.id === visitId);

                if (log) {
                    setData({ visitor: fullVisitor, log });
                } else {
                    setError('Badge not active or found');
                }
            } else {
                setError('Invalid or expired badge');
            }
        } catch (err) {
            console.error(err);
            setError('Failed to load badge');
        } finally {
            setLoading(false);
        }
    };

    if (loading) {
        return (
            <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center">
                <div className="text-center">
                    <Loader className="animate-spin text-[var(--color-primary)] mx-auto mb-4" size={48} />
                    <p className="text-[var(--color-text-tertiary)]">Loading badge...</p>
                </div>
            </div>
        );
    }

    if (error || !data) {
        return (
            <div className="min-h-screen bg-gradient-to-br from-slate-900 via-red-900/20 to-slate-900 flex flex-col items-center justify-center p-6 text-center">
                <div className="w-24 h-24 bg-red-500/20 rounded-full flex items-center justify-center mb-6 animate-pulse">
                    <AlertTriangle className="text-red-500" size={48} />
                </div>
                <h1 className="text-3xl font-bold text-white mb-2">Invalid Badge</h1>
                <p className="text-[var(--color-text-tertiary)] mb-4">This badge is no longer active or does not exist.</p>
                <div className="mt-4 p-4 bg-slate-800/50 rounded-lg text-sm text-[var(--color-text-tertiary)] font-mono">
                    Badge ID: {id}
                </div>
                <a
                    href="/kiosk"
                    className="mt-8 bg-slate-700 hover:bg-slate-600 text-white px-6 py-3 rounded-xl transition-colors"
                >
                    Return to Kiosk
                </a>
            </div>
        );
    }

    const { visitor, log } = data;
    const isValid = log.status === 'CHECKED_IN' && (!log.exitTime);
    const timeLeft = log.badgeExpiry ? new Date(log.badgeExpiry).getTime() - currentTime.getTime() : 0;
    const isExpired = log.badgeExpiry ? timeLeft < 0 : false;

    const entryTime = new Date(log.entryTime);
    const duration = Math.floor((currentTime.getTime() - entryTime.getTime()) / 60000);
    const hours = Math.floor(duration / 60);
    const minutes = duration % 60;

    return (
        <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex flex-col items-center justify-center p-4">
            {/* Site Branding */}
            <div className="mb-6 text-center">
                <div className="flex items-center justify-center gap-2 mb-2">
                    <Shield className="text-[var(--color-primary)]" size={28} />
                    <span className="text-xl font-bold text-white tracking-tight">Veridian</span>
                </div>
                <p className="text-[var(--color-text-tertiary)] text-sm">Facility Access Control</p>
            </div>

            {/* Flip Card Container */}
            <div
                className="relative w-full max-w-sm cursor-pointer"
                style={{ perspective: '1000px' }}
                onClick={() => setIsFlipped(!isFlipped)}
            >
                <div
                    className="relative w-full transition-transform duration-700"
                    style={{
                        transformStyle: 'preserve-3d',
                        transform: isFlipped ? 'rotateY(180deg)' : 'rotateY(0)'
                    }}
                >
                    {/* FRONT - Badge Info */}
                    <div
                        className={`w-full bg-white rounded-3xl overflow-hidden shadow-2xl ${!isValid || isExpired ? 'opacity-75' : ''}`}
                        style={{ backfaceVisibility: 'hidden' }}
                    >
                        {/* Status Header */}
                        <div className={`py-4 text-center text-white font-bold tracking-wider flex items-center justify-center gap-2 ${isValid && !isExpired ? 'bg-gradient-to-r from-emerald-600 to-emerald-500' : 'bg-gradient-to-r from-red-600 to-red-500'}`}>
                            {isValid && !isExpired ? (
                                <>
                                    <div className="w-3 h-3 bg-white rounded-full animate-pulse" />
                                    ACTIVE VISITOR
                                </>
                            ) : (
                                <>
                                    <AlertTriangle size={20} />
                                    {log.status === 'REVOKED' ? 'ACCESS REVOKED' : 'INVALID / EXPIRED'}
                                </>
                            )}
                        </div>

                        <div className="p-6 flex flex-col items-center">
                            {/* Photo */}
                            <div className="w-32 h-32 rounded-full border-4 border-emerald-100 shadow-lg overflow-hidden mb-4 bg-gradient-to-br from-slate-100 to-slate-200 flex items-center justify-center">
                                {visitor.photoUrl ? (
                                    <img src={visitor.photoUrl} alt={visitor.name} className="w-full h-full object-cover" />
                                ) : (
                                    <User size={56} className="text-[var(--color-text-tertiary)]" />
                                )}
                            </div>

                            {/* Name */}
                            <h1 className="text-2xl font-bold text-slate-900 text-center leading-tight mb-1">
                                {visitor.name}
                            </h1>

                            {/* Type Badge */}
                            <span className={`px-4 py-1 rounded-full text-xs font-bold uppercase tracking-wider mb-4 ${visitor.type === 'VISITOR' ? 'bg-blue-100 text-blue-700' :
                                visitor.type === 'CONTRACTOR' ? 'bg-amber-100 text-amber-700' :
                                    visitor.type === 'INSPECTOR' ? 'bg-red-100 text-red-700' :
                                        'bg-slate-100 text-slate-700'
                                }`}>
                                {visitor.type}
                            </span>

                            {/* Company */}
                            {visitor.company && (
                                <p className="text-slate-600 font-medium mb-4">{visitor.company}</p>
                            )}

                            {/* Info Grid */}
                            <div className="w-full grid grid-cols-2 gap-3 border-t border-slate-100 pt-4">
                                <div className="bg-slate-50 rounded-xl p-3 text-center">
                                    <p className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-bold mb-1">Badge</p>
                                    <p className="text-sm font-mono font-bold text-[var(--color-primary)]">{log.badgeNumber}</p>
                                </div>
                                <div className="bg-slate-50 rounded-xl p-3 text-center">
                                    <p className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-bold mb-1">Duration</p>
                                    <p className="text-sm font-bold text-slate-700">
                                        {hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`}
                                    </p>
                                </div>
                            </div>

                            {/* Escort Notice */}
                            {log.escort && (
                                <div className="w-full mt-4 bg-amber-50 rounded-xl p-3 border border-amber-200 text-center">
                                    <p className="text-[10px] text-amber-600 uppercase tracking-wider font-bold mb-1">Escort Required</p>
                                    <div className="flex items-center justify-center gap-2 text-amber-800 font-semibold text-sm">
                                        <User size={14} />
                                        {log.escort.name}
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Footer */}
                        <div className="bg-slate-50 px-4 py-3 border-t border-slate-100 flex items-center justify-between">
                            <div className="flex items-center gap-2 text-[var(--color-text-tertiary)] text-sm">
                                <Clock size={14} />
                                {currentTime.toLocaleTimeString()}
                            </div>
                            <div className="flex items-center gap-1 text-[var(--color-primary)] text-xs font-medium">
                                <RotateCcw size={12} />
                                Tap to flip
                            </div>
                        </div>
                    </div>

                    {/* BACK - QR Code for Security/Checkout */}
                    <div
                        className="absolute top-0 left-0 w-full bg-gradient-to-br from-slate-800 to-slate-900 rounded-3xl overflow-hidden shadow-2xl"
                        style={{
                            backfaceVisibility: 'hidden',
                            transform: 'rotateY(180deg)'
                        }}
                    >
                        {/* Header */}
                        <div className="py-4 bg-gradient-to-r from-blue-600 to-blue-500 text-center text-white font-bold tracking-wider flex items-center justify-center gap-2">
                            <QrCode size={20} />
                            SECURITY SCAN
                        </div>

                        <div className="p-8 flex flex-col items-center">
                            {/* QR Code */}
                            <div className="bg-white p-4 rounded-2xl shadow-lg mb-6">
                                <QRCodeSVG
                                    value={`${window.location.origin}/badges/${id}`}
                                    size={200}
                                    level="H"
                                    includeMargin={false}
                                />
                            </div>

                            <p className="text-white font-bold text-lg mb-2">Scan to Verify</p>
                            <p className="text-[var(--color-text-tertiary)] text-sm text-center mb-6">
                                Security personnel can scan this code to verify badge status or check out visitor.
                            </p>

                            {/* Badge Reference */}
                            <div className="bg-slate-800 rounded-xl px-6 py-3 border border-slate-700">
                                <p className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider text-center mb-1">Badge ID</p>
                                <p className="text-lg font-mono font-bold text-emerald-400 text-center">{log.badgeNumber}</p>
                            </div>

                            {/* Checkout Button */}
                            <button
                                onClick={(e) => {
                                    e.stopPropagation();
                                    window.location.href = '/kiosk';
                                }}
                                className="mt-6 w-full bg-red-600 hover:bg-red-700 text-white font-bold py-4 rounded-xl flex items-center justify-center gap-2 transition-colors"
                            >
                                <LogOut size={20} />
                                Sign Out at Kiosk
                            </button>
                        </div>

                        {/* Footer */}
                        <div className="bg-slate-800/50 px-4 py-3 border-t border-slate-700 flex items-center justify-center">
                            <div className="flex items-center gap-1 text-[var(--color-text-tertiary)] text-xs font-medium">
                                <RotateCcw size={12} />
                                Tap to flip back
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Bottom Navigation */}
            <div className="mt-8 flex flex-col items-center gap-3">
                <Link
                    to="/"
                    className="flex items-center gap-2 text-[var(--color-text-tertiary)] hover:text-emerald-400 text-sm transition-colors px-4 py-2 rounded-lg hover:bg-white/5"
                >
                    <LayoutDashboard size={16} />
                    <span>Dashboard</span>
                </Link>
                <p className="text-slate-600 text-xs text-center">
                    Digital Badge powered by Veridian Cultivation Platform
                </p>
            </div>
        </div>
    );
}
