import { FC, useState } from "react";
import ServicesTable from "../components/ServicesTable/ServicesTable.tsx";
import PageBlock from "../../../components/PageBlock/PageBlock.tsx";
import styles from "./ServicesPage.module.css";
import { Button, Flex, Popover, rem, Switch } from "@mantine/core";
import ServiceTypeSegmentedControl, {
    ServicesTab,
} from "../components/ServiceTypeSegmentedControl/ServiceTypeSegmentedControl.tsx";
import ServicesKitsTable from "../components/ServicesKitsTable/ServicesKitsTable.tsx";
import ServicePriceCategoryTable from "../components/ServicePriceCategoryTable/ServicePriceCategoryTable.tsx";
import useServicesState from "../hooks/useServicesState.tsx";
import useServicesKitsState from "../hooks/useServicesKitsState.tsx";
import useServicePriceCategoryState from "../hooks/useServicePriceCategoryState.tsx";
import { ObjectStateToTableProps } from "../../../types/utils.ts";
import { IconDownload, IconFileExcel, IconFileTypePdf } from "@tabler/icons-react";
import FileSaver from "file-saver";
import { getCurrentDateTimeForFilename } from "../../../shared/lib/date.ts";

export const ServicesPage: FC = () => {
    const [serviceType, setServiceType] = useState(ServicesTab.DEAL_SERVICE);
    const [isEditMode, setIsEditMode] = useState(false);
    const {
        services,
        onServiceDelete,
        onServiceUpdate,
        onCreateClick,
        onCreateCategoryClick,
    } = useServicesState();
    const { servicesKits, onKitUpdate, onKitCreateClick } =
        useServicesKitsState();
    const {
        onCreateClick: onCreatePriceCategoryClick,
        ...priceCategoryRestProps
    } = useServicePriceCategoryState();
    const getBody = () => {
        switch (serviceType) {
            case ServicesTab.SERVICES_KITS:
                return (
                    <ServicesKitsTable
                        items={servicesKits}
                        onChange={onKitUpdate}
                    />
                );
            case ServicesTab.DEAL_SERVICE:
            case ServicesTab.PRODUCT_SERVICE: {
                const servicesOrdered = services.filter(service => service.serviceType === serviceType).sort((a, b) => {
                        if (serviceType === ServicesTab.DEAL_SERVICE) {
                            return a.category.dealServiceRank.localeCompare(b.category.dealServiceRank);
                        }
                        return a.category.productServiceRank.localeCompare(b.category.productServiceRank);
                    },
                );
                return (
                    <ServicesTable
                        onDelete={onServiceDelete}
                        onChange={onServiceUpdate}
                        items={servicesOrdered}
                        serviceType={serviceType}
                        editMode={isEditMode}
                    />
                );
            }
            case ServicesTab.SERVICES_PRICE_CATEGORIES:
                return (
                    <ServicePriceCategoryTable
                        {...ObjectStateToTableProps(priceCategoryRestProps)}
                    />
                );
        }
    };
    const getControls = () => {
        switch (serviceType) {
            case ServicesTab.SERVICES_KITS:
                return (
                    <Button
                        onClick={onKitCreateClick}
                        variant={"default"}>
                        Создать набор
                    </Button>
                );
            case ServicesTab.DEAL_SERVICE:
            case ServicesTab.PRODUCT_SERVICE:
                return (
                    <Flex align={"center"} gap={rem(10)}>
                        <div style={{
                            display: "grid",
                            gridAutoFlow: "column",
                            gridAutoColumns: "1fr",
                            width: "max-content",
                            gap: rem(10),
                        }}>

                            <Button
                                onClick={onCreateClick}
                                variant={"default"}>
                                Создать услугу
                            </Button>
                            <Button

                                onClick={onCreateCategoryClick}
                                variant={"default"}>
                                Создать категорию
                            </Button>
                            <Popover withArrow shadow={"md"}>
                                <Popover.Target>

                                    <Button
                                        leftSection={<IconDownload />}
                                        variant={"default"}>
                                        Скачать
                                    </Button>
                                </Popover.Target>
                                <Popover.Dropdown>
                                    <Flex direction={"column"} gap={rem(10)}>
                                        <Button
                                            onClick={onDownloadPdfClick}
                                            variant={"default"}
                                            leftSection={<IconFileTypePdf />}
                                        >
                                            В формате PDF
                                        </Button>
                                        <Button
                                            onClick={onDownloadExcelClick}
                                            variant={"default"}
                                            leftSection={<IconFileExcel />}
                                        >
                                            В формате Excel
                                        </Button>
                                    </Flex>
                                </Popover.Dropdown>
                            </Popover>

                        </div>

                        <Switch

                            variant={"default"}
                            label={"Режим редактирования"}
                            checked={isEditMode}
                            onChange={() => setIsEditMode(!isEditMode)}
                        />
                    </Flex>
                );
            case ServicesTab.SERVICES_PRICE_CATEGORIES:
                return (
                    <Button
                        variant={"default"}
                        onClick={() => {
                            if (onCreatePriceCategoryClick) {
                                onCreatePriceCategoryClick();
                            }
                        }}>
                        Создать категорию
                    </Button>
                );
        }
    };

    const onDownloadPdfClick = () => {
        const date = getCurrentDateTimeForFilename();
        FileSaver.saveAs(`${import.meta.env.VITE_API_URL}/service/export-list/pdf`,
            `прайс_лист_${date}.pdf`,
        );
    };
    const onDownloadExcelClick = () => {
        const date = getCurrentDateTimeForFilename();
        FileSaver.saveAs(`${import.meta.env.VITE_API_URL}/service/export-list/excel`,
            `прайс_лист_${date}.xlsx`,
        );
    };
    return (
        <div className={styles["container"]}>
            <PageBlock>
                <div className={styles["top-panel"]}>
                    {getControls()}
                    <ServiceTypeSegmentedControl
                        className={styles["top-panel-last-item"]}
                        value={serviceType.toString()}
                        onChange={event => setServiceType(parseInt(event))}
                    />
                </div>
            </PageBlock>
            <PageBlock>{getBody()}</PageBlock>
        </div>
    );
};
