import { saveRole } from '@/api/api_role';
import { alertError, alertSuccess } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { SelectRole } from '@/components/costum/SelectRole';
import { useModalRole } from '@/components/modal/modalRole';
import { APP_MENU } from '@/const/menu';
import { NavigationMenuItem, Role } from '@/types';
import { useRole } from '@/useQuery/query';
import { usePage } from '@inertiajs/react';
import { DeleteIcon, PlusIcon, Save } from 'lucide-react';
import { useState } from 'react';
import { Form } from 'react-bootstrap';

export default function RolePage() {
    const { token } = usePage().props;
    const roles = useRole();

    const [role, setRole] = useState<Role>();
    const [appMenu, setAppMenu] = useState<NavigationMenuItem[]>(structuredClone(APP_MENU));

    const modalRole = useModalRole({
        onSubmit: async (role) => {
            const response = await saveRole(role, token as string);
            const data = await response.json();
            if (response.status == 200 || response.status == 201) {
                roles.refetch();
                alertSuccess('Role berhasil disimpan');
                modalRole.close();
            } else {
                alertError(data.message);
            }
        },
    });

    const renderAppMenu = (item: NavigationMenuItem, indent?: number) => {
        return (
            <tr>
                <td></td>
                <td>
                    <label htmlFor={item.label} style={{ marginLeft: indent ?? 0 }}>
                        <div>{item.label}</div>
                    </label>
                </td>
                <td className="d-flex justify-content-center">
                    {item.href && (
                        <Form.Check
                            id={item.label}
                            checked={item.checked == 1 ? true : false}
                            onChange={(e) => {
                                const currentAppMenu = [...appMenu];
                                currentAppMenu.forEach((menu, idx) => {
                                    if (menu.label == item.label) {
                                        currentAppMenu[idx] = { ...menu, checked: e.target.checked ? 1 : 0 };
                                    }
                                    if (menu.children) {
                                        menu.children = menu.children.map((child) => {
                                            if (child.label == item.label) {
                                                return { ...child, checked: e.target.checked ? 1 : 0 };
                                            }
                                            if (child.children) {
                                                child.children = child.children.map((sub) => {
                                                    if (sub.label == item.label) {
                                                        return { ...sub, checked: e.target.checked ? 1 : 0 };
                                                    }
                                                    return sub;
                                                });
                                            }
                                            return child;
                                        });
                                    }
                                });
                                setAppMenu(currentAppMenu);
                            }}
                        />
                    )}
                </td>
            </tr>
        );
    };

    // const renderUserMenu = (item: NavigationMenuItem, indent?: number) => {
    //     return (
    //         <tr>
    //             <td></td>
    //             <td>
    //                 <label htmlFor={item.label} style={{ marginLeft: indent ?? 0 }}>
    //                     <div>{item.label}</div>
    //                 </label>
    //             </td>
    //             <td className="d-flex justify-content-center"></td>
    //         </tr>
    //     );
    // };

    return (
        <>
            <div className="py-3 w-75 container">
                <div className="row">
                    <div className="col-md-12">
                        <div className="mb-2 d-flex justify-content-between">
                            <div className="d-flex gap-3">
                                <ButtonSubmit onClick={modalRole.open} icon={<PlusIcon size={18} />} className="btn-primary">
                                    Tambah Role
                                </ButtonSubmit>
                                <ButtonSubmit
                                    icon={<DeleteIcon size={18} />}
                                    className="btn-warning"
                                    onClick={() => {
                                        setRole(undefined);
                                        setAppMenu(structuredClone(APP_MENU));
                                    }}
                                >
                                    Clear
                                </ButtonSubmit>
                            </div>
                            <ButtonSubmit icon={<Save size={18} />} className="btn-success">
                                Simpan
                            </ButtonSubmit>
                        </div>
                        <hr />
                        <div className="row mb-2">
                            <label className="col-form-label col-md-2">Roles</label>
                            <div className="col-md-4">
                                <SelectRole
                                    onChange={(V) => {
                                        const _role = roles.data?.find((item: Role) => item.id?.toString() == V);
                                        setRole(_role);
                                    }}
                                />
                            </div>
                            <div className="col-md-3" />
                        </div>
                    </div>
                    <div className="col-md-6">
                        <div
                            style={{
                                height: 400,
                                overflow: 'auto',
                                border: '1px solid rgb(187, 187, 187)',
                            }}
                        >
                            <table className="table-bordered table-sm table table-fixed">
                                <thead>
                                    <tr className="fixed">
                                        <th className="text-center" style={{ width: 50 }}></th>
                                        <th>Nama Menu</th>
                                        <th className="text-center" style={{ width: 67, verticalAlign: 'middle' }} />
                                    </tr>
                                </thead>
                                <tbody>
                                    {appMenu?.map((item: NavigationMenuItem) => {
                                        if (!item.children && item.href) {
                                            return renderAppMenu(item);
                                        }
                                        return (
                                            <>
                                                {renderAppMenu(item)}
                                                {item.children?.map((child: NavigationMenuItem) => {
                                                    if (child.href) {
                                                        return renderAppMenu(child, 16);
                                                    }
                                                    return (
                                                        <>
                                                            {renderAppMenu(child, 16)}
                                                            {child.children?.map((submenu: NavigationMenuItem) => {
                                                                if (submenu.href) {
                                                                    return renderAppMenu(submenu, 32);
                                                                }
                                                                return;
                                                            })}
                                                        </>
                                                    );
                                                })}
                                            </>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            {modalRole.modal}
        </>
    );
}
