import { useEffect, useState } from 'react';
import {
    Box,
    Button,
    Divider,
    FormControl,
    FormLabel,
    IconButton,
    Stack,
    Select,
    MenuItem,
    Autocomplete,
    TextField,
} 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';
import { ExpenseItemApi } from '../../../api/expense-item';
import { DangerOutlinedButton, PrimaryButton } from '../../common/Buttons/Buttons';

export const SelectExpenseItemModal = ({
    isOpen,
    onClose,
    onSelect,
    formId,
    title = '',
    isSaving = false,
    sheet,
}) => {
    const [selectedValue, setSelectedValue] = useState('');
    const [expenseItemOptions, setExpenseItemOption] = useState([])

    useEffect(() => {
        if (formId === null) return;
        ExpenseItemApi.getAll({ r_start: true, sheet: sheet }).then(data => {
            if (data.success) {
                setExpenseItemOption(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>
                            <Autocomplete
                                size="small"
                                options={expenseItemOptions}
                                noOptionsText="Не найдено"
                                getOptionLabel={(option) => option.name || ''}
                                getOptionKey={(option) => option.id}
                                value={selectedValue}
                                onChange={(event, newValue) => {
                                    setSelectedValue(newValue);
                                }}
                                slotProps={{
                                    popper: {
                                        style: { zIndex: 60 },
                                    },
                                }}
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        placeholder="Не выбрана"
                                        sx={{
                                            '& .MuiOutlinedInput-root': {
                                                '& fieldset': {
                                                    borderColor: 'rgba(0,0,0,0.1)',
                                                },
                                            },
                                        }}
                                    />
                                )}
                            />

                        </FormControl>
                    </Stack>

                    <Stack
                        direction="row"
                        spacing={0.75}
                        sx={{
                            justifyContent: 'flex-end',
                            marginTop: '1.5rem',
                            width: '100%',
                        }}
                    >
                        <DangerOutlinedButton
                            onClick={handleCancel}
                            disabled={isSaving}
                        >
                            Отмена
                        </DangerOutlinedButton>

                        <PrimaryButton
                            onClick={handleSave}
                            disabled={!isFormValid || isSaving}
                            loading={isSaving}>
                            Выбрать
                        </PrimaryButton>
                    </Stack>
                </Box>
            </ModalContainer>
        </ModalBackdrop>
    );
};