// Copyright 2018 Northern.tech AS
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
import { useState } from 'react';

import { accordionClasses, accordionDetailsClasses, accordionSummaryClasses } from '@mui/material';
import { makeStyles } from 'tss-react/mui';

import { DEVICE_STATES, canAccess } from '@northern.tech/store/constants';
import { customSort } from '@northern.tech/utils/helpers';

import AuthsetListItem from './AuthSetListItem';

const fiveColumns = '0.5fr 1fr 1.5fr 2fr 2fr';
const useStyles = makeStyles()(theme => ({
  authsets: {
    [`.columnHeader, .${accordionSummaryClasses.root}, .${accordionSummaryClasses.content}`]: {
      cursor: 'default'
    },
    [`.header, .body .${accordionSummaryClasses.content}`]: {
      display: 'grid',
      gridColumnGap: theme.spacing(2),
      gridTemplateColumns: '0.5fr 1fr 1.5fr 2fr 2fr 2fr',
      alignItems: 'center',
      margin: 0
    }
  },
  accordion: {
    borderInline: 'none',
    '&:before': { display: 'none' },
    '&:hover': { borderColor: theme.palette.divider },
    '&:not(:last-of-type)': { borderBottom: 'none' },
    [`&.${accordionClasses.expanded}`]: { margin: 0 },
    [`.${accordionSummaryClasses.root}`]: {
      height: 'auto',
      minHeight: theme.spacing(5.25),
      [`&.${accordionSummaryClasses.expanded}`]: { height: 'auto', minHeight: theme.spacing(5.25) }
    },
    [`.${accordionSummaryClasses.content}`]: {
      [`&.${accordionSummaryClasses.expanded}`]: { margin: 0 }
    },
    [`.columns-5 .${accordionSummaryClasses.content}`]: {
      gridTemplateColumns: fiveColumns
    },
    [`.${accordionDetailsClasses.root}`]: { flexDirection: 'row', minHeight: theme.spacing(5.25) }
  },
  confirmMessage: { fontWeight: 500 },
  fitContent: { width: 'fit-content' },
  header: {
    padding: theme.spacing(2),
    '&.columns-5': { gridTemplateColumns: fiveColumns }
  }
}));

export const defaultColumns = [
  { title: '', canAccess },
  { title: 'Status', canAccess },
  { title: 'Device tier', canAccess },
  { title: 'Public key', canAccess },
  { title: 'Time of request', canAccess },
  { title: 'Actions', canAccess: ({ userCapabilities: { canManageDevices } }) => canManageDevices }
];

export const AuthsetList = ({ device, listRef, userCapabilities, ...remainingProps }) => {
  const [expandRow, setExpandRow] = useState();
  const { classes } = useStyles();
  const { auth_sets: authsets = [], status = DEVICE_STATES.accepted } = device;

  const availableColumns = defaultColumns.filter(column => column.canAccess({ userCapabilities }));

  const groupedAuthsets = authsets.reduce(
    // for each authset compare the device status and if it matches authset status, put it in correct list
    (accu, authset) => {
      if (authset.status === status) {
        accu.active.push(authset);
      } else if (authset.status === DEVICE_STATES.pending) {
        accu.pending.push(authset);
      } else {
        accu.inactive.push(authset);
      }
      return accu;
    },
    { active: [], inactive: [], pending: [] }
  );

  const orderedAuthsets = [
    ...groupedAuthsets.pending.sort(customSort(true, 'ts')),
    ...groupedAuthsets.active.sort(customSort(true, 'ts')),
    ...groupedAuthsets.inactive.sort(customSort(true, 'ts'))
  ];

  return (
    <div className={`authsets ${classes.authsets}`}>
      <div className={`header columns-${availableColumns.length} ${classes.header}`}>
        {availableColumns.map(({ title: headerName }, index) => (
          <div className="columnHeader" key={`columnHeader-${index}`}>
            {headerName}
          </div>
        ))}
      </div>
      <div className="body relative" ref={listRef}>
        {orderedAuthsets.map(authset => (
          <AuthsetListItem
            authset={authset}
            classes={classes}
            columns={availableColumns}
            device={device}
            isExpanded={expandRow === authset.id}
            key={`authset-${authset.id}`}
            onExpand={setExpandRow}
            userCapabilities={userCapabilities}
            {...remainingProps}
          />
        ))}
      </div>
    </div>
  );
};

export default AuthsetList;
