import React, { useEffect, useState } from 'react';
import Icon from './Icon';
import { OwlMark } from './ui';

type NavLeaf = { id: string; label: string; icon: string };
type NavGroup = { label?: string; icon?: string; items: NavLeaf[] };

export const NAV: NavGroup[] = [
    { items: [{ id: 'Dashboard', label: 'Overview', icon: 'dashboard' }] },
    { label: 'Income', icon: 'income', items: [
        { id: 'IncomeQuotation', label: 'Quotations', icon: 'quote' },
        { id: 'IncomeInvoice', label: 'Invoices', icon: 'invoice' },
        { id: 'IncomeReceipt', label: 'Receipts', icon: 'receipt' },
    ]},
    { label: 'Expense', icon: 'expense', items: [{ id: 'Expense', label: 'Expenses', icon: 'expense' }] },
    { label: 'Staff', icon: 'staff', items: [
        { id: 'Staff', label: 'Staff', icon: 'staff' },
        { id: 'StaffSalary', label: 'Salary', icon: 'salary' },
    ]},
    { label: 'Resources', icon: 'resource', items: [
        { id: 'Contact', label: 'Contacts', icon: 'contact' },
        { id: 'Product', label: 'Products', icon: 'product' },
    ]},
    { label: 'Shareholders', icon: 'shareholder', items: [
        { id: 'Shareholder', label: 'Shareholders', icon: 'shareholder' },
        { id: 'ShareholderLoan', label: 'Loans', icon: 'loan' },
    ]},
    { label: 'Accounting', icon: 'accounting', items: [
        { id: 'AccountingOthers', label: 'Journal · Others', icon: 'accounting' },
        { id: 'AccountingBalance', label: 'Balance Sheet', icon: 'balance' },
    ]},
    { label: 'Website', icon: 'news', items: [
        { id: 'News', label: 'News', icon: 'news' },
        { id: 'Subscriber', label: 'Subscribers', icon: 'send' },
    ]},
    { label: 'System', icon: 'settings', items: [
        { id: 'AdminUser', label: 'Admins', icon: 'shield' },
        { id: 'ApiCredential', label: 'API Credentials', icon: 'key' },
    ]},
];

type SidebarProps = { route: string; setRoute: (id: string) => void };

const Sidebar = ({ route, setRoute }: SidebarProps) => {
    const initialOpen = () => {
        const o: Record<number, boolean> = {};
        NAV.forEach((g, i) => { if (g.label) o[i] = true; });
        return o;
    };
    const [openGroups, setOpenGroups] = useState<Record<number, boolean>>(initialOpen);

    useEffect(() => {
        NAV.forEach((g, i) => {
            if (g.label && g.items.some(it => it.id === route)) {
                setOpenGroups(o => ({ ...o, [i]: true }));
            }
        });
    }, [route]);

    return (
        <aside className="sidebar">
            <div className="sidebar__brand">
                <OwlMark height={32} />
            </div>

            <nav className="sidebar__nav">
                {NAV.map((g, gi) => {
                    if (!g.label) {
                        const it = g.items[0];
                        return (
                            <button key={gi}
                                className={`navitem navitem--solo ${route === it.id ? 'navitem--on' : ''}`}
                                onClick={() => setRoute(it.id)} title={it.label}>
                                <Icon name={it.icon} size={18} />
                                <span className="navitem__txt">{it.label}</span>
                            </button>
                        );
                    }

                    if (g.items.length === 1) {
                        const it = g.items[0];
                        return (
                            <button key={gi}
                                className={`navitem navitem--solo ${route === it.id ? 'navitem--on' : ''}`}
                                onClick={() => setRoute(it.id)} title={g.label}>
                                <Icon name={g.icon || it.icon} size={18} />
                                <span className="navitem__txt">{g.label}</span>
                            </button>
                        );
                    }

                    const open = openGroups[gi];
                    return (
                        <div key={gi} className="navgroup">
                            <button className="navgroup__head"
                                onClick={() => setOpenGroups(o => ({ ...o, [gi]: !o[gi] }))}>
                                {g.icon && <Icon name={g.icon} size={18} />}
                                <span className="navgroup__label">{g.label}</span>
                                <Icon name="chevronDown" size={14}
                                    className={`navgroup__chev ${open ? '' : 'navgroup__chev--closed'}`} />
                            </button>
                            {open && g.items.map(it => (
                                <button key={it.id}
                                    className={`navitem navitem--sub ${route === it.id ? 'navitem--on' : ''}`}
                                    onClick={() => setRoute(it.id)} title={it.label}>
                                    <span className="navitem__dot" />
                                    <span className="navitem__txt">{it.label}</span>
                                </button>
                            ))}
                        </div>
                    );
                })}
            </nav>

        </aside>
    );
};

export default Sidebar;
