/* eslint-disable react/prop-types */
import React, { useState } from 'react';
import AddRounded from '@mui/icons-material/AddRounded';
import DeleteIcon from '@mui/icons-material/Delete';

import { ALIAS, MAIN } from '../constants';

import { formatKeywordsForGrid, formatKeywordsForUpdate, formatLanguages } from '../helpers/formatObjects';
import { isAliasDialogButtonDisabled } from '../helpers/validations';

import {
  Button,
  DataGridPro,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Stack,
  ToggleButton,
  ToggleButtonGroup,
} from '@/mui/components';

import styles from './AliasDialog.module.scss';

function AliasDialog(props) {
  const [data, setData] = useState(() =>
    formatKeywordsForGrid(props.row.keywords).map((keyword, index) => ({ ...keyword, id: `${keyword.id}${index}` })),
  );

  const formattedLanguages = formatLanguages(props.languages);
  const isDisabled = isAliasDialogButtonDisabled(data);

  const handleStatusChange = (row, value) => {
    if (!value) return;
    if (value === ALIAS && data.some((item) => item.lang === row.lang && item.status === MAIN)) return;

    const tempData = [...data];

    tempData.forEach((item) => {
      if (item.id === row.id) {
        // eslint-disable-next-line no-param-reassign
        item.status = value;
      } else if (item.lang === row.lang && item.status === MAIN) {
        // eslint-disable-next-line no-param-reassign
        item.status = ALIAS;
      }
    });

    setData(tempData);
  };

  const handleRowUpdate = (row) => {
    const tempData = window.structuredClone(data);

    const index = tempData.findIndex((item) => item.id === row.id);
    tempData[index] = row;

    const hasMainLangRow = tempData.some(
      (item) => item.lang === row.lang && item.status === MAIN && item.id !== row.id,
    );
    if (hasMainLangRow) tempData[index].status = ALIAS;

    setData(tempData);

    return row;
  };

  const handleDeleteRow = (rowId) => {
    const tempData = data.filter((item) => item.id !== rowId);

    setData(tempData);
  };

  const handleAddRow = () => {
    const tempData = [...data];

    tempData.push({
      id: `${Date.now()}`,
      lang: 'EN',
      value: '',
      status: ALIAS,
    });

    setData(tempData);
  };

  const handleSave = () => {
    const formattedKeywords = formatKeywordsForUpdate(data);

    props.handleRowUpdate({ ...props.row, keywords: formattedKeywords });
  };

  console.log(data, 'data');

  return (
    <Dialog open={!!props.row} onClose={props.handleClose}>
      <DialogTitle onClose={props.handleClose}>Aliases</DialogTitle>
      <DialogContent>
        <div className={styles.AliasButton}>
          <Button
            onClick={handleAddRow}
            variant="outlined"
            size="small"
            color="primary"
            startIcon={<AddRounded />}
            disabled={isDisabled}
          >
            Alias
          </Button>
        </div>
        <DataGridPro
          size="large"
          hideFooter
          disableRowSelectionOnClick
          processRowUpdate={handleRowUpdate}
          rows={data}
          columns={[
            {
              field: 'value',
              headerName: 'Name',
              width: 180,
              editable: true,
              sortable: false,
              filterable: false,
              disableColumnMenu: true,
            },
            {
              field: 'lang',
              headerName: 'Language',
              width: 160,
              cellType: 'singleSelect',
              valueOptions: props.languages,
              sortable: false,
              editable: true,
              filterable: false,
              disableColumnMenu: true,
              renderCellValue: ({ value }) => formattedLanguages[value],
            },
            {
              field: 'status',
              headerName: 'Status',
              width: 120,
              sortable: false,
              filterable: false,
              disableColumnMenu: true,
              renderCellValue: (cell) => (
                <ToggleButtonGroup
                  exclusive
                  color="primary"
                  size="small"
                  shape="rounded"
                  value={cell.value}
                  onChange={(_, value) => handleStatusChange(cell.row, value)}
                >
                  <ToggleButton value={ALIAS}>Alias</ToggleButton>
                  <ToggleButton value={MAIN}>Main</ToggleButton>
                </ToggleButtonGroup>
              ),
            },
            {
              field: 'id',
              headerName: 'Alias',
              align: 'center',
              width: 90,
              sortable: false,
              filterable: false,
              disableColumnMenu: true,
              renderCellValue: (params) => (
                <Stack fullWidth>
                  <IconButton onClick={() => handleDeleteRow(params.id)}>
                    <DeleteIcon color="error" />
                  </IconButton>
                </Stack>
              ),
            },
          ]}
        />
      </DialogContent>
      <DialogActions>
        <Button size="small" variant="outlined" color="primary" onClick={props.handleClose}>
          Cancel
        </Button>
        <Button size="small" variant="contained" color="primary" onClick={handleSave} disabled={isDisabled}>
          Apply
        </Button>
      </DialogActions>
    </Dialog>
  );
}

export default AliasDialog;
