import React, {ReactNode, useState} from 'react';
import {useMediaQuery} from "react-responsive";
import ListHeadColumn from "./ListHeader/ListHeadColumn";
import ListView from "../../SVG/ViewStyleList";
import CardView from "../../SVG/ViewStyleCard";
import EmptyList from "./EmptyList";
import {PaginationMetadata} from "../../../models/Axios";
import Pagination from "./Pagination/Pagination";
import csv from '../../../assets/images/CSV.svg'
import xlsx from '../../../assets/images/xls.svg'
import DownloadXlsx from "../../SVG/DownloadXlsx";
import DownloadCsv from "../../SVG/DownloadCsv";
import ListRow from "./ListRow";
export type Order = 'ASC' | 'DESC'
type DuaListProps = {
    children: ReactNode[]//list row
    orderParams?: {
        order: Order
        order_by: string
        setOrder: (order_by: string, order: Order) => void
    }
    pagination?: {
        meta: PaginationMetadata
        setPage: (n: number) => void
        setPerPage?: (n: number) => void
        lastFetched?: any
    }
    exportList?: (type: 'csv' | 'xlsx') => void
    listBreakpoint?: string
    customClass?:string
}
const toggleOrderBy: Record<Order, Order> = {
    'ASC': 'DESC',
    'DESC': 'ASC'
}
/**
 *  This Component is Wrapper for lists.
 *  It offers pagination, ordering the list, exporting as csv/xlsx
 *  Check the DuaListProps interface and some list for example on how to use it
 *
 *  You need to map the list you want to render and wrap it with this component
 *
 *  For each column use one of the different types of ListColumns depending on what you want
 *  Some IMPORTANT things for the COLUMNS are
 *  You need to ,probably, define the flex parameter manually to make it work properly on all view ports
 *  The headers of the list are created automatically from the LABEL property of each column
 *  Add the ORDERABLE property to a column to allow the user to order base on that column
 *
 */
const DuaList = ({children, customClass, orderParams, pagination, exportList, listBreakpoint = '1399'}: DuaListProps) => {
    const isMobileDevice = useMediaQuery({query: `(max-width: ${listBreakpoint}px)`})
    const [listView, setListView] = useState(true);
    if (children.length < 1) {
        return (
            <EmptyList>
                Δεν βρέθηκε περιεχόμενο.
            </EmptyList>
        )
    }
    const isCardView = !listView || isMobileDevice
    const firstRow = children[0]
    // @ts-ignore
    const columns = firstRow.props.children
    const headerCols = columns.map((col: any, index: number) => {
            if (col?.props && col.props.flex) {
                const type = col.props.type ?? ''
                const flex = col.props.flex
                const label = col.props.label ?? ''
                const align = col.props.align ?? 'left'
                const orderable = col.props.orderable
                let onClick
                let activeOrder
                if (orderable && orderParams) {
                    onClick = () => {
                        orderParams.setOrder(
                            orderable,
                            orderable === orderParams.order_by ? toggleOrderBy[orderParams.order] : 'ASC'
                        )
                    }
                    // @ts-ignore
                    activeOrder = (orderable === orderParams.order_by) ? orderParams.order : null
                }
                return (
                    <ListHeadColumn
                        type={type}
                        key={index}
                        flex={flex}
                        align={align}
                        onClick={onClick}
                        activeOrder={activeOrder}
                        orderable={orderable}
                    >
                        {(label && label !== '') && label}
                    </ListHeadColumn>
                )
            }
        }
    )
    const colClass =
        customClass === 'button-view'
            ? 'col-12 col-sm-12 col-md-6 col-xl-4 col-xxl-3'
            : `col-12 ${isCardView ? 'col-sm-6 col-lg-4' : ''}`;
    return (
        <>
            <div className={`dua-list ${customClass} ${isCardView ? 'card-view' : 'list-view'}`}>
                {
                    <>
                        <div className="list-head">
                            {
                                isCardView || headerCols
                            }
                            {
                                exportList && <div
                                    className={`download-xlsx ${customClass}`}
                                    onClick={() => exportList("xlsx")}
                                >
                                    <DownloadXlsx
                                        color={'var(--generic-block-border-hover)'}
                                        colorText={'var(--app-background)'}
                                    />
                                    {/*<img src={xlsx}/>*/}
                                </div>
                            }
                            {
                                exportList && <div className={`download-csv ${customClass}`} onClick={() => exportList('csv')}>
                                    <DownloadCsv
                                        color={'var(--generic-block-border-hover)'}
                                        colorText={'var(--app-background)'}
                                    />
                                    {/*<img src={csv}*/}
                                </div>
                            }
                            {
                                isMobileDevice ||
                                <div
                                    className={`d-flex justify-content-end change-view ${customClass} ${!isMobileDevice && "display"}`}>
                                    <button disabled={listView} onClick={() => setListView(true)}>
                                        <ListView
                                            // hoverColor={'#040059'}
                                            color={listView ? '#1A73E8' : '#707070'}/>
                                    </button>
                                    <button disabled={!listView} onClick={() => setListView(false)}>
                                        <CardView
                                            // hoverColor={'#040059'}
                                            color={listView ? '#707070' : '#1A73E8'}/>
                                    </button>
                                </div>
                            }
                        </div>
                        <div className={`row ${customClass == 'button-view' ? 'g-5' : 'g-3'} mb-4`}>
                            {
                                children.map(c => {
                                        return (<div
                                            // @ts-ignore
                                            key={c.props._key}
                                            className={colClass}>
                                            {c}
                                        </div>)
                                    }
                                )
                            }
                        </div>
                    </>
                }
            </div>
            {
                pagination &&
                <div className={'d-flex'}>
                    <Pagination
                        lastFetched={pagination.lastFetched}
                        totalRecords={pagination.meta.total_count}
                        currentPage={Number(pagination.meta.page)}
                        totalPages={pagination.meta.page_count}
                        setPage={pagination.setPage}
                        setPerPage={pagination.setPerPage}
                        perPage={Number(pagination.meta.page_size)? Number(pagination.meta.page_size) : Number(pagination.meta.per_page) }
                    />
                </div>
            }
        </>
    );
}
export default DuaList
