import { useState } from 'react'
import * as Dialog from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import { useMutation } from '@apollo/client/react'

import {
    GET_USERS_PAGE_QUERY,
    SIGN_UP_MUTATION,
} from '../../../../entities/employee/api/employee.graphql'
import type {
    SignUpData,
    SignUpVariables,
} from '../../../../entities/employee/model/types'

import './AddEmployeeModal.scss'

type AddEmployeeModalProps = {
    open: boolean
    onOpenChange: (open: boolean) => void
}

export function AddEmployeeModal({ open, onOpenChange }: AddEmployeeModalProps) {
    const [organisationId, setOrganisationId] = useState('')
    const [username, setUsername] = useState('')
    const [password, setPassword] = useState('')
    const [groupId, setGroupId] = useState('')

    const [signUp, { loading, error }] = useMutation<SignUpData, SignUpVariables>(
        SIGN_UP_MUTATION,
        {
            refetchQueries: [
                {
                    query: GET_USERS_PAGE_QUERY,
                    variables: {},
                },
            ],
            onCompleted: () => {
                setUsername('')
                setPassword('')
                setGroupId('')
                onOpenChange(false)
            },
        },
    )

    function handleSubmit(event: React.SubmitEvent<HTMLFormElement>) {
        event.preventDefault()

        signUp({
            variables: {
                organisationId,
                username,
                password,
                groupId: groupId.trim() ? groupId : null,
            },
        })
    }

    return (
        <Dialog.Root open={open} onOpenChange={onOpenChange}>
            <Dialog.Portal>
                <Dialog.Overlay className="add-employee-modal__overlay" />

                <Dialog.Content className="add-employee-modal">
                    <div className="add-employee-modal__header">
                        <div>
                            <Dialog.Title className="add-employee-modal__title">
                                Добавить сотрудника
                            </Dialog.Title>

                            <Dialog.Description className="add-employee-modal__description">
                                Создание пользователя для доступа к смартфонам
                            </Dialog.Description>
                        </div>

                        <Dialog.Close className="add-employee-modal__close" type="button">
                            <X size={20} />
                        </Dialog.Close>
                    </div>

                    <form className="add-employee-form" onSubmit={handleSubmit}>
                        <label className="add-employee-field">
                            {/* <span>Логин</span> */}
                            <input
                                value={username}
                                onChange={(event) => setUsername(event.target.value)}
                                placeholder="Логин*"
                                required
                            />
                        </label>

                        <label className="add-employee-field">
                            {/* <span>Пароль</span> */}
                            <input
                                value={password}
                                onChange={(event) => setPassword(event.target.value)}
                                placeholder="Пароль*"
                                type="password"
                                required
                            />
                        </label>

                        <label className="add-employee-field">
                            {/* <span>ID организации</span> */}
                            <input
                                value={organisationId}
                                onChange={(event) => setOrganisationId(event.target.value)}
                                placeholder="ID организации*"
                                required
                            />
                        </label>

                        <label className="add-employee-field">
                            {/* <span>ID группы</span> */}
                            <input
                                value={groupId}
                                onChange={(event) => setGroupId(event.target.value)}
                                placeholder="ID группы"
                            />
                        </label>

                        {error && (
                            <div className="add-employee-error">
                                Не удалось добавить сотрудника. Проверьте данные.
                            </div>
                        )}

                        <div className="add-employee-modal__footer">
                            <Dialog.Close className="add-employee-cancel" type="button">
                                Отмена
                            </Dialog.Close>

                            <button
                                className="add-employee-submit"
                                type="submit"
                                disabled={loading}
                            >
                                {loading ? 'Добавление...' : 'Добавить'}
                            </button>
                        </div>
                    </form>
                </Dialog.Content>
            </Dialog.Portal>
        </Dialog.Root>
    )
}