import { useEffect, useState } from 'react';
import {
    Box,
    Button,
    Divider,
    FormControl,
    FormLabel,
    IconButton,
    Stack,
    Select,
    MenuItem,
} from '@mui/material';
import {
    ModalBackdrop,
    ModalContainer,
    HeaderContainer,
    ModalTitle,
} from '../../common/Modal/ModalStyled';
import { Cancel } from '../../common/icons/icons';
import { DictVspApi } from '../../../api/dict-vsp';
import { toast } from 'react-toastify';

export const SelectVspModal = ({
    isOpen,
    onClose,
    onSelect,
    formId,
    title = 'Выбор ВСП',
    isSaving = false,
}) => {
    const [selectedValue, setSelectedValue] = useState('');
    const [vspOptions, setVspOption] = useState([])

    useEffect(() => {
        if (formId === null) return;
        DictVspApi.getDropdownVsp({ form_id: formId }).then(data => {
            if (data.success) {
                setVspOption(data.result)
                return;
            }
            toast.error('Ошибка получения ВСП')
        })
    }, [formId])

    useEffect(() => {
        if (!isOpen) {
            setSelectedValue('');
        }
    }, [isOpen])

    const handleCancel = () => {
        setSelectedValue('');
        onClose();
    };

    const handleBackdropClick = (e) => {
        if (e.target === e.currentTarget) {
            handleCancel();
        }
    };

    const handleSave = () => {
        onSelect?.(selectedValue);
        onClose();
    };

    const isFormValid = selectedValue;

    if (!isOpen) return null;

    return (
        <ModalBackdrop isOpen={isOpen} onClick={handleBackdropClick}>
            <ModalContainer height={'max-content'} >
                <HeaderContainer>
                    <Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>
                        <ModalTitle>{title}</ModalTitle>
                    </Stack>
                    <IconButton size="small" onClick={handleCancel}>
                        <Cancel />
                    </IconButton>
                </HeaderContainer>

                <Box>
                    <Divider sx={{ marginBottom: '0.75rem' }} />

                    {/* Выбор ВСП */}
                    <Stack sx={{ marginBottom: '0.75rem', width: '100%' }}>
                        <FormControl fullWidth>
                            <Select
                                value={selectedValue}
                                onChange={(e) => setSelectedValue(e.target.value)}
                                displayEmpty
                                size="small"
                            >
                                <MenuItem value="" disabled>
                                    Выберите ВСП
                                </MenuItem>
                                {vspOptions.map((option) => (
                                    <MenuItem key={option.id} value={option.id}>
                                        {option.registration_number}
                                    </MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                    </Stack>

                    <Stack
                        direction="row"
                        spacing={0.75}
                        sx={{
                            justifyContent: 'flex-end',
                            marginTop: '1.5rem',
                            width: '100%',
                        }}
                    >
                        <Button
                            variant="outlined"
                            color="default"
                            onClick={handleCancel}
                            style={{ height: '2.5rem' }}
                            disabled={isSaving}
                        >
                            Отмена
                        </Button>
                        <Button
                            variant="contained"
                            onClick={handleSave}
                            style={{ height: '2.5rem' }}
                            disabled={!isFormValid || isSaving}
                            loading={isSaving}
                        >
                            Выбрать
                        </Button>
                    </Stack>
                </Box>
            </ModalContainer>
        </ModalBackdrop>
    );
};