import { FC, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import CheckBoxComponent from '../../../components/CheckBoxComponent'
import { PERMISSION_GROUP_ORDER } from '../../../helpers/permissions'
import { PermissionType } from '../types/UserTypes'

type Props = {
    permissions: PermissionType[]
    selectedIds: string[]
    onToggle: (id: string) => void
}

const RolePermissionsSelector: FC<Props> = ({ permissions, selectedIds, onToggle }) => {
    const { t } = useTranslation('global')
    const [activeGroup, setActiveGroup] = useState<string>('')

    const groupedPermissions = useMemo(() => {
        const groups = new Map<string, PermissionType[]>()

        PERMISSION_GROUP_ORDER.forEach((group) => {
            groups.set(group, [])
        })

        permissions.forEach((permission) => {
            const groupItems = groups.get(permission.group)
            if (groupItems) {
                groupItems.push(permission)
            }
        })

        return PERMISSION_GROUP_ORDER
            .map((group) => ({
                group,
                items: groups.get(group) ?? [],
            }))
            .filter(({ items }) => items.length > 0)
    }, [permissions])

    useEffect(() => {
        if (groupedPermissions.length === 0) {
            setActiveGroup('')
            return
        }

        if (!groupedPermissions.some(({ group }) => group === activeGroup)) {
            setActiveGroup(groupedPermissions[0].group)
        }
    }, [activeGroup, groupedPermissions])

    const activeGroupPermissions = groupedPermissions.find(({ group }) => group === activeGroup)?.items ?? []

    return (
        <div className='mt-5'>
            <div className='flex flex-wrap items-center gap-2 pb-2'>
                {groupedPermissions.map(({ group }) => (
                    <button
                        key={group}
                        type='button'
                        className={`px-4 py-2 rounded-xl text-sm whitespace-nowrap border transition-all ${activeGroup === group
                            ? 'bg-primary text-white border-primary'
                            : 'bg-white text-gray-700 border-gray-200'
                            }`}
                        onClick={() => setActiveGroup(group)}
                    >
                        {t(`user.permission_groups.${group}`)}
                    </button>
                ))}
            </div>

            <div className='mt-6 text-sm flex flex-wrap gap-5'>
                {activeGroupPermissions.map((item) => (
                    <div key={item.id} className='flex flex-1 min-w-[23%] items-center'>
                        <CheckBoxComponent
                            checked={selectedIds.includes(item.id)}
                            onChange={() => onToggle(item.id)}
                        />
                        <div>{item.title}</div>
                    </div>
                ))}
            </div>
        </div>
    )
}

export default RolePermissionsSelector
