import { useState, useEffect } from 'react';
import {
    Users, UserPlus, LogIn, LogOut, Building, Search,
    Filter, Download, Calendar, Shield, AlertTriangle, X
} from 'lucide-react';

import { visitorsApi, Visitor, VisitorLog, ActiveVisitor, AccessZone } from '../lib/visitorsApi';
import { PageHeader, MetricCard, EmptyState, CardSkeleton } from '../components/ui/LinearPrimitives';
import { useToast } from '../context/ToastContext';

type TabType = 'active' | 'all' | 'zones' | 'reports';

export default function VisitorManagementPage() {
    const { addToast } = useToast();
    const [activeTab, setActiveTab] = useState<TabType>('active');
    const [activeVisitors, setActiveVisitors] = useState<ActiveVisitor[]>([]);
    const [allVisitors, setAllVisitors] = useState<(Visitor & { logs: VisitorLog[] })[]>([]);
    const [zones, setZones] = useState<AccessZone[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState('');
    const [revokeModal, setRevokeModal] = useState<{ visitor: ActiveVisitor, notes: string } | null>(null);

    useEffect(() => {
        loadData();
    }, [activeTab]);

    const loadData = async () => {
        setLoading(true);
        try {
            if (activeTab === 'active') {
                const { visitors } = await visitorsApi.getActive();
                setActiveVisitors(visitors);
            } else if (activeTab === 'all') {
                const { visitors } = await visitorsApi.getAll({ search: searchQuery || undefined });
                setAllVisitors(visitors);
            } else if (activeTab === 'zones') {
                const zonesData = await visitorsApi.getZones();
                setZones(zonesData);
            }
        } catch (error) {
            console.error('Failed to load data:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleCheckOut = async (visitor: ActiveVisitor) => {
        try {
            await visitorsApi.checkOut(visitor.visitorId);
            addToast(`${visitor.name} checked out`, 'success');
            loadData();
        } catch (error) {
            addToast('Failed to check out', 'error');
        }
    };

    const formatDuration = (entryTime: string) => {
        const minutes = Math.floor((Date.now() - new Date(entryTime).getTime()) / 60000);
        if (minutes < 60) return `${minutes}m`;
        const hours = Math.floor(minutes / 60);
        return `${hours}h ${minutes % 60}m`;
    };

    const handleRevoke = async () => {
        if (!revokeModal) return;
        try {
            await visitorsApi.revoke(revokeModal.visitor.visitorId, revokeModal.notes);
            setRevokeModal(null);
            addToast('Access revoked', 'warning');
            loadData();
        } catch (error) {
            addToast('Failed to revoke access', 'error');
        }
    };

    const getTypeBadge = (type: string) => {
        const badges: Record<string, string> = {
            VISITOR: 'badge-accent',
            CONTRACTOR: 'badge-warning',
            INSPECTOR: 'badge-destructive',
            VENDOR: 'badge-accent',
            DELIVERY: 'badge-success',
            OTHER: 'badge'
        };
        return badges[type] || 'badge';
    };

    return (
        <div className="space-y-6 animate-in">
            <PageHeader
                title="Visitor Management"
                subtitle="Real-time facility access monitoring"
                actions={
                    <a
                        href="/kiosk"
                        target="_blank"
                        className="btn btn-primary"
                    >
                        <UserPlus size={16} />
                        <span className="hidden sm:inline">Open Kiosk</span>
                    </a>
                }
            />

            {/* Stats */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                <MetricCard icon={Users} label="On-Site Now" value={activeVisitors.length} accent="success" />
                <MetricCard icon={LogIn} label="Today's Visits" value="--" accent="accent" />
                <MetricCard icon={Building} label="Zones Active" value={zones.length} accent="accent" />
                <MetricCard icon={AlertTriangle} label="Alerts" value="0" accent="warning" />
            </div>

            {/* Tabs */}
            <div className="card p-1 inline-flex gap-1">
                {(['active', 'all', 'zones', 'reports'] as TabType[]).map(tab => (
                    <button
                        key={tab}
                        onClick={() => setActiveTab(tab)}
                        className={`
                            px-4 py-2 rounded-md text-sm font-medium transition-colors duration-fast capitalize
                            ${activeTab === tab
                                ? 'bg-accent text-white'
                                : 'text-secondary hover:text-primary hover:bg-tertiary'
                            }
                        `}
                    >
                        {tab === 'active' ? 'Live View' : tab}
                    </button>
                ))}
            </div>

            {/* Active Visitors Tab */}
            {activeTab === 'active' && (
                <div className="card overflow-hidden">
                    {loading ? (
                        <div className="p-4 space-y-2">
                            {Array.from({ length: 3 }).map((_, i) => <CardSkeleton key={i} />)}
                        </div>
                    ) : activeVisitors.length === 0 ? (
                        <EmptyState
                            icon={Users}
                            title="No visitors on-site"
                            description="Visitors will appear here when they check in."
                        />
                    ) : (
                        <div className="divide-y divide-subtle">
                            {activeVisitors.map(visitor => (
                                <div key={visitor.logId} className="p-4 flex items-center justify-between hover:bg-tertiary transition-colors duration-fast">
                                    <div className="flex items-center gap-3">
                                        <div className="w-9 h-9 bg-accent-muted rounded-full flex items-center justify-center text-accent font-semibold text-sm">
                                            {visitor.name.charAt(0)}
                                        </div>
                                        <div>
                                            <div className="flex items-center gap-2">
                                                <span className="font-medium text-primary text-sm">{visitor.name}</span>
                                                <span className={`${getTypeBadge(visitor.type)} text-[10px]`}>
                                                    {visitor.type}
                                                </span>
                                            </div>
                                            <div className="text-xs text-tertiary">
                                                {visitor.company && `${visitor.company} · `}
                                                {visitor.purpose}
                                            </div>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-4">
                                        <div className="text-right hidden md:block">
                                            <div className="text-[10px] text-tertiary uppercase tracking-wider">Badge</div>
                                            <div className="text-xs text-accent font-mono">{visitor.badgeNumber}</div>
                                        </div>
                                        <div className="text-right hidden md:block">
                                            <div className="text-[10px] text-tertiary uppercase tracking-wider">Duration</div>
                                            <div className="text-xs text-primary">{formatDuration(visitor.entryTime)}</div>
                                        </div>
                                        <div className="flex gap-2">
                                            <button
                                                onClick={() => handleCheckOut(visitor)}
                                                className="btn btn-secondary text-xs h-8"
                                            >
                                                <LogOut size={14} />
                                                Sign Out
                                            </button>
                                            <button
                                                onClick={() => setRevokeModal({ visitor, notes: '' })}
                                                className="btn btn-ghost text-destructive hover:bg-destructive-muted text-xs h-8"
                                            >
                                                <AlertTriangle size={14} />
                                                Revoke
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}

            {/* All Visitors Tab */}
            {activeTab === 'all' && (
                <div className="space-y-4">
                    <div className="flex gap-3">
                        <div className="flex-1 relative">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-tertiary" size={16} />
                            <input
                                type="text"
                                value={searchQuery}
                                onChange={e => setSearchQuery(e.target.value)}
                                onKeyDown={e => e.key === 'Enter' && loadData()}
                                placeholder="Search all records..."
                                className="input w-full pl-9"
                            />
                        </div>
                        <button className="btn btn-secondary">
                            <Filter size={16} />
                            Filter
                        </button>
                    </div>

                    <div className="card overflow-hidden">
                        <table className="w-full">
                            <thead className="bg-secondary">
                                <tr className="text-left text-xs text-tertiary uppercase tracking-wider">
                                    <th className="p-4">Visitor</th>
                                    <th className="p-4">Type</th>
                                    <th className="p-4">Company</th>
                                    <th className="p-4">Last Visit</th>
                                    <th className="p-4">Status</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-subtle">
                                {allVisitors.map(visitor => (
                                    <tr key={visitor.id} className="hover:bg-tertiary transition-colors duration-fast">
                                        <td className="p-4">
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 bg-tertiary rounded-full flex items-center justify-center text-secondary text-xs font-semibold">
                                                    {visitor.name.charAt(0)}
                                                </div>
                                                <div>
                                                    <div className="text-sm font-medium text-primary">{visitor.name}</div>
                                                    <div className="text-xs text-tertiary">{visitor.email}</div>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="p-4">
                                            <span className={`${getTypeBadge(visitor.type)} text-[10px]`}>
                                                {visitor.type}
                                            </span>
                                        </td>
                                        <td className="p-4 text-sm text-secondary">{visitor.company || '—'}</td>
                                        <td className="p-4 text-xs text-tertiary">
                                            {visitor.logs[0]
                                                ? new Date(visitor.logs[0].entryTime).toLocaleDateString()
                                                : 'Never'
                                            }
                                        </td>
                                        <td className="p-4">
                                            {visitor.logs[0]?.status === 'CHECKED_IN' ? (
                                                <span className="badge-success text-[10px]">On-Site</span>
                                            ) : visitor.logs[0]?.status === 'REVOKED' ? (
                                                <span className="badge-destructive text-[10px]">REVOKED</span>
                                            ) : (
                                                <span className="badge text-[10px]">Off-Site</span>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {/* Zones Tab */}
            {activeTab === 'zones' && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                    {zones.map(zone => (
                        <div key={zone.id} className="card p-4">
                            <div className="flex items-center justify-between mb-3">
                                <div>
                                    <h3 className="font-medium text-primary text-sm">{zone.name}</h3>
                                    <span className="text-xs text-tertiary font-mono">{zone.code}</span>
                                </div>
                                <Building className="text-tertiary" size={20} />
                            </div>
                            {zone.description && (
                                <p className="text-xs text-tertiary mb-3">{zone.description}</p>
                            )}
                            <div className="flex flex-wrap gap-1">
                                {zone.escortRequired && <span className="badge-warning text-[10px]">Escort Required</span>}
                                {zone.ndaRequired && <span className="badge-destructive text-[10px]">NDA Required</span>}
                                {zone.maxOccupancy && <span className="badge-accent text-[10px]">Max: {zone.maxOccupancy}</span>}
                            </div>
                        </div>
                    ))}

                    <button className="card card-interactive p-8 flex flex-col items-center justify-center gap-2 border-dashed">
                        <Building size={24} className="text-tertiary" />
                        <span className="text-sm text-tertiary">Add Zone</span>
                    </button>
                </div>
            )}

            {/* Reports Tab */}
            {activeTab === 'reports' && (
                <div className="card p-6">
                    <div className="flex items-center justify-between mb-6">
                        <h3 className="text-lg font-medium text-primary">Visitor Reports</h3>
                        <button className="btn btn-secondary">
                            <Download size={16} />
                            Export Report
                        </button>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="bg-tertiary rounded-lg p-4">
                            <h4 className="text-sm font-medium text-primary mb-3">Quick Reports</h4>
                            <ul className="space-y-2">
                                <li>
                                    <a href="#" className="text-accent hover:underline text-sm flex items-center gap-2">
                                        <Calendar size={14} />
                                        Last 7 Days Visitor Log
                                    </a>
                                </li>
                                <li>
                                    <a href="#" className="text-accent hover:underline text-sm flex items-center gap-2">
                                        <Calendar size={14} />
                                        Last 30 Days Visitor Log
                                    </a>
                                </li>
                                <li>
                                    <a href="#" className="text-accent hover:underline text-sm flex items-center gap-2">
                                        <Shield size={14} />
                                        Compliance Report (90 days)
                                    </a>
                                </li>
                            </ul>
                        </div>
                        <div className="bg-tertiary rounded-lg p-4">
                            <h4 className="text-sm font-medium text-primary mb-3">Custom Report</h4>
                            <div className="space-y-3">
                                <div>
                                    <label className="text-xs text-tertiary">Date Range</label>
                                    <div className="flex gap-2 mt-1">
                                        <input type="date" className="input flex-1 h-9 text-xs" />
                                        <input type="date" className="input flex-1 h-9 text-xs" />
                                    </div>
                                </div>
                                <button className="btn btn-ghost w-full text-accent hover:bg-accent-muted text-sm">
                                    Generate Report
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Revoke Modal */}
            {revokeModal && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50 animate-fade-in">
                    <div className="card w-full max-w-md p-6 animate-scale-in">
                        <div className="flex items-center justify-between mb-4">
                            <div className="flex items-center gap-2 text-destructive">
                                <AlertTriangle size={20} />
                                <h3 className="text-lg font-semibold">Revoke Access</h3>
                            </div>
                            <button
                                onClick={() => setRevokeModal(null)}
                                className="p-2 hover:bg-tertiary rounded-md transition-colors"
                            >
                                <X size={16} className="text-tertiary" />
                            </button>
                        </div>

                        <p className="text-sm text-secondary mb-4">
                            Revoke access for <span className="font-semibold text-primary">{revokeModal.visitor.name}</span>?
                            This will invalidate their badge.
                        </p>

                        <div className="mb-6">
                            <label className="block text-xs font-medium text-tertiary uppercase tracking-wider mb-2">
                                Reason for Revocation
                            </label>
                            <textarea
                                value={revokeModal.notes}
                                onChange={e => setRevokeModal({ ...revokeModal, notes: e.target.value })}
                                className="input w-full h-24 py-3 resize-none"
                                placeholder="Security violation, elapsed time, etc."
                            />
                        </div>

                        <div className="flex gap-3">
                            <button
                                onClick={() => setRevokeModal(null)}
                                className="btn btn-secondary flex-1"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={handleRevoke}
                                disabled={!revokeModal.notes.trim()}
                                className="btn flex-1 bg-destructive hover:bg-destructive/90 text-white disabled:opacity-50"
                            >
                                REVOKE ACCESS
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
