import { useState, useEffect, useCallback, useDrawer} from 'react';
import { useTranslation } from 'react-i18next';
// ** React Imports
import Swal from 'sweetalert2';

// ** MUI Imports
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import CardContent from '@mui/material/CardContent';
import { Button } from '@mui/material';
import { useTheme } from '@mui/material/styles';
import { ExportVariant} from 'mdi-material-ui';
import {TextField} from '@mui/material';
import {IconButton} from '@mui/material';
import {EyePlusOutline, NoteEditOutline, AccountOffOutline} from 'mdi-material-ui';
import {Switch} from '@mui/material';
import { DataGrid } from '@mui/x-data-grid';

// ** Actions Imports
import { gettypeMoney, remove } from 'src/store/apps/typemoney';
import * as moneyService from 'src/store/apps/typemoney';

// ** Custom Components Imports
import DialogAddMoney from 'src/views/apps/opportunity/view/AddCurrencyDrawer';
import { localizedTextsMap } from '../../opportunity/components/opportunity-list';

const userStatusObj = {
  active: 'success',
  pending: 'warning',
  inactive: 'secondary',
};
 

const RowOptions = ({ row, setValues, openForm }) => {
  // ** Hooks
  // ** State
  const [anchorEl, setAnchorEl] = useState(null);
  const rowOptionsOpen = Boolean(anchorEl);
  const [Toogle , setToogle] = useState(false);
  const {t} = useTranslation()

  const handleRowOptionsClick = event => {
    setAnchorEl(event.currentTarget);
  };

  const handleRowOptionsClose = () => {
    setAnchorEl(null);
  };

  const handleDelete = async (id) => {
      Swal.fire({
        title: t('alerts.sure'),
        text:t('alerts.sureMessage'),
        icon: 'warning',
        showCancelButton: true,
        /*confirmButtonColor: '#3085d6',*/
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, deleted it!'
      }).then(async (result)=>{
          // eslint-disable-next-line no-console
          if (result.isConfirmed) {
          try {
            const response = await moneyService.remove(id);
            // console.log(response)
            // eslint-disable-next-line newline-before-return
            return response;
          } catch (e) {
            // console.log(e)
            return e;
          }
        }
      })
  };

  return (
    <>  
      <IconButton title='Edit' onClick={() => {
        setValues(row)
        openForm(true)
      }} name='edit'>
        <NoteEditOutline color='success' fontSize='inherit' />
      </IconButton>
      <IconButton onClick={()=> handleDelete(row.id)} name="disable">
        <AccountOffOutline color="error" fontSize='inherit' />
      </IconButton>
    </>
  );
};

const defaultColumns = (setValues, openForm) => {
  return [
    {
      flex: 0.15,
      field: 'moneyName',
      minWidth: 150,
      headerName: 'Money Name',
      renderCell: ({ row }) => {  
        return (
          <Typography title={row.moneyName} noWrap variant='body2'>
            {row.moneyName}
          </Typography>
        );
      },
    },
    {
      flex: 0.15,
      field: 'moneyShortName',
      minWidth: 160,
      headerName: 'Money Short Name',
      renderCell: ({ row }) => {
        return (
          <Typography title={row.moneyShortName} noWrap variant='body2'>
            {row.moneyShortName}
          </Typography>
        );
      },
    },
    {
      flex: 0.15,
      minWidth: 150,
      sortable: false,
      field: 'actions',
      headerName: 'Actions',
      renderCell: ({ row }) => {
        return <RowOptions 
          row={row} 
          setValues={setValues} 
          openForm={openForm}    
        />;
      },
    },
  ]
}

const CurrencyList = () => {
  // ** State
  const [value, setValue] = useState('');
  // const [pageSize, setPageSize] = useState(10);
  const [addMoneyOpen, setAddMoneyOpen] = useState(false);
  const [isUpdate, setIsUpdate] = useState(false);
  const [money, setMoney] = useState([]);
  const [TypeMoney, setTypeMoney] = useState();

  const handleFetchUsers = () => {
    const onSuccess = ({ data }) => {
      setMoney(data.data.items);
    };

    const onError = ({ data }) => {
      Swal.fire(t('errors.error'), t('accepted.failed'), 'error');
    };

    gettypeMoney(onSuccess, onError);
  };

  useEffect(() => {
    handleFetchUsers();
  }, []);

  const handleFilter = useCallback(val => {
    setValue(val);
  }, []);

  const toggleAddmoneyDrawer = () => {
    setTypeMoney()
    setAddMoneyOpen(!addMoneyOpen)
  }; 

  const columns = defaultColumns(setTypeMoney, setAddMoneyOpen)

  return (
    <Grid container spacing={6}>
      <Grid item xs={12}>
        <Card>
          <Box sx={{ p: 5, pb: 3, display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between' }}>
            <Typography variant='h5' align='center'>
              Type Money
            </Typography>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center' }}>
              <Button sx={{ mb: 2 }} onClick={toggleAddmoneyDrawer} variant='contained'>
                Add Type Money
              </Button>
            </Box>
          </Box>
          <Box sx={{ height: 400, width: '100%' }}>
            <DataGrid
              rows={money}
              columns={columns}
              pageSize={5}
              rowsPerPageOptions={[10, 25, 50]}
              checkboxSelection
              disableSelectionOnClick
              experimentalFeatures={{ newEditingApi: true }}
              localeText={localizedTextsMap}
            />
          </Box>
        </Card>
      </Grid>
      <DialogAddMoney
        open={addMoneyOpen}
        toggle={toggleAddmoneyDrawer}
        isUpdate={TypeMoney}
        TypeMoney={TypeMoney}
        setMoney={setMoney}
      />
    </Grid>
  );
};

export default CurrencyList;