import { create } from "zustand";
import ChartCard from "../Chart/ChartCard";
import { Icon } from "../../tremor/Icon";
import { ChevronLeftIcon } from "@heroicons/react/20/solid";
import React, { useMemo } from "react";
import { twMerge } from "tailwind-merge";
import { useDashboard } from "../../layouts/Dashboard/useDashboard";
import { Text } from "../../tremor/Text";

export const useDrilldownModal = create<{
    open: boolean;
    widgetId?: string;
    setOpen: (open: boolean, widgetId?: string) => void;
}>((set) => ({
    open: false,
    setOpen: (op: boolean, wid?: string) => set({ open: op, widgetId: wid }),
}));

export const DrilldownModal: React.FC<{}> = ({ }) => {
    const { open, setOpen, widgetId } = useDrilldownModal();
    const { widgets } = useDashboard();

    const widget = useMemo(() => {
        if (!widgetId) return undefined;
        return widgets.find((w) => w.id === widgetId);
    }, [widgetId, widgets]);

    const goBack = () => {
        setOpen(false);
    };

    return (
        <dialog open={open}>
            <div
                className={twMerge(
                    "onvo-@container/widgetmodal onvo-h-full onvo-animate-dialogOpen onvo-w-full onvo-z-50 onvo-fixed onvo-left-0 onvo-top-0 onvo-bg-white/10 dark:onvo-bg-black/10 onvo-backdrop-blur-lg"
                )}
            >
                <div
                    key={widget?.id || ""}
                    className="onvo-relative onvo-flex onvo-flex-grow onvo-w-[80%] onvo-h-[80%] onvo-left-[10%] onvo-top-[10%] onvo-rounded-2xl onvo-flex-col onvo-foreground-color onvo-shadow-2xl"
                >
                    <div
                        className={
                            "onvo-foreground-color onvo-rounded-t-2xl onvo-w-full onvo-left-0 onvo-top-0 onvo-z-10 onvo-flex onvo-flex-row onvo-justify-start onvo-items-center onvo-gap-4 onvo-border-solid onvo-border-b onvo-border-black/10 onvo-p-2 dark:onvo-border-white/10"
                        }
                    >
                        <Icon
                            icon={ChevronLeftIcon}
                            variant="shadow"
                            className="onvo-ml-2 onvo-background-color onvo-border-solid onvo-border onvo-border-black/10 dark:onvo-border-white/10"
                            onClick={goBack}
                        />
                        <Text>Drilldown</Text>
                    </div>
                    <div className="onvo-p-4 onvo-w-full onvo-h-full">
                        {widget && <ChartCard widget={widget} />}
                    </div>
                </div>
            </div>
        </dialog>
    );
};
