import { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Divider,
  FormControlLabel,
  Stack,
  Typography,
} from '@mui/material';
import Modal from '../../../../components/common/Modal/Modal';
import { PrimaryButton } from '../../../../components/common/Buttons/Buttons';
import { ModalContainer } from './Modal.style';
import SearchComponent from '../../../../components/common/SearchComponent';
import Checkbox from '../../../../components/common/Checkbox';
import { DictVspApi } from '../../../../api/dict-vsp';
import { downloadFile } from '../../../../utils/downloadFile';
import { toast } from 'react-toastify';

const ModalExport = ({ open, onClose, ssps = [], loading = false }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedSsps, setSelectedSsps] = useState([]);

  useEffect(() => {
    if (open) {
      setSearchTerm('');
      setSelectedSsps([]);
    }
  }, [open]);

  const filteredSsps = ssps.filter((ssp) => {
    const searchLower = searchTerm.toLowerCase();
    const title = (ssp.title || ssp.name || '').toLowerCase();
    return title.includes(searchLower);
  });

  const handleSspToggle = (sspId) => {
    setSelectedSsps((prev) => {
      if (prev.includes(sspId)) {
        return prev.filter((id) => id !== sspId);
      } else {
        return [...prev, sspId];
      }
    });
  };

  const handleExport = async () => {
    if (selectedSsps.length > 0) {
      try {
        const response = await DictVspApi.export({
          ssp_ids: selectedSsps,
        });
        await downloadFile(response, 'Справочник ВСП', 'csv');
      } catch (error) {
        console.log(error);
        toast.error('Ошибка при скачивании файла');
      }
    }
  };

  const handleClose = () => {
    if (!loading) {
      setSearchTerm('');
      setSelectedSsps([]);
      onClose();
    }
  };

  const selectedCount = selectedSsps.length;
  const totalCount = ssps.length;

  return (
    <Modal
      title="Экспорт ВСП"
      open={open}
      onClose={handleClose}
      customSize={'40'}
      actions={
        <Stack
          direction={'row'}
          justifyContent={'space-between'}
          width={'100%'}
        >
          <Typography variant="body2" color="textSecondary">
            Выбрано: {selectedCount} из {totalCount}
          </Typography>
          <Stack spacing={'.5rem'} direction={'row'}>
            <Button
              variant="grey"
              onClick={handleClose}
              style={{ height: '2.5rem' }}
              disabled={loading}
            >
              Отменить
            </Button>
            <PrimaryButton
              variant="contained"
              onClick={handleExport}
              style={{ height: '2.5rem' }}
              disabled={loading || selectedSsps.length === 0}
            >
              {loading ? 'Экспорт...' : 'Экспортировать'}
            </PrimaryButton>
          </Stack>
        </Stack>
      }
    >
      <Divider sx={{ mb: '1.5rem' }} />

      <ModalContainer maxHeight="50vh">
        <SearchComponent
          placeholder="Введите название для поиска..."
          value={searchTerm}
          onChange={setSearchTerm}
          disabled={loading}
          height="2.5rem"
        />

        {/* Список ССП с галочками */}
        {filteredSsps.length === 0 && searchTerm && (
          <Box
            sx={{
              textAlign: 'center',
              py: 4,
              color: 'text.secondary',
            }}
          >
            Ничего не найдено
          </Box>
        )}

        {filteredSsps.length === 0 && !searchTerm && (
          <Box
            sx={{
              textAlign: 'center',
              py: 4,
              color: 'text.secondary',
            }}
          >
            Нет доступных региональных филиалов
          </Box>
        )}

        <Box
          sx={{
            height: '21rem',
            overflowY: 'auto',
            border: '1px solid',
            borderColor: '#DEE2E6',
            borderRadius: '.5rem',
            padding: 1,
            backgroundColor: 'white',
          }}
        >
          {filteredSsps.map((ssp) => (
            <Box
              key={ssp.id}
              sx={{
                height: '2.3rem',
              }}
            >
              <FormControlLabel
                control={
                  <Checkbox
                    checked={selectedSsps.includes(ssp.id)}
                    onChange={() => handleSspToggle(ssp.id)}
                    disabled={loading}
                    size="16"
                  />
                }
                label={ssp.title || ssp.name || `ССП ${ssp.id}`}
                sx={{
                  width: '100%',
                  mx: 0,
                  display: 'flex',
                  flexDirection: 'row',
                  gap: '.75rem',
                }}
              />
            </Box>
          ))}
        </Box>
      </ModalContainer>

      <Divider sx={{ mt: '1.5rem' }} />
    </Modal>
  );
};

export default ModalExport;
