
import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
    ChevronDown, Search, Menu, LogOut, X, Bike, FileBarChart,
    TrendingUp, Box, Wallet, Receipt, LayoutGrid, CheckCircle2
} from 'lucide-react';

export const ROLES = {
    IT_ADMIN: 'IT_ADMIN',
    ADMIN: 'ADMIN',
    OPERATOR: 'OPERATOR',
    VIEWER: 'VIEWER'
};

export const formatCurrency = (num: number | string) => "PKR " + (Number(num) || 0).toLocaleString();
export const getCurrentDate = () => new Date().toISOString().split('T')[0];

export function Toast({ message, onClose }: { message: string, onClose: () => void }) {
    useEffect(() => {
        const timer = setTimeout(onClose, 3000);
        return () => clearTimeout(timer);
    }, [onClose]);

    return (
        <div className="fixed top-6 right-6 z-[400] animate-slide-in-right">
            <div className="bg-slate-900/95 text-white px-6 py-4 rounded-2xl shadow-2xl flex items-center gap-4 border border-white/10 backdrop-blur-md min-w-[320px]">
                <div className="w-10 h-10 bg-emerald-500 rounded-full flex items-center justify-center text-white shrink-0 shadow-lg shadow-emerald-500/20">
                    <CheckCircle2 size={22} />
                </div>
                <div className="flex-1">
                    <p className="text-[10px] font-black uppercase tracking-widest text-emerald-400 mb-0.5 leading-none">System Notification</p>
                    <p className="text-sm font-bold uppercase tracking-tight leading-tight">{message}</p>
                </div>
                <button onClick={onClose} className="ml-2 p-1.5 hover:bg-white/10 rounded-lg transition-colors">
                    <X size={16} className="text-slate-400" />
                </button>
            </div>
            <div className="absolute bottom-0 left-0 right-0 h-1 bg-emerald-500 rounded-b-2xl animate-shrink-width" />
        </div>
    );
}

export function IntegratedInput({ label, value, onChange, placeholder, icon: Icon, type = "text", colSpan = "col-span-1", disabled = false }: any) {
    return (
        <div className={`${colSpan} group bg-white rounded-xl border border-slate-200 overflow-hidden focus-within:border-cyan-500 focus-within:ring-4 focus-within:ring-cyan-500/10 transition-all duration-300 ${disabled ? 'bg-slate-50 opacity-60' : 'hover:border-slate-300'}`}>
            <div className="flex items-center gap-2 bg-slate-50/50 px-4 py-2 border-b border-slate-100/80">
                {Icon && <Icon size={12} className="text-slate-400 group-focus-within:text-cyan-600 transition-colors" />}
                <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest">{String(label)}</label>
            </div>
            <div className="px-4 py-2.5">
                <input
                    type={type}
                    value={value}
                    onChange={onChange}
                    placeholder={placeholder}
                    disabled={disabled}
                    className="w-full bg-transparent text-sm font-bold text-slate-900 outline-none placeholder:text-slate-300 placeholder:font-medium tracking-tight"
                />
            </div>
        </div>
    );
}

