import { useEffect, useState } from "react"
import { useCities, useReport, useReportExport } from "../hooks/swrHooks"
import { useDebounce } from "@uidotdev/usehooks"
import { ICity } from "../interfaces/fuel"
import { mutate } from "swr"
import { ActionIcon, Autocomplete, Badge, Button, CloseButton, Flex, ScrollAreaAutosize, Table } from "@mantine/core"
import { IconRefresh } from "@tabler/icons-react"

export default function Reports() {
    const [download, setDownload] = useState(false)

    const [search, setSearch] = useState<string | undefined>("")
    const debouncedSearch = useDebounce(search, 500)
    const [selectedOption, setSelectedOption] = useState<number | null>(null)
    const { cities } = useCities(10, 1, debouncedSearch)

    const { report } = useReport(selectedOption)

    const { reportExported } = useReportExport(selectedOption, download)

    const refreshReport = async () => {
        mutate(`/info/reports/${selectedOption}?to_export=false`)
    }

    useEffect(() => {
        if (selectedOption && reportExported && download) {
            const url = window.URL.createObjectURL(reportExported)
            const link = document.createElement('a')
            link.href = url
            link.setAttribute('download', 'report.xlsx')
            document.body.appendChild(link);
            link.click();
            link.remove();
            setDownload(false)
        }
    }, [selectedOption, reportExported, download])

    const exportReport = async () => {
        setDownload(true)
    }

    return (
        <ScrollAreaAutosize w={'100%'} h={'100%'} p='sm'>
            <Flex component="form" gap={'sm'}>
                {/* <SearchableSelect /> */}
                <Autocomplete
                    placeholder="Населенный пункт"
                    flex={'1'}
                    data={cities ? cities.map((item: ICity) => ({ label: item.name, value: item.id.toString() })) : []}
                    onSelect={(e) => console.log(e.currentTarget.value)}
                    onChange={(value) => setSearch(value)}
                    onOptionSubmit={(value) => setSelectedOption(Number(value))}
                    rightSection={
                        search !== '' && (
                            <CloseButton
                                size="sm"
                                onMouseDown={(event) => event.preventDefault()}
                                onClick={() => {
                                    setSearch('')
                                    setSelectedOption(null)
                                }}
                                aria-label="Clear value"
                            />
                        )
                    }
                    value={search}
                />

                <ActionIcon size='auto' variant='transparent' onClick={() => refreshReport()}>
                    <IconRefresh />
                </ActionIcon>

                <Button disabled={!selectedOption} onClick={() => exportReport()}>
                    Экспорт
                </Button>
            </Flex>

            {report &&
                <Table highlightOnHover>
                    <Table.Thead>
                        <Table.Tr>
                            {[
                                { field: 'id', headerName: '№', width: 70 },
                                ...Object.keys(report).map(key => ({
                                    field: key,
                                    headerName: key.charAt(0).toUpperCase() + key.slice(1),
                                    width: 150
                                }))
                            ].map(column => (
                                <Table.Th key={column.headerName}>{column.headerName}</Table.Th>
                            ))}
                        </Table.Tr>
                    </Table.Thead>
                    <Table.Tbody>
                        {[...new Set(Object.keys(report).flatMap(key => Object.keys(report[key])))].map(id => {
                            const row: any = { id: Number(id) };
                            Object.keys(report).forEach(key => {
                                row[key] = report[key][id];
                            });
                            return (<Table.Tr key={row.id}>
                                {[
                                    { field: 'id', headerName: '№', width: 70 },
                                    ...Object.keys(report).map(key => ({
                                        field: key,
                                        headerName: key.charAt(0).toUpperCase() + key.slice(1),
                                        width: 150
                                    }))
                                ].map(column => {
                                    if (column.field === 'Активность') {
                                        return (
                                            row['Активность'] ? (
                                                <Table.Td key={`${row.id}-${column.headerName}`}>
                                                    <Badge fullWidth variant="light">
                                                        Активен
                                                    </Badge>
                                                </Table.Td>

                                            ) : (
                                                <Table.Td key={`${row.id}-${column.headerName}`}>
                                                    <Badge color="gray" fullWidth variant="light">
                                                        Отключен
                                                    </Badge>
                                                </Table.Td>
                                            )
                                        )
                                    }
                                    return (
                                        <Table.Td key={`${row.id}-${column.headerName}`}>{row[column.field]}</Table.Td>
                                    )
                                })}
                            </Table.Tr>)
                        })}
                    </Table.Tbody>
                </Table>
            }
        </ScrollAreaAutosize>
    )
}