// ** Next Import
import Link from 'next/link';
import { useState } from 'react';

// ** 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 { styled } from '@mui/material/styles';
import CustomChip from 'src/@core/components/mui/chip';
import IconButton from '@mui/material/IconButton';

// ** Icons
import EyePlusOutline from 'mdi-material-ui/EyePlusOutline';

// ** Hooks Imports
import { useTranslation } from 'react-i18next';

// ** Views Imports
import { DataGrid } from '@mui/x-data-grid';
import { localizedTextsMap } from 'src/views/apps/opportunity/components/opportunity-list';

// ** Components
import Translations from 'src/layouts/components/Translations';
import CustomAvatar from 'src/@core/components/mui/avatar';
import { getInitials } from 'src/@core/utils/get-initials';
import CustomColumnMenu from 'src/components/custom-column-menu';

const statusLabel = {
  0: <Translations text='logbook.open' />,
  1: <Translations text='logbook.finalized' />,
  2: <Translations text='logbook.reviewed' />,
  3: <Translations text='logbook.pending' />,
};

const statusColor = {
  0: 'success',
  1: 'warning',
  2: 'info',
  3: 'error',
};

// ** Styled component for the link for the avatar with image
const AvatarWithImageLink = styled(Link)(({ theme }) => ({
  marginRight: theme.spacing(3),
}));

// ** Styled component for the link for the avatar without image
const AvatarWithoutImageLink = styled(Link)(({ theme }) => ({
  textDecoration: 'none',
  marginRight: theme.spacing(3),
}));

const renderClient = row => {
  if (row.avatar) {
    return (
      // <AvatarWithImageLink href={`/apps/user/view/${row.id}`}>
      <CustomAvatar src={row.avatar} sx={{ mr: 3, width: 30, height: 30 }} />
      // </AvatarWithImageLink>
    );
  } else {
    return (
      // <AvatarWithoutImageLink href={`/apps/user/view/${row.id}`}>
      <CustomAvatar
        skin='light'
        color={row.avatarColor || 'primary'}
        sx={{ mr: 3, width: 30, height: 30, fontSize: '.875rem' }}
      >
        {getInitials(row.fullName ? row.fullName : 'John Doe')}
      </CustomAvatar>
      // </AvatarWithoutImageLink>
    );
  }
};

const defaultColumns = (total, t, openForm) => {
  return [
    {
      flex: 0.25,
      minWidth: 230,
      field: 'fullName',
      // headerName: <Translations text={'general.user'} />,
      headerName: `${t('general.user')} (${total})`,
      renderCell: ({ row }) => {
        const { id, name } = row.user;

        return (
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            {renderClient(row.user)}
            <Box
              sx={{
                display: 'flex',
                alignItems: 'flex-start',
                flexDirection: 'column',
              }}
            >
              {/* <Link href={`/apps/user/view/${id}`} passHref> */}
              <Typography
                noWrap
                component='a'
                variant='body2'
                title={name}
                sx={{
                  fontWeight: 600,
                  color: 'text.primary',
                  textDecoration: 'none',
                }}
              >
                {name}
              </Typography>
              {/* </Link> */}
            </Box>
          </Box>
        );
      },
    },
    {
      flex: 0.25,
      field: 'status',
      minWidth: 250,
      // sortable: false,
      // headerName: <Translations text={'login.email'} />,
      headerName: t('general.status'),
      renderCell: ({ row }) => {
        return (
          <CustomChip
            skin='light'
            size='large'
            label={statusLabel[row?.status]}
            color={statusColor[row?.status]}
            sx={{
              textTransform: 'capitalize',
              padding: '0.5rem',
              margin: '0 0.5rem',
            }}
          />
        );
      },
    },
    {
      flex: 0.25,
      field: 'date',
      minWidth: 80,
      // headerName: <Translations text={'general.id'} />,
      headerName: t('general.date'),
      renderCell: ({ row }) => {
        const date = new Date(row.date);

        return (
          <Typography title={date.toLocaleString()} noWrap variant='body2'>
            {date.toLocaleString()}
          </Typography>
        );
      },
    },
    {
      flex: 0.25,
      field: 'quantity',
      minWidth: 80,
      // headerName: <Translations text={'general.id'} />,
      headerName: t('general.total'),
      sortable: false,
      renderCell: ({ row }) => {
        return (
          <Typography title={row.totalActivities} noWrap variant='body2'>
            {row.totalActivities}
          </Typography>
        );
      },
    },
    {
      flex: 0.25,
      minWidth: 100,
      sortable: false,
      field: 'actions',
      headerName: t('general.actions'),
      renderCell: ({ row }) => {
        return (
          <IconButton
            title='Edit'
            onClick={() => {
              openForm(row.id, row.user.name);
            }}
            name='edit'
          >
            <EyePlusOutline color='info' fontSize='inherit' />
          </IconButton>
        );
      },
    },
  ];
};

const TableReport = ({ items, total, setPage, pageSize, setPageSize, openForm, setSort }) => {
  const { t } = useTranslation();

  const [columnVisibility, setColumnVisibility] = useState({
    user: true,
    status: true,
    date: true,
    quantity: true,
  });

  const columns = defaultColumns(total, t, openForm);

  const onRowClick = params => {
    openForm(params.row.id , params.row.user.name);
  };

  return (
    <Grid container spacing={6}>
      <Grid item xs={12}>
        <Box sx={{ width: '100%' }}>
          <DataGrid
            autoHeight
            rows={items}
            checkboxSelection
            pageSize={pageSize}
            disableSelectionOnClick
            columns={columns}
            rowCount={total}
            sortingMode='server'
            paginationMode='server'
            rowsPerPageOptions={[10, 25, 50]}
            onPageChange={newPage => setPage(newPage + 1)}
            onPageSizeChange={newPageSize => setPageSize(newPageSize)}
            // hideFooterPagination
            localeText={localizedTextsMap}
            components={{
              ColumnMenu: CustomColumnMenu,
            }}
            onRowClick={onRowClick}
            columnVisibilityModel={columnVisibility}
            onColumnVisibilityModelChange={newModel => {
              setColumnVisibility(newModel);
            }}
            onSortModelChange={sortModel => {
              setSort(sortModel);
            }}
          />
        </Box>
      </Grid>
    </Grid>
  );
};

export default TableReport;