export function IntegratedSelect({ label, value, onChange, options, icon: Icon, colSpan = "col-span-1", displayKey = null, placeholder = null, disabled = false }: any) {
    const [isOpen, setIsOpen] = useState(false);
    const [search, setSearch] = useState('');
    const dropdownRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    const filteredOptions = useMemo(() => {
        if (!search) return options || [];
        const term = search.toLowerCase();
        return (options || []).filter((opt: any) => {
            if (typeof opt === 'object' && opt !== null) {
                // Search across all values in the object
                return Object.values(opt).some(val => String(val).toLowerCase().includes(term));
            }
            return String(opt).toLowerCase().includes(term);
        });
    }, [options, search]);

    const selectedOption = useMemo(() => {
        return (options || []).find((opt: any) => {
            const val = displayKey ? (opt.id || opt[displayKey]) : opt;
            return String(val) === String(value);
        });
    }, [options, value, displayKey]);

    const handleSelect = (opt: any) => {
        const val = displayKey ? (opt.id || opt[displayKey]) : opt;
        onChange({ target: { value: val } });
        setIsOpen(false);
        setSearch('');
    };

    // Helper to safely render the label string
    const getOptionLabel = (opt: any) => {
        if (!opt) return '';
        if (typeof opt === 'object') {
            if (displayKey && opt[displayKey]) return String(opt[displayKey]);
            // Fallback: try common keys or just first value, never return object
            return String(opt.label || opt.name || Object.values(opt)[0] || 'Invalid Object');
        }
        return String(opt);
    };

    return (
        <div ref={dropdownRef} className={`${colSpan} relative group bg-white rounded-xl border border-slate-200 focus-within:border-cyan-500 focus-within:ring-4 focus-within:ring-cyan-500/10 transition-all duration-300 ${disabled ? 'bg-slate-50 opacity-60' : 'hover:border-slate-300'} ${isOpen ? 'z-50 ring-4 ring-cyan-500/10 border-cyan-500' : 'z-0'}`}>
            <div className="flex items-center gap-2 bg-slate-50/50 px-4 py-2 border-b border-slate-100/80">
                {Icon && <Icon size={12} className="text-slate-400 group-focus-within:text-cyan-600 transition-colors" />}
                <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest">{String(label)}</label>
            </div>

            <div onClick={() => !disabled && setIsOpen(!isOpen)} className={`px-4 py-3 flex justify-between items-center cursor-pointer min-h-[44px] ${disabled ? 'pointer-events-none' : ''}`}>
            <span className={`text-sm font-bold truncate tracking-tight ${selectedOption ? 'text-slate-900' : 'text-slate-300 font-medium'}`}>
                {selectedOption ? getOptionLabel(selectedOption) : (placeholder || 'Select...')}
            </span>
                <ChevronDown size={16} className={`text-slate-400 transition-transform duration-300 ${isOpen ? 'rotate-180 text-cyan-600' : ''}`} />
            </div>

            {isOpen && (
                <div className="absolute top-[calc(100%+8px)] left-0 right-0 z-[200] bg-white border border-slate-200 rounded-xl shadow-2xl overflow-hidden animate-fade-in ring-1 ring-black/5">
                    <div className="p-2 border-b border-slate-100 bg-slate-50">
                        <div className="flex items-center gap-2 bg-white border border-slate-200 rounded-lg px-3 py-2 focus-within:border-cyan-500 focus-within:ring-2 focus-within:ring-cyan-500/20 transition-all">
                            <Search size={14} className="text-slate-400" />
                            <input autoFocus type="text" placeholder={`Search ${label}...`} className="w-full text-xs font-bold text-slate-900 placeholder:text-slate-300 outline-none uppercase tracking-wide bg-transparent"
                                   value={search} onChange={(e) => setSearch(e.target.value)} onClick={(e) => e.stopPropagation()}
                            />
                        </div>
                    </div>
                    <div className="max-h-60 overflow-y-auto custom-scrollbar p-1">
                        {filteredOptions.length === 0 ? (
                            <div className="px-4 py-6 text-xs font-bold text-slate-400 uppercase italic text-center">No matching records</div>
                        ) : (
                            filteredOptions.map((opt: any, idx: number) => {
                                const val = displayKey ? (opt.id || opt[displayKey]) : opt;
                                const isActive = String(val) === String(value);
                                return (
                                    <div key={idx} onClick={() => handleSelect(opt)} className={`px-4 py-3 text-xs font-bold uppercase tracking-tight rounded-lg cursor-pointer transition-all mb-0.5 ${isActive ? 'bg-cyan-50 text-cyan-700' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'}`}>
                                        <div className="flex justify-between items-center">
                                            <span>{getOptionLabel(opt)}</span>
                                            {isActive && <div className="w-1.5 h-1.5 rounded-full bg-cyan-500"></div>}
                                        </div>
                                        {/* Optional Secondary Detail if available */}
                                        {typeof opt === 'object' && opt.chassisNumber && <div className="text-[9px] text-slate-400 font-mono mt-0.5 tracking-normal">CHS: {opt.chassisNumber}</div>}
                                    </div>
                                );
                            })
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}

export function Header({ title, onMenuClick, user, onLogout, setActiveItem }: any) {
    const [reportsOpen, setReportsOpen] = useState(false);
    const reportsRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (reportsRef.current && !reportsRef.current.contains(event.target as Node)) {
                setReportsOpen(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    const reportLinks = [
        { id: 'sales_report', label: 'Sales Ledger', icon: TrendingUp },
        { id: 'stock_report', label: 'Stock Audit', icon: Box },
        { id: 'expense_report', label: 'Expense Analysis', icon: Wallet },
        { id: 'financial_summary', label: 'Net Profit Report', icon: Receipt },
    ];

    return (
        <header className="flex justify-between items-center py-4 px-6 lg:px-8 mb-2 bg-white/80 backdrop-blur-md sticky top-0 z-50 border-b border-slate-100 leading-none">
            <div className="flex items-center gap-6 leading-none">
                <div className="flex items-center gap-4">
                    <button onClick={onMenuClick} className="p-2 bg-white rounded-lg text-slate-900 shadow-sm border border-slate-200 lg:hidden leading-none">
                        <Menu size={18} />
                    </button>
                    <h2 className="text-xl font-bold font-heading text-slate-900 tracking-tight uppercase truncate underline decoration-cyan-500/30 underline-offset-8 leading-none">
                        {String(title)}
                    </h2>
                </div>

                <div className="hidden lg:flex items-center h-10 px-1 bg-slate-50 rounded-xl border border-slate-200 leading-none">
                    <button
                        onClick={() => setActiveItem('dashboard')}
                        className="px-4 py-2 text-[10px] font-black uppercase tracking-widest text-slate-400 hover:text-slate-900 transition-colors flex items-center gap-2"
                    >
                        <LayoutGrid size={14}/> Terminal
                    </button>
                    <div className="w-[1px] h-4 bg-slate-200"></div>
                    <div className="relative" ref={reportsRef}>
                        <button
                            onClick={() => setReportsOpen(!reportsOpen)}
                            className={`px-4 py-2 text-[10px] font-black uppercase tracking-widest transition-colors flex items-center gap-2 ${reportsOpen ? 'text-cyan-600' : 'text-slate-400 hover:text-slate-900'}`}
                        >
                            <FileBarChart size={14}/> Reports <ChevronDown size={12} className={`transition-transform ${reportsOpen ? 'rotate-180' : ''}`} />
                        </button>

                        {reportsOpen && (
                            <div className="absolute top-full left-0 mt-2 w-56 bg-white rounded-2xl shadow-2xl border border-slate-200 p-2 animate-fade-in leading-none ring-1 ring-black/5">
                                {reportLinks.map(link => (
                                    <button
                                        key={link.id}
                                        onClick={() => { setActiveItem('reports'); setReportsOpen(false); }}
                                        className="w-full flex items-center gap-3 px-4 py-3 rounded-xl hover:bg-slate-50 transition-colors group leading-none"
                                    >
                                        <div className="w-8 h-8 rounded-lg bg-slate-50 flex items-center justify-center text-slate-400 group-hover:bg-cyan-50 group-hover:text-cyan-600">
                                            <link.icon size={16} />
                                        </div>
                                        <span className="text-[11px] font-black uppercase text-slate-600 group-hover:text-slate-900">{link.label}</span>
                                    </button>
                                ))}
                                <div className="border-t border-slate-100 my-1 pt-1">
                                    <button
                                        onClick={() => { setActiveItem('reports'); setReportsOpen(false); }}
                                        className="w-full text-center py-2 text-[8px] font-black text-cyan-600 uppercase tracking-[0.2em]"
                                    >
                                        View Full Report Center
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            <div className="flex items-center gap-4 leading-none">
                <div className="hidden md:flex flex-col items-end leading-none">
                    <span className="text-xs font-bold text-slate-900 leading-none">{user?.name}</span>
                    <span className="text-[10px] text-cyan-600 font-bold uppercase tracking-widest leading-none">{user?.role}</span>
                </div>
                <button onClick={onLogout} className="p-2 bg-white rounded-lg text-slate-400 hover:text-rose-600 shadow-sm border border-slate-200 transition-colors leading-none" title="Logout">
                    <LogOut size={18} />
                </button>
            </div>
        </header>
    );
}

export function SidebarItem({ item, isActive, onClick }: any) {
    const IconComp = item.icon;
    return (
        <button onClick={onClick} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg transition-all duration-200 group relative ${isActive ? 'bg-white text-slate-950 shadow-md font-bold' : 'text-slate-400 hover:bg-white/5 hover:text-white font-medium'} leading-none`}>
            <IconComp size={16} className={isActive ? 'text-cyan-600' : 'group-hover:text-cyan-400 transition-colors'} />
            <span className="text-xs tracking-wide uppercase leading-none">{String(item.label)}</span>
        </button>
    );
}
