import React, { useEffect } from 'react';
import { X, RotateCcw, SlidersHorizontal } from 'lucide-react';

/**
 * FilterDrawer — a right-side slide-in drawer for employer portal filter panels.
 *
 * Props:
 *   open          {boolean}   – controls visibility
 *   onClose       {function}  – called when backdrop or X is clicked
 *   onReset       {function}  – called when "Clear All" is clicked
 *   activeCount   {number}    – number of active filters (shown in badge)
 *   title         {string}    – drawer heading
 *   children      {node}      – filter form content
 */
export default function FilterDrawer({ open, onClose, onReset, activeCount = 0, title = 'Filters', children }) {
    // Lock body scroll when drawer is open
    useEffect(() => {
        if (open) {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = '';
        }
        return () => { document.body.style.overflow = ''; };
    }, [open]);

    // Close on Escape key
    useEffect(() => {
        const handler = (e) => { if (e.key === 'Escape') onClose(); };
        window.addEventListener('keydown', handler);
        return () => window.removeEventListener('keydown', handler);
    }, [onClose]);

    return (
        <>
            {/* ── Backdrop ── */}
            <div
                className={`fixed inset-0 z-40 bg-black/30 backdrop-blur-[2px] transition-opacity duration-300 ${
                    open ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'
                }`}
                onClick={onClose}
                aria-hidden="true"
            />

            {/* ── Drawer Panel ── */}
            <div
                role="dialog"
                aria-modal="true"
                aria-label={title}
                className={`fixed top-0 right-0 z-50 h-full w-full sm:w-[420px] bg-white shadow-2xl flex flex-col transition-transform duration-300 ease-in-out ${
                    open ? 'translate-x-0' : 'translate-x-full'
                }`}
            >
                {/* Header */}
                <div className="flex items-center justify-between px-6 py-5 border-b border-slate-100 bg-gradient-to-r from-[#185FA5]/5 to-white flex-shrink-0">
                    <div className="flex items-center space-x-3">
                        <div className="p-2 bg-[#185FA5]/10 rounded-xl">
                            <SlidersHorizontal className="w-4 h-4 text-[#185FA5]" />
                        </div>
                        <div>
                            <h2 className="text-sm font-black text-slate-900 tracking-tight">{title}</h2>
                            {activeCount > 0 && (
                                <p className="text-[10px] font-bold text-[#185FA5] mt-0.5">
                                    {activeCount} filter{activeCount !== 1 ? 's' : ''} active
                                </p>
                            )}
                        </div>
                    </div>
                    <div className="flex items-center space-x-2">
                        {activeCount > 0 && (
                            <button
                                type="button"
                                onClick={onReset}
                                className="flex items-center space-x-1.5 px-3 py-1.5 rounded-lg text-[11px] font-bold text-rose-600 hover:bg-rose-50 border border-rose-100 transition-all"
                            >
                                <RotateCcw className="w-3 h-3" />
                                <span>Clear All</span>
                            </button>
                        )}
                        <button
                            type="button"
                            onClick={onClose}
                            className="p-2 rounded-xl hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors"
                            aria-label="Close filters"
                        >
                            <X className="w-5 h-5" />
                        </button>
                    </div>
                </div>

                {/* Scrollable body */}
                <div className="flex-1 overflow-y-auto px-6 py-5 space-y-6">
                    {children}
                </div>

                {/* Footer */}
                <div className="px-6 py-4 border-t border-slate-100 bg-slate-50/50 flex-shrink-0">
                    <button
                        type="button"
                        onClick={onClose}
                        className="w-full py-3 bg-[#185FA5] hover:bg-[#1450861] text-white text-sm font-bold rounded-xl transition-all shadow-sm hover:shadow-md active:scale-[0.98]"
                        style={{ background: 'linear-gradient(135deg, #185FA5 0%, #1d7dd6 100%)' }}
                    >
                        Apply Filters
                        {activeCount > 0 && (
                            <span className="ml-2 bg-white/20 text-white text-[10px] font-black px-2 py-0.5 rounded-full">
                                {activeCount} active
                            </span>
                        )}
                    </button>
                </div>
            </div>
        </>
    );
}

/**
 * FilterSection — a labelled group inside FilterDrawer.
 */
export function FilterSection({ label, children }) {
    return (
        <div className="space-y-3">
            <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{label}</p>
            {children}
        </div>
    );
}

/**
 * FilterSelect — a full-width styled select inside FilterDrawer.
 */
export function FilterSelect({ id, value, onChange, disabled = false, children }) {
    return (
        <select
            id={id}
            value={value}
            onChange={onChange}
            disabled={disabled}
            className={`w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-semibold text-slate-700 focus:ring-2 focus:ring-blue-100 focus:border-[#185FA5] outline-none cursor-pointer transition-all ${
                disabled ? 'opacity-40 cursor-not-allowed bg-slate-100' : ''
            }`}
        >
            {children}
        </select>
    );
}

/**
 * FilterInput — a full-width styled text input inside FilterDrawer.
 */
export function FilterInput({ id, value, onChange, placeholder }) {
    return (
        <input
            id={id}
            type="text"
            value={value}
            onChange={onChange}
            placeholder={placeholder}
            className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-semibold text-slate-700 focus:ring-2 focus:ring-blue-100 focus:border-[#185FA5] outline-none transition-all placeholder:text-slate-400 placeholder:font-normal"
        />
    );
}

/**
 * FilterChips — a row of selectable chip buttons for single-select options.
 * options: [{ value, label }]
 */
export function FilterChips({ options, selected, onChange }) {
    return (
        <div className="flex flex-wrap gap-2">
            {options.map(opt => (
                <button
                    key={opt.value}
                    type="button"
                    onClick={() => onChange(opt.value)}
                    className={`px-3 py-1.5 rounded-full text-xs font-bold transition-all border ${
                        selected === opt.value
                            ? 'bg-[#185FA5] text-white border-[#185FA5] shadow-sm'
                            : 'bg-white text-slate-600 border-slate-200 hover:border-[#185FA5] hover:text-[#185FA5]'
                    }`}
                >
                    {opt.label}
                </button>
            ))}
        </div>
    );
}

/**
 * FilterCheckboxList — a list of checkboxes for multi-select.
 * items: string[]
 */
export function FilterCheckboxList({ items, selected, onToggle }) {
    return (
        <div className="space-y-2 max-h-48 overflow-y-auto pr-1">
            {items.map(item => (
                <label key={item} className="flex items-center space-x-3 cursor-pointer group">
                    <div className={`w-4 h-4 rounded border-2 flex items-center justify-center flex-shrink-0 transition-all ${
                        selected.includes(item)
                            ? 'bg-[#185FA5] border-[#185FA5]'
                            : 'border-slate-300 group-hover:border-[#185FA5]'
                    }`}>
                        {selected.includes(item) && (
                            <svg className="w-2.5 h-2.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
                                <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                            </svg>
                        )}
                    </div>
                    <span className="text-sm font-medium text-slate-700 capitalize group-hover:text-slate-900 transition-colors">{item}</span>
                </label>
            ))}
        </div>
    );
}
