import { useRoles, useUsers } from "../hooks/swrHooks"
import { IRole } from "../interfaces/role"
import { useEffect, useState } from "react"
import { CreateField } from "../interfaces/create"
import UserService from "../services/UserService"
import CustomTable from "../components/CustomTable"
import { Link, Spinner } from "@fluentui/react-components"
import { IUser } from "../interfaces/user"

export default function Users() {
    const { users, isError, isLoading } = useUsers()

    const { roles } = useRoles()

    const [roleOptions, setRoleOptions] = useState<{ label: string, value: string }[]>()

    const [data, setData] = useState<IUser[]>([])

    useEffect(() => {
        if (Array.isArray(roles)) {
            setRoleOptions(roles.map((role: IRole) => ({ label: role.name, value: role.id.toString() })))
        }
    }, [roles])

    useEffect(() => {
        if (users) {
            setData(users)
        }
    }, [users])

    const createFields: CreateField[] = [
        { key: 'email', headerName: 'E-mail', type: 'string', required: true, defaultValue: '' },
        { key: 'login', headerName: 'Логин', type: 'string', required: true, defaultValue: '' },
        { key: 'phone', headerName: 'Телефон', type: 'string', required: false, defaultValue: '' },
        { key: 'name', headerName: 'Имя', type: 'string', required: true, defaultValue: '' },
        { key: 'surname', headerName: 'Фамилия', type: 'string', required: true, defaultValue: '' },
        { key: 'password', headerName: 'Пароль', type: 'string', required: true, defaultValue: '' },
    ]

    const handleError = (error: any) => {
        if (error?.response?.status === 401) {
            return (
                <Link href="/auth/signin">
                Войдите, чтобы продолжить
                </Link>
            )
        } else {
            return "Произошла ошибка при получении данных."
        }
    }

    if (isError) return (
        <div style={{ padding: '1rem' }}>
            {handleError(isError)}
        </div>
    )

    if (isLoading) {
        return (
            <div style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                width: '100%',
                height: '100%',
                padding: '1rem',
            }}>
                <Spinner />
            </div>
        )
    }

    return (
        <div style={{
            display: 'flex',
            flexDirection: 'column',
            width: '100%',
            height: '100%',
            padding: '1rem'
        }}>
            {Array.isArray(roleOptions) && Array.isArray(data) &&
                <CustomTable
                    createFields={createFields}
                    submitHandler={UserService.createUser}
                    data={data}
                    onEditCell={(rowId, columnId, value) => {
                        console.log(rowId, columnId, value)
                        setData((prev) =>
                            prev.map((row) =>
                                row.id === rowId ? { ...row, [columnId]: value } : row
                            )
                        )
                    }}
                    columns={[
                        {
                            name: 'email',
                            header: 'E-mail',
                            type: "string"
                        },
                        {
                            name: 'login',
                            header: 'Логин',
                            type: "string"
                        },
                        {
                            name: 'phone',
                            header: 'Телефон',
                            type: "string"
                        },
                        {
                            name: 'name',
                            header: 'Имя',
                            type: "string"
                        },
                        {
                            name: 'surname',
                            header: 'Фамилия',
                            type: "string"
                        },
                        {
                            name: 'is_active',
                            header: 'Активен',
                            type: "boolean"
                        },
                        {
                            name: 'role_id',
                            header: 'Роль',
                            type: "dictionary" //TODO: dictionary getter by id
                        }
                    ]} />
            }
        </div>
    )
}