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 { IconRefresh } from "@tabler/icons-react"
import { Badge, Button, Combobox, createTableColumn, DataGrid, DataGridBody, DataGridCell, DataGridHeader, DataGridHeaderCell, DataGridRow, Option, TableCellLayout, TableColumnDefinition } from "@fluentui/react-components"

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 (
        <div style={{
            width: '100%',
            height: '100%',
            padding: '1rem'
        }}>
            <form style={{
                display: 'flex',
                gap: '0.5rem'
            }}>
                {/* <SearchableSelect /> */}
                <Combobox clearable placeholder="Населенный пункт" onOptionSelect={(_, data) => {
                    setSelectedOption(Number(data.optionValue))
                    setSearch(data.optionText ?? "")
                }} value={search} onChange={(e) => setSearch(e.currentTarget.value)}>
                    {cities && Array.isArray(cities) && cities.map((item: ICity) => (
                        <Option key={item.id} value={item.id.toString()}>
                            {item.name}
                        </Option>
                    ))}
                </Combobox>

                <Button icon={<IconRefresh />} appearance="subtle" onClick={() => refreshReport()}>

                </Button>

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

            <div style={{
                display: 'flex',
                width: '100%',
                overflow: 'auto'
            }}>
                {report &&
                    <ReportTable report={report} />
                }
            </div>

        </div>
    )
}


interface ReportType {
    [key: string]: Record<string, unknown>;
}

function ReportTable({ report }: { report: ReportType }) {
    // Build column definitions
    const columns: TableColumnDefinition<any>[] = [
        createTableColumn({
            columnId: "id",
            renderHeaderCell: () => {
                return "№"
            },
            renderCell: (item) => <TableCellLayout>{item.id}</TableCellLayout>,
        }),
        ...Object.keys(report).map((key) =>
            createTableColumn({
                columnId: key,
                renderHeaderCell: () => {
                    return key.charAt(0).toUpperCase() + key.slice(1)
                },
                renderCell: (item: any) => {
                    if (key === "Активность") {
                        return (
                            <TableCellLayout>
                                {item["Активность"] ? (
                                    <Badge color="success">Активен</Badge>
                                ) : (
                                    <Badge color="danger">Отключен</Badge>
                                )}
                            </TableCellLayout>
                        );
                    }
                    return <TableCellLayout>{item[key] as string}</TableCellLayout>;
                },
            })
        ),
    ];

    // Build rows from report (same logic you used)
    const items = [...new Set(Object.keys(report).flatMap((key) => Object.keys(report[key])))]
        .map((id) => {
            const row: Record<string, unknown> = { id: Number(id) };
            Object.keys(report).forEach((key) => {
                row[key] = report[key][id];
            });
            return row;
        });

    return (
        <DataGrid
            items={items}
            columns={columns}
            sortable
            focusMode='row_unstable'
            resizableColumns
            resizableColumnsOptions={{ autoFitColumns: false }}
            size='extra-small'

        >
            <DataGridHeader>
                <DataGridRow>
                    {({ renderHeaderCell }) => (
                        <DataGridHeaderCell>{renderHeaderCell()}</DataGridHeaderCell>
                    )}
                </DataGridRow>
            </DataGridHeader>

            <DataGridBody>
                {({ item, rowId }) => (
                    <DataGridRow key={rowId}>
                        {({ renderCell }) => <DataGridCell>{renderCell(item)}</DataGridCell>}
                    </DataGridRow>
                )}
            </DataGridBody>
        </DataGrid>
    );
}
