import { useRef, useState, ReactNode } from "react";
import { Link } from "react-router-dom";
import {
    CheckCircle,
    User,
    Mail,
    FileText,
    Camera,
    ArrowRight,
    ArrowLeft,
    Building,
    Phone,
    Shield,
    Trash2,
    Loader2,
    AlertTriangle,
    ChevronDown
} from "lucide-react";
import { visitorsApi } from "@/lib/visitorsApi";

const commonStyles = {
    inputWrapper:
        "relative group flex items-center w-full rounded-full overflow-hidden shadow-sm transition-all duration-300",
    input:
        "w-full py-3.5 pl-12 pr-4 text-sm text-slate-900 placeholder-transparent bg-white/70 backdrop-blur-md border border-slate-200 rounded-full focus:outline-none focus:border-cyan-500 focus:ring-2 focus:ring-cyan-500 peer transition-all duration-300 disabled:opacity-50",
    inputIcon:
        "absolute left-4 text-[var(--color-text-tertiary)] peer-focus:text-cyan-500 transition-colors w-5 h-5",
    label:
        "absolute left-12 text-[var(--color-text-tertiary)] text-sm transition-all duration-200 peer-placeholder-shown:top-3.5 peer-placeholder-shown:text-[var(--color-text-tertiary)] peer-placeholder-shown:text-base peer-focus:top-1.5 peer-focus:text-xs peer-focus:text-cyan-600",
    button:
        "w-full py-3.5 px-6 font-semibold rounded-full bg-gradient-to-r from-cyan-600 to-blue-600 text-white shadow-lg hover:opacity-90 hover:shadow-cyan-500/30 transition-all duration-300 flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",
    link: "font-medium text-cyan-600 hover:text-cyan-700 transition-colors hover:underline",
};

interface VisitorKioskShellProps {
    children: ReactNode;
    onBack?: () => void;
    title?: ReactNode;
    subtitle?: string;
}

export const VisitorKioskShell = ({ children, onBack, title, subtitle }: VisitorKioskShellProps) => {
    return (
        <section className="relative bg-white min-h-screen">
            <div className="grid grid-cols-1 lg:grid-cols-2 min-h-screen">
                {/* Left Hero Section - Fixed/Sticky on Desktop */}
                <div className="relative flex items-end px-6 pb-16 pt-20 lg:pt-60 lg:pb-24 bg-slate-900 lg:sticky lg:top-0 lg:h-screen overflow-hidden">
                    <img
                        src="https://images.unsplash.com/photo-1565553642973-6afe791aee33?q=80&w=2623&auto=format&fit=crop"
                        alt="Modern Facility Hallway"
                        className="absolute inset-0 w-full h-full object-cover opacity-40 mix-blend-overlay"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-900/80 to-transparent" />

                    <div className="relative z-10 max-w-lg">
                        {onBack && (
                            <button
                                onClick={onBack}
                                className="absolute -top-40 left-0 lg:hidden text-white/50 hover:text-white flex items-center gap-2 mb-4"
                            >
                                <ArrowLeft size={18} /> Back
                            </button>
                        )}

                        <div className="flex items-center gap-2 mb-6">
                            <span className="badge badge-accent bg-cyan-500/10 text-cyan-400 border-cyan-500/20 shadow-[0_0_15px_rgba(6,182,212,0.3)]">SECURE FACILITY</span>
                        </div>
                        <h3 className="text-4xl sm:text-5xl font-bold text-white drop-shadow-2xl leading-tight">
                            Welcome to <br />
                            <span className="text-transparent bg-clip-text bg-gradient-to-r from-cyan-400 to-blue-500 animate-pulse-slow">
                                Veridian
                            </span>
                        </h3>
                        <p className="mt-4 text-lg text-slate-300 leading-relaxed">
                            Please complete the check-in process to receive your digital visitor badge and safety clearance.
                        </p>
                        <ul className="mt-10 grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-5">
                            {[
                                "Digital NDA Signature",
                                "Safety Briefing",
                                "Instant Badge Issuance",
                                "Escort Assignment",
                            ].map((item, i) => (
                                <li
                                    key={i}
                                    className="flex items-center gap-3 text-slate-200 text-lg font-medium"
                                >
                                    <CheckCircle className="text-cyan-500 w-5 h-5 flex-shrink-0" />
                                    {item}
                                </li>
                            ))}
                        </ul>
                    </div>
                </div>

                {/* Right Content Section - Scrollable */}
                <div className="flex items-center justify-center px-6 py-16 lg:py-24 bg-gradient-to-br from-white via-slate-50 to-white relative">
                    {onBack && (
                        <button
                            onClick={onBack}
                            className="absolute top-8 left-8 hidden lg:flex items-center gap-2 text-[var(--color-text-tertiary)] hover:text-slate-600 transition-colors"
                        >
                            <ArrowLeft size={20} /> Back
                        </button>
                    )}

                    <div className="w-full max-w-md bg-white/80 backdrop-blur-xl shadow-2xl rounded-3xl p-8 lg:p-10 border border-white/50 ring-1 ring-slate-100">
                        {(title || subtitle) && (
                            <div className="mb-8">
                                {title && <h2 className="text-3xl font-bold text-slate-900 sm:text-4xl tracking-tight">{title}</h2>}
                                {subtitle && <p className="mt-2 text-sm text-slate-600">{subtitle}</p>}
                            </div>
                        )}
                        {children}
                    </div>
                </div>
            </div>
        </section>
    );
};

