import React, { useState } from 'react';

import {
  Box,
  Button,
  TextField,
  Checkbox,
  Typography,
  FormLabel,
  FormHelperText
} from '@mui/material';

import Dialog from '../common/Dialog';
import { selectUserRoles } from '../../store/usersSlice/selectors';
import { reportsError } from '../../store/reportsSlice/selectors';
import { useSelector, useDispatch } from 'react-redux';

import { makeStyles } from 'tss-react/mui';

import { SaveReportRequest, AdvancedReportsData, saveReport } from '../../store/reportsSlice/thunks';

const useStyles = makeStyles()(theme => ({
  formSection: {
    marginBottom: theme.spacing(3),
    maxWidth: 460,
    '& .MuiInputBase-input ': {
      marginBottom: 0,
      height: 32
    },
    '& .MuiSelect-root.MuiOutlinedInput-root': {
      width: 172,
      height: 40
    },
    '& .MuiSelect-icon': {
      right: 8
    },
    '& .MuiCheckbox-root': {
      padding: '0px 6px 0px 0',
      '&:hover': {
        background: 'none'
      },
      '& input[type="checkbox"]': {
        display: 'none'
      }
    },
  },
  fieldGroup: {
    display: 'flex',
    flexDirection: 'column',
    gap: theme.spacing(2.5)
  },
  divider: {
    margin: theme.spacing(4, 0)
  },
  checkboxSection: {
    display: 'flex',
    maxWidth: 350,
    flexWrap: 'wrap'
  },
  sectionTitle: {
    marginBottom: theme.spacing(1),
    fontWeight: 600
  },
  buttonIcon: {
    marginRight: theme.spacing(1)
  },
  formRow: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: theme.spacing(2)
  },
  label: {
    width: 185,
    flexShrink: 0,
    marginRight: theme.spacing(2),
    color: theme.palette.text.primary,
    fontWeight: 400,
    textAlign: 'right'
  },
  fieldContainer: {
    flex: 1,
  },
}));

const SaveReport = (
  { sql, onSave, category = 'uncategorized', onClose, open }:
  { sql: string, onSave: (report: SaveReportRequest) => void, category?: string, onClose: () => void, open: boolean }
) => {
  const dispatch = useDispatch();
  const { classes } = useStyles();

  const [formData, setFormData] = useState({
    reportTitle: '',
    isPublic: false,
    reportRoles: [] as string[],
  });
  const [errors, setErrors] = useState<{ reportTitle?: string }>({
    reportTitle: ''
  });

  const userRoles = useSelector(selectUserRoles);
  const saveReportError = useSelector(reportsError);

  const handleInputChange = (field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));

    // Clear errors when user starts typing
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: ''
      }));
    }
  };

  const validateForm = () => {
    const newErrors: { reportTitle?: string } = {};

    if (!formData.reportTitle.trim()) {
      newErrors.reportTitle = 'Report title is required.';
    } else if (!/^[A-Za-z0-9- _\-]+$/.test(formData.reportTitle)) {
      newErrors.reportTitle = 'Please use only letters, numbers, spaces, dashes and underscores';
    }

    setErrors(newErrors as { reportTitle: string; });
    return Object.keys(newErrors).length === 0;
  };

  const handleSave = async () => {
    if (validateForm()) {
      const advancedReportsData: AdvancedReportsData = {
        SQL: {
          fields: {},
          tables: {},
          filters: [],
          groupby: [],
          orderby: [],
          SQLSTRING: sql
        }
      };

      const report: SaveReportRequest = {
        report_title: 'Advanced reports',
        search_name: formData.reportTitle,
        is_public: formData.isPublic,
        sharedPermission: Object.fromEntries(formData.reportRoles.map(key => [key, true])),
        type: 'advanced',
        reportCategory: category,
        search_url: 'advancedreports',
        search_params: sql,
        overwrite: true,
        AdvancedReportsData: advancedReportsData
      }

      const result = await dispatch(saveReport(report)).unwrap();
      report.id = result[0]?.reportId ?? null;
      onSave(report);
      onClose();
    }
  };

  return (
      <Dialog
        open={open}
        fullWidth
        size={false}
        width={550}
        onClose={onClose}
        title="Save as report"
        actionButtons={
          <>
            <Button onClick={onClose} variant="outlined" color="inherit" sx={{ mr: 1 }}>
              Close
            </Button>
            <Button variant="contained" onClick={handleSave}>
              Save
            </Button>
          </>

        }
      >
        <Box className={classes.formSection}>
          <Box className={classes.formRow}>
            <Typography variant="body1" className={classes.label}>
              Report title
            </Typography>
            <Box className={classes.fieldContainer}>
              <TextField
                fullWidth
                variant="outlined"
                value={formData.reportTitle}
                onChange={(e) => handleInputChange('reportTitle', e.target.value)}
                error={!!errors.reportTitle}
                helperText={errors.reportTitle}
              />
            </Box>
          </Box>
          <Box className={classes.formRow}>
            <Typography variant="body1" className={classes.label}>
              Share report with these user roles
            </Typography>
            <Box className={classes.fieldContainer}>
              <Box className={classes.checkboxSection}>
                {userRoles.map((role) => (
                  <FormLabel key={role.id} sx={{ display: 'flex', alignItems: 'center', mr: 1 }}>
                    <Checkbox
                      checked={formData.reportRoles.includes(role.id)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          handleInputChange('reportRoles', [...formData.reportRoles, role.id]);
                        } else {
                          handleInputChange('reportRoles', formData.reportRoles.filter(r => r !== role.id));
                        }
                      }}
                    />
                    <Typography variant="body2">{role.id}</Typography>
                  </FormLabel>
                ))}
              </Box>
            </Box>
          </Box>
          <FormLabel className={classes.formRow}>
            <Typography variant="body1" className={classes.label}>
              Set as public
            </Typography>
            <Box className={classes.fieldContainer}>
              <Checkbox
                checked={formData.isPublic}
                onChange={(e) => handleInputChange('isPublic', e.target.checked)}
              />
            </Box>
          </FormLabel>
          <FormHelperText error>{saveReportError}</FormHelperText>
        </Box>
      </Dialog>
  );
};

export default SaveReport;
