import { useState, useEffect, useCallback, useDrawer} from 'react';
import { useTranslation } from 'react-i18next';
// ** React Imports
import Swal from 'sweetalert2';
import Link from 'next/link';
// ** 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';
// ** Actions Imports
import { DataGrid } from '@mui/x-data-grid';
import CustomChip from 'src/@core/components/mui/chip';
import CustomAvatar from 'src/@core/components/mui/avatar';
// ** Custom Components Imports
import DialogAddPayment from 'src/views/apps/opportunity/view/AddPaymentDrawer';
import { getPayForms, remove } from 'src/store/apps/payforms';
import * as paymentService from 'src/store/apps/payforms';
import Translations from 'src/layouts/components/Translations';
import { localizedTextsMap } from './opportunity-list';


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

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

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

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

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

const defaultColumns = (setValues, openForm, deletePayment) => {
  return [
    {
      flex: 0.25,
      field: 'payName',
      minWidth: 250,
      headerName: <Translations text='general.payment' />,
      renderCell: ({ row }) => {  
        return (
          <Typography title={row.payName} noWrap variant='body2'>
            {row.payName}
          </Typography>
        );
      },
    },
    {
      flex: 0.15,
      minWidth: 150,
      sortable: false,
      field: 'actions',
      headerName: <Translations text='general.actions' />,
      renderCell: ({ row }) => {
        return <RowOptions 
          row={row} 
          setValues={setValues} 
          openForm={openForm}    
          deletePayment={deletePayment}
        />;
      },
    },
  ]
}

const PaymentTermsList = () => {
  // ** State
  const [value, setValue] = useState('');
  // const [pageSize, setPageSize] = useState(10);
  const [addPaymentOpen, setAddPaymentOpen] = useState(false);
  const [isUpdate, setIsUpdate] = useState(false);
  const [payment, setPayment] = useState([]);
  const [payForm, setPayForm] = useState();

  const { t } = useTranslation();

  const handleFetchUsers = () => {
    const onSuccess = ({ data }) => {
      const { data: payment } = data;
      setPayment(data.data.results.items);
    };

    const onError = ({ data }) => {
      Swal.fire('Error', '¡Petición fallida!', 'error');
    };

    getPayForms(onSuccess, onError);
  };

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

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

  const toggleAddpaymentDrawer = () => {
    setPayForm()
    setAddPaymentOpen(!addPaymentOpen)
  }; 
  
  const deletePayment = id => {
    remove(
      id,
      ({ data }) => {
        Success(t('accepted.remove'))
        setPayment(payment => {
          return payment.filter(item => item.id !== id);
        });
      },
      ({ status, data }) => {
        if (status == 404 && data?.message == 'category not found') {
          Swal.fire('Error', '¡La categoria no esta registrada!', 'error');
        } else {
          Swal.fire('Error', '¡Peticion Fallida!', 'error');
        }
      },
    );
  };

  const columns = defaultColumns(setPayForm, setAddPaymentOpen, deletePayment);

  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'>
              <Translations text='title.terms' />
            </Typography>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center' }}>
              <Button sx={{ mb: 2 }} onClick={toggleAddpaymentDrawer} variant='contained'>
                <Translations text='add.terms' />
              </Button>
            </Box>
          </Box>
          <Box sx={{ height: 400, width: '100%' }}>
            <DataGrid
              rows={payment}
              columns={columns}
              pageSize={5}
              rowsPerPageOptions={[10, 25, 50]}
              checkboxSelection
              disableSelectionOnClick
              experimentalFeatures={{ newEditingApi: true }}
              localeText={localizedTextsMap}
              disableColumnFilter
              disableColumnMenu
            />
          </Box>
        </Card>
      </Grid>
      <DialogAddPayment
        open={addPaymentOpen}
        toggle={toggleAddpaymentDrawer}
        isUpdate={payForm}
        payform={payForm}
        setPayment={setPayment}
      />
    </Grid>
  );
};

export default PaymentTermsList;