import Typography from "@mui/material/Typography";
import {useEffect, useState} from "react";
import {
    Avatar,
    Card,
    CardContent,
    CardHeader,
    CircularProgress,
    Collapse, Divider,
    FormControl,
    MenuItem, Pagination,
    Select
} from "@mui/material";
import Box from "@mui/material/Box";
import {backURL} from "../../actions/PathDB";
import userDefault from "../../img/header/userDefault.png";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import {connect} from "react-redux";
import {actionUserCount, actionUserFind} from "../../actions/ActionUserFind";
import {timeCalc} from "../ProductPage/timeCalc";

const ClientsCart = ({_id, login, nick, avatar, createdAt, acl}) => {
    const ItemAccordion = ({text, size='h6'}) => {
        return (
            <Typography
                variant={size}
                color='#616161'
                letterSpacing='1px'
            >
                {text}
            </Typography>
        )
    }
    const [expanded, setExpanded] = useState(false);
    const handleExpandClick = () => {
        setExpanded(!expanded);
    };
    return (
        <Card sx={{boxShadow: 'none', border: '1px solid #616161', marginBottom: '20px'}}>
            <Box display='flex' justifyContent='space-between' alignItems='center' padding='0 20px 0 10px'
                 style={{cursor:'pointer'}}
                 onClick={handleExpandClick}
            >
                <CardHeader
                    avatar={
                        avatar ?
                            <Avatar alt="User" src={avatar?.url && backURL + '/' + avatar.url}/> :
                            <Avatar alt="User" src={userDefault}/>
                    }
                    title={`Login: ${login || 'login'}  ${nick ? '| Nick: ' + nick : ''} ${(acl && Array.isArray(acl) && acl.length > 1) ? '| Status: ' + acl.slice(1, acl.length).toString() : ''}`}
                    subheader={timeCalc(+createdAt || 0)}
                />
                <ExpandMoreIcon />
            </Box>
            <Collapse in={expanded} timeout="auto" unmountOnExit>
                <CardContent>
                    <ItemAccordion text={`Login: ${login || 'login'}`}/>
                    <ItemAccordion size={'body1'} text={`${nick ? 'Nick: ' + nick : ''}`}/>
                    <ItemAccordion size={'body1'} text={`${(acl && Array.isArray(acl) && acl.length > 1) ? 'Status: ' + acl.slice(1, acl.length).toString() : ''}`}/>
                    <ItemAccordion size={'body1'} text={'Created at: '+timeCalc(+createdAt || 0)}/>
                </CardContent>
            </Collapse>
        </Card>
    )
}
const Clients = ({usersArr, usersCount, getAllClients, getCountUser}) => {
    const itemsPerPage = 100
    const [page, setPage] = useState(1)
    const [sortValue, setSortValue] = useState('login')
    const [sortVector, setSortVector] = useState(1)
    const [sortSelect, setSortSelect] = useState(0)

    useEffect(() => {
        if (!usersArr && page === 1) getAllClients()
        if (!usersCount) getCountUser()
        else {
            setCount(Math.ceil(+usersCount?.payload / itemsPerPage))
        }
    }, [getAllClients, getCountUser, page, sortValue, sortVector, usersArr, usersCount])

    const [count, setCount] = useState(1)
    const handleChange = (event, value) => {
        setPage(value);
        getAllClients(itemsPerPage * value, sortValue, sortVector);
    }
    const handleChangeSelect = (event) => {
        setSortSelect(event.target.value);
        if (event.target.value === 0){
            setSortValue('login')
            setSortVector(1)
            getAllClients(itemsPerPage*page, sortValue, sortVector)
        }
        else if (event.target.value === 1){
            setSortValue('login')
            setSortVector(-1)
            getAllClients(itemsPerPage*page, sortValue, sortVector)
        }
        else if (event.target.value === 2){
            setSortValue('login')
            setSortVector(1)
            getAllClients(itemsPerPage*page, sortValue, sortVector)
        }
        else if (event.target.value === 3){
            setSortValue('createdAt')
            setSortVector(1)
            getAllClients(itemsPerPage*page, sortValue, sortVector)
        }
        else if (event.target.value === 4){
            setSortValue('createdAt')
            setSortVector(-1)
            getAllClients(itemsPerPage*page, sortValue, sortVector)
        }
    }

    return (
        <>
            <Box marginBottom='20px' width='100%' display='flex' justifyContent='space-between' alignItems='center'>
                {usersCount?.payload  && <Typography variant='h6' letterSpacing='2px'>Total clients: {usersCount.payload}</Typography>}
                <FormControl variant="standard">
                    <Select
                        labelId="demo-simple-select-label"
                        id="demo-simple-select"
                        value={sortSelect}
                        label="Sort"
                        onChange={handleChangeSelect}
                        sx={{textTransform: 'uppercase', color: '#616161'}}
                    >
                        <MenuItem value={0}>Default sort</MenuItem>
                        <MenuItem value={1}>Sort by login: ascending</MenuItem>
                        <MenuItem value={2}>Sort by login: descending</MenuItem>
                        <MenuItem value={3}>Sort by created at: ascending</MenuItem>
                        <MenuItem value={4}>Sort by created at: descending</MenuItem>
                    </Select>
                </FormControl>
            </Box>
            {!usersArr || !usersArr?.payload ?
                <Box sx={{height: '100%', width: '100%', display: 'flex', justifyContent:'center', alignItems:'center'}}><CircularProgress color="inherit"/></Box>:
                Array.isArray(usersArr.payload) && usersArr.payload.map(item => {
                    return <ClientsCart key={item?._id} _id={item?._id || ''} login={item?.login || 'not found'} nick={item?.nick || ''} createdAt={item?.createdAt || ''} avatar={item?.avatar} acl={item?.acl}/>
                })
            }
            <Box width='100%' flexGrow='0'>
                <Divider sx={{margin: '20px'}}/>
                <Box display='flex' justifyContent='center' width='100%'>
                    <Pagination
                        count={count}
                        page={page}
                        onChange={handleChange}
                        defaultPage={1}
                        color="primary"
                        size="large"
                        showFirstButton
                        showLastButton
                    />
                </Box>
            </Box>
        </>
    )
}
export const CClients = connect(state => ({usersArr: state.promise['allUsers'], usersCount: state.promise['usersCount']}), {getAllClients: actionUserFind, getCountUser: actionUserCount})(Clients)