interface VisitorCheckInProps {
    onBack: () => void;
    onSuccess: (data: { badgeNumber: string; visitId: string; message: string }) => void;
}

const VisitorCheckIn = ({ onBack, onSuccess }: VisitorCheckInProps) => {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [formData, setFormData] = useState({
        name: '',
        company: '',
        email: '',
        phone: '',
        purpose: '',
        type: 'VISITOR' as const,
        ndaAccepted: false
    });

    // Camera State
    const [capturedPhoto, setCapturedPhoto] = useState<string | null>(null);
    const [showCamera, setShowCamera] = useState(false);
    const videoRef = useRef<HTMLVideoElement>(null);
    const streamRef = useRef<MediaStream | null>(null);

    const startCamera = async () => {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({
                video: { facingMode: 'user', width: 640, height: 480 }
            });
            streamRef.current = stream;
            if (videoRef.current) {
                videoRef.current.srcObject = stream;
            }
            setShowCamera(true);
            setError(null);
        } catch (err) {
            console.error('Camera access denied:', err);
            setError('Camera access denied. Please allow camera permissions.');
        }
    };

    const capturePhoto = () => {
        if (videoRef.current) {
            const canvas = document.createElement('canvas');
            canvas.width = videoRef.current.videoWidth;
            canvas.height = videoRef.current.videoHeight;
            const ctx = canvas.getContext('2d');
            if (ctx) {
                ctx.drawImage(videoRef.current, 0, 0);
                const photoDataUrl = canvas.toDataURL('image/jpeg', 0.8);
                setCapturedPhoto(photoDataUrl);
                stopCamera();
            }
        }
    };

    const stopCamera = () => {
        if (streamRef.current) {
            streamRef.current.getTracks().forEach(track => track.stop());
            streamRef.current = null;
        }
        setShowCamera(false);
    };

    const retakePhoto = () => {
        setCapturedPhoto(null);
        startCamera();
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError(null);
        setLoading(true);

        try {
            // Validate required fields
            if (!formData.name || !formData.purpose) {
                throw new Error("Name and Purpose are required.");
            }
            if (!formData.ndaAccepted) {
                throw new Error("You must accept the NDA to check in.");
            }

            // 1. Create Visitor
            const visitorData: any = {
                name: formData.name,
                purpose: formData.purpose,
                type: formData.type,
                company: formData.company || undefined,
                email: formData.email || undefined,
                phone: formData.phone || undefined,
                photoUrl: capturedPhoto || undefined,
                ndaAccepted: formData.ndaAccepted
            };

            // Remove empty strings
            Object.keys(visitorData).forEach(key =>
                (visitorData[key] === undefined || visitorData[key] === '') && delete visitorData[key]
            );

            const visitor = await visitorsApi.create(visitorData);

            // 2. Check In
            const result = await visitorsApi.checkIn(visitor.id, {
                ndaAccepted: formData.ndaAccepted
            });

            onSuccess({
                badgeNumber: result.badgeNumber,
                visitId: result.visitId,
                message: `Welcome, ${visitor.name}!`
            });

        } catch (err: any) {
            console.error(err);
            setError(err.response?.data?.error || err.message || 'Failed to check in');
        } finally {
            setLoading(false);
        }
    };

    return (
        <VisitorKioskShell
            onBack={onBack}
            title={
                <>
                    Visitor <span className="text-cyan-600">Check-In</span>
                </>
            }
            subtitle="Create your visitor profile for today."
        >
            {error && (
                <div className="mb-6 bg-red-50 text-red-600 px-4 py-3 rounded-xl text-sm flex items-start gap-3 border border-red-100">
                    <AlertTriangle className="w-5 h-5 flex-shrink-0 mt-0.5" />
                    <span>{error}</span>
                </div>
            )}

            {/* Form */}
            <form className="space-y-5" onSubmit={handleSubmit}>
                {/* Name */}
                <div className={commonStyles.inputWrapper}>
                    <User className={commonStyles.inputIcon} />
                    <input
                        type="text"
                        placeholder="Full Name *"
                        className={`${commonStyles.input} peer`}
                        id="fullname"
                        value={formData.name}
                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                        required
                        disabled={loading}
                    />
                    <label htmlFor="fullname" className={commonStyles.label}>
                        Full Name
                    </label>
                </div>

                {/* Company */}
                <div className={commonStyles.inputWrapper}>
                    <Building className={commonStyles.inputIcon} />
                    <input
                        type="text"
                        placeholder="Company / Organization"
                        className={`${commonStyles.input} peer`}
                        id="company"
                        value={formData.company}
                        onChange={(e) => setFormData({ ...formData, company: e.target.value })}
                        disabled={loading}
                    />
                    <label htmlFor="company" className={commonStyles.label}>
                        Company
                    </label>
                </div>

                <div className="grid grid-cols-2 gap-4">
                    {/* Email */}
                    <div className={commonStyles.inputWrapper}>
                        <Mail className={commonStyles.inputIcon} />
                        <input
                            type="email"
                            placeholder="Email"
                            className={`${commonStyles.input} peer`}
                            id="email"
                            value={formData.email}
                            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                            disabled={loading}
                        />
                        <label htmlFor="email" className={commonStyles.label}>
                            Email
                        </label>
                    </div>
                    {/* Phone */}
                    <div className={commonStyles.inputWrapper}>
                        <Phone className={commonStyles.inputIcon} />
                        <input
                            type="tel"
                            placeholder="Phone"
                            className={`${commonStyles.input} peer`}
                            id="phone"
                            value={formData.phone}
                            onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                            disabled={loading}
                        />
                        <label htmlFor="phone" className={commonStyles.label}>
                            Phone
                        </label>
                    </div>
                </div>

                {/* Purpose */}
                <div className={commonStyles.inputWrapper}>
                    <FileText className={commonStyles.inputIcon} />
                    <input
                        type="text"
                        placeholder="Purpose of Visit *"
                        className={`${commonStyles.input} peer`}
                        id="purpose"
                        value={formData.purpose}
                        onChange={(e) => setFormData({ ...formData, purpose: e.target.value })}
                        required
                        disabled={loading}
                    />
                    <label htmlFor="purpose" className={commonStyles.label}>
                        Purpose of Visit
                    </label>
                </div>

                {/* Visitor Type Selector */}
                <div className={commonStyles.inputWrapper}>
                    <Shield className={commonStyles.inputIcon} />
                    <div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-[var(--color-text-tertiary)]">
                        <ChevronDown size={16} />
                    </div>
                    <select
                        className={`${commonStyles.input} pt-6 pb-2 peer appearance-none`}
                        value={formData.type}
                        onChange={(e) => setFormData({ ...formData, type: e.target.value as any })}
                        disabled={loading}
                    >
                        <option value="VISITOR">Standard Visitor</option>
                        <option value="CONTRACTOR">Contractor</option>
                        <option value="INSPECTOR">Inspector</option>
                        <option value="VENDOR">Vendor</option>
                        <option value="DELIVERY">Delivery</option>
                    </select>
                    <label className="absolute left-12 top-1.5 text-xs text-[var(--color-text-tertiary)] font-medium transition-all duration-200">
                        Visit Type
                    </label>
                </div>

                {/* Photo Capture */}
                <div className="relative group rounded-3xl overflow-hidden shadow-inner bg-slate-50 border border-slate-200 hover:border-cyan-400/50 transition-colors">
                    {!showCamera && !capturedPhoto && (
                        <button
                            type="button"
                            onClick={startCamera}
                            className="w-full h-32 flex flex-col items-center justify-center gap-2 text-[var(--color-text-tertiary)] hover:text-cyan-600 transition-colors"
                            disabled={loading}
                        >
                            <Camera className="w-8 h-8 opacity-50 group-hover:opacity-100" />
                            <span className="text-sm font-medium">Take Security Photo (Optional)</span>
                        </button>
                    )}

                    {showCamera && (
                        <div className="relative aspect-[4/3] bg-black">
                            <video
                                ref={videoRef}
                                autoPlay
                                playsInline
                                muted
                                className="w-full h-full object-cover"
                            />
                            <div className="absolute bottom-4 left-0 right-0 flex justify-center gap-4 px-4">
                                <button
                                    type="button"
                                    onClick={stopCamera}
                                    className="px-4 py-2 bg-slate-800/80 text-white rounded-full text-sm hover:bg-slate-700 backdrop-blur-md"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="button"
                                    onClick={capturePhoto}
                                    className="px-6 py-2 bg-cyan-500 text-white rounded-full text-sm font-bold shadow-lg shadow-cyan-500/30 hover:bg-cyan-400"
                                >
                                    Capture
                                </button>
                            </div>
                        </div>
                    )}

                    {capturedPhoto && (
                        <div className="relative aspect-[4/3] bg-black group">
                            <img
                                src={capturedPhoto}
                                alt="Captured"
                                className="w-full h-full object-cover opacity-90"
                            />
                            <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity">
                                <button
                                    type="button"
                                    onClick={retakePhoto}
                                    className="px-4 py-2 bg-red-500/90 text-white rounded-full text-sm font-medium flex items-center gap-2 hover:bg-red-500"
                                >
                                    <Trash2 size={16} /> Retake
                                </button>
                            </div>
                            <div className="absolute top-2 right-2">
                                <span className="bg-[var(--color-primary)] text-white text-xs px-2 py-1 rounded-full flex items-center gap-1 shadow-sm">
                                    <CheckCircle size={10} /> Photo Ready
                                </span>
                            </div>
                        </div>
                    )}
                </div>

                {/* NDA Checkbox */}
                <label className="flex items-start gap-3 p-4 bg-slate-50 rounded-2xl cursor-pointer hover:bg-slate-100 transition-colors border border-transparent hover:border-slate-200">
                    <div className={`mt-0.5 w-5 h-5 rounded-full border flex items-center justify-center transition-all ${formData.ndaAccepted ? 'bg-cyan-500 border-cyan-500 text-white' : 'bg-white border-slate-300'}`}>
                        {formData.ndaAccepted && <CheckCircle size={14} />}
                    </div>
                    <input
                        type="checkbox"
                        checked={formData.ndaAccepted}
                        onChange={e => setFormData({ ...formData, ndaAccepted: e.target.checked })}
                        className="sr-only"
                        disabled={loading}
                    />
                    <div className="text-sm">
                        <span className="text-slate-700 font-medium">Agreement Required</span>
                        <p className="text-[var(--color-text-tertiary)] text-xs mt-0.5">I agree to the Veridian Non-Disclosure Agreement and safety policies.</p>
                    </div>
                </label>

                <button
                    type="submit"
                    disabled={loading}
                    className={commonStyles.button}
                >
                    {loading ? (
                        <>
                            <Loader2 className="animate-spin" size={20} /> Processing...
                        </>
                    ) : (
                        <>
                            Start Check-In <ArrowRight size={18} />
                        </>
                    )}
                </button>
            </form>
        </VisitorKioskShell>
    );
};

export default VisitorCheckIn;
