import PropTypes from 'prop-types';
import React, { useState, useEffect, useCallback } from 'react';
import { Link as RouterLink } from 'react-router-dom';

// material-ui
import { Box, Link, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material';

import * as EgovNet from 'api/egovFetch';
import {itemIdxByPage} from "../../../utils/calc";
import {format} from "date-fns";

function createData(trackingNo, title, dt, name) {
    return { trackingNo, title, dt, name };
}

function descendingComparator(a, b, orderBy) {
    if (b[orderBy] < a[orderBy]) {
        return -1;
    }
    if (b[orderBy] > a[orderBy]) {
        return 1;
    }
    return 0;
}

function getComparator(order, orderBy) {
    return order === 'desc' ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy);
}

function stableSort(array, comparator) {
    const stabilizedThis = array.map((el, index) => [el, index]);
    stabilizedThis.sort((a, b) => {
        const order = comparator(a[0], b[0]);
        if (order !== 0) {
            return order;
        }
        return a[1] - b[1];
    });
    return stabilizedThis.map((el) => el[0]);
}

// ==============================|| ORDER TABLE - HEADER CELL ||============================== //

const headCells = [
    {
        id: 'trackingNo',
        align: 'left',
        disablePadding: false,
        label: 'No.'
    },
    {
        id: 'title',
        align: 'center',
        disablePadding: true,
        label: '제목'
    },
    {
        id: 'dt',
        align: 'center',
        disablePadding: false,
        label: '작성일자'
    },
    {
        id: 'name',
        align: 'center',
        disablePadding: false,
        label: '작성자'
    },
];

// ==============================|| ORDER TABLE - HEADER ||============================== //

function OrderTableHead({ order, orderBy }) {
    return (
        <TableHead>
            <TableRow>
                {headCells.map((headCell) => (
                    <TableCell
                        key={headCell.id}
                        align={headCell.align}
                        padding={headCell.disablePadding ? 'none' : 'normal'}
                        sortDirection={orderBy === headCell.id ? order : false}
                        sx={{ width:headCell.id === 'trackingNo' ? '10%' :
                                    headCell.id === 'title' ? '50%' :
                                    headCell.id === 'dt' ? '25%' : '15%', }}
                    >
                        {headCell.label}
                    </TableCell>
                ))}
            </TableRow>
        </TableHead>
    );
}

OrderTableHead.propTypes = {
    order: PropTypes.string,
    orderBy: PropTypes.string
};

// ==============================|| ORDER TABLE ||============================== //

export default function OrderTable() {
    const [order] = useState('asc');
    const [orderBy] = useState('trackingNo');
    const [selected] = useState([]);

    const [listTag, setListTag] = useState([]);

    const retrieveList = useCallback(() => {
        // console.groupCollapsed("EgovAdminUsageList.retrieveList()");

        const retrieveListURL = '/admin/dashboard/question';

        const requestOptions = {
            method: "POST",
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify()
        }

        EgovNet.requestFetch(retrieveListURL,
            requestOptions,
            (resp) => {
                let mutListTag = [];

                const resultCnt = parseInt(resp.result.QuestionList.length);
                // const currentPageNo = 1;            // resp.result.paginationInfo.currentPageNo;
                // const pageSize = resultCnt;         // resp.result.paginationInfo.pageSize;

                // 리스트 항목 구성
                if (resultCnt === 0) {
                    mutListTag.push(createData('', '데이터가 없습니다.', '', ''));
                } else {
                    resp.result.QuestionList.forEach(function (item, index) {
                        if (index === 0) mutListTag = []; // 목록 초기화
                        // const listIdx = itemIdxByPage(resultCnt, currentPageNo, pageSize, index);

                        mutListTag.push(
                            createData(index+1, item[0], item[1], item[2]),
                        );
                    });
                }
                setListTag(mutListTag);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
        // console.groupEnd("EgovAdminPrivacyList.retrieveList()");
        // eslint-disable-next-line react-hooks/exhaustive-deps
    },[listTag]);

    useEffect(() => {
        retrieveList();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // const rows = [listTag
    //     createData(1, '흙막이 가시설 띠장 전단 설계시 플래지 ...', '2024-02-04 13:22', '홍길동'),
    //     createData(2, '콘크리트 벽체 설계기준 적용 유무 확인 ...', '2024-02-04 13:22', '홍길동'),
    //     createData(3, '한중콘크리트 초기양생 관련', '2024-02-04 13:22', '홍길동'),
    //     createData(4, 'KDS 21 30 00 : 2022가설흙...', '2024-02-04 13:22', '홍길동'),
    //     createData(5, '인테리어필름 시방서 관련', '2024-02-04 13:22', '홍길동'),
    //     createData(6, '고온고압증기양생기포콘크리트(ALC) 구조', '2024-02-04 13:22', '홍길동'),
    //     createData(7, '지반을 최저등급으로 가정한 경우란', '2024-02-04 13:22', '홍길동')
    // ];

    const isSelected = (trackingNo) => selected.indexOf(trackingNo) !== -1;

    return (
        <Box>
            <TableContainer
                sx={{
                    width: '100%',
                    overflowX: 'auto',
                    position: 'relative',
                    display: 'block',
                    maxWidth: '100%',
                    '& td, & th': { whiteSpace: 'nowrap' }
                }}
            >
                <Table
                    aria-labelledby="tableTitle"
                    sx={{
                        '& .MuiTableCell-root:first-of-type': {
                            pl: 2
                        },
                        '& .MuiTableCell-root:last-of-type': {
                            pr: 0
                        }
                    }}
                >
                    <OrderTableHead order={order} orderBy={orderBy} />
                    <TableBody>
                        {stableSort(listTag, getComparator(order, orderBy)).map((row, index) => {
                            const isItemSelected = isSelected(row.trackingNo);
                            const labelId = `enhanced-table-checkbox-${index}`;

                            return (
                                <TableRow
                                    hover
                                    role="checkbox"
                                    sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                                    aria-checked={isItemSelected}
                                    tabIndex={-1}
                                    key={row.trackingNo}
                                    selected={isItemSelected}
                                >
                                    <TableCell width="10%" align="left" component="th" id={labelId} scope="row">{row.trackingNo}</TableCell>
                                    <TableCell width="50%" align="left"><Link color="secondary" component={RouterLink} to="" sx={{ overflow: 'hidden', textOverflow: 'ellipsis', display: 'block'}}>{row.title}</Link></TableCell>
                                    <TableCell width="25%" align="center">{row.dt? format(row.dt, "yyyy-MM-dd HH:mm") : ""}</TableCell>
                                    <TableCell width="15%" align="center">{row.name}</TableCell>
                                </TableRow>
                            );
                        })}
                    </TableBody>
                </Table>
            </TableContainer>
        </Box>
    );
}
