import { Badge } from "../../tremor/Badge";
import { Label, Metric } from "../../tremor/Text";
import { Button } from "../../tremor/Button";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useDashboard } from "../../layouts/Dashboard/useDashboard";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import {
  ArrowDownTrayIcon,
  ArrowLeftIcon,
  ArrowPathIcon,
  ArrowRightIcon,
  Bars3Icon,
  ClockIcon,
  DocumentChartBarIcon,
  FunnelIcon,
  PencilIcon,
  PhotoIcon,
  PlusIcon,
  PresentationChartBarIcon,
  TrashIcon,
} from "@heroicons/react/24/outline";
import { toast } from "sonner";
import { useBackend } from "../../layouts/Wrapper";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuIconWrapper,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "../../tremor/DropdownMenu";
import { useTheme } from "../../layouts/Dashboard/useTheme";
import { Popover, PopoverContent, PopoverTrigger } from "../../tremor/Popover";
import { FilterBar } from "../FilterBar";
import { useAutomationsModal } from "../AutomationsModal/useAutomationsModal";
import { Tooltip } from "../../tremor/Tooltip";
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import { Text } from "../../tremor/Text";
import { EyeIcon, EyeSlashIcon } from "@heroicons/react/20/solid";
import { Icon } from "../../tremor/Icon";

dayjs.extend(relativeTime);

function formatList(items: string[]) {
  if (items.length === 0) return <></>;
  if (items.length === 1) return <Badge variant="neutral" className="!onvo-py-0 onvo-mb-1">{items[0]}</Badge>;
  if (items.length === 2) return <><Badge variant="neutral" className="!onvo-py-0 onvo-mb-1">{items[0]}</Badge> and <Badge variant="neutral" className="!onvo-py-0 onvo-mb-1">{items[1]}</Badge></>;

  return <>{items.slice(0, -1).map(a => <Badge key={a} variant="neutral" className="!onvo-py-0 onvo-mb-1 onvo-mr-1">{a}</Badge>)}and <Badge key={items[items.length - 1]} variant="neutral" className="!onvo-py-0 onvo-mb-1">{items[items.length - 1]}</Badge></>;
}

export const LastUpdatedBadge: React.FC<{}> = ({ }) => {
  const { dashboard, refreshing } = useDashboard();
  const [key, setKey] = useState(new Date().toISOString());
  const [lastUpdated, setLastUpdated] = useState(dashboard?.last_updated_at || dashboard?.created_at);

  useEffect(() => {
    let interval = setInterval(() => {
      setKey(new Date().toISOString());
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, []);

  useEffect(() => {
    if (dashboard) {
      setLastUpdated(dashboard.last_updated_at || dashboard.created_at);
    }
  }, [dashboard]);

  if (refreshing) {
    return (
      <Badge key="refreshing-badge" className="onvo-last-updated-badge onvo-justify-center onvo-items-center">
        <ArrowPathIcon className="onvo-size-3 onvo-animate-spin onvo-w-full" />
        Auto refreshing...
      </Badge>
    );
  }

  return (
    <Tooltip side="bottom" align="end" content={"The dashboard was last updated " + dayjs(lastUpdated).fromNow()}>
      <Badge key={key} className="onvo-last-updated-badge onvo-justify-center onvo-items-center onvo-w-full">
        <ArrowPathIcon className="onvo-size-3" />
        {dayjs(lastUpdated).fromNow()}
      </Badge>
    </Tooltip>
  );
};

export const DashboardHeaderTab: React.FC<{ item: { label: string, id: number } }> = ({ item }) => {
  const [editing, setEditing] = useState(false);
  const [title, setTitle] = useState(item.label);
  const componentRef = useRef<HTMLDivElement>(null);

  const { backend, adminMode } = useBackend();
  const { dashboard, setDashboard, widgets } = useDashboard();
  const { containerRef } = useBackend();

  const updateDashboard = () => {
    setEditing(false);
    if (dashboard) {
      const newTabs = dashboard.tabs.map((tab) => {
        if (tab.id === item.id) {
          return {
            ...tab,
            label: title,
          }
        }
        return tab;
      });
      const newDashboard = {
        ...dashboard,
        tabs: newTabs,
      };

      setDashboard(newDashboard);
      backend?.dashboards.update(dashboard.id, newDashboard);
    }
  }


  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (componentRef.current && !componentRef.current.contains(event.target as Node)) {
        updateDashboard();
      }
    };

    if (editing) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [editing]);


  const moveTab = (position: "left" | "right") => {
    if (dashboard) {
      const currentIndex = dashboard.tabs.findIndex(tab => tab.id === item.id);
      if (currentIndex === -1) return;

      const newTabs = [...dashboard.tabs];
      let newIndex;

      if (position === "left") {
        newIndex = Math.max(0, currentIndex - 1);
      } else {
        newIndex = Math.min(newTabs.length - 1, currentIndex + 1);
      }

      // Only move if the new position is different
      if (newIndex !== currentIndex) {
        // Remove the tab from its current position
        const [movedTab] = newTabs.splice(currentIndex, 1);
        // Insert it at the new position
        newTabs.splice(newIndex, 0, movedTab);

        const newDashboard = {
          ...dashboard,
          tabs: newTabs,
        };

        setDashboard(newDashboard);
        backend?.dashboards.update(dashboard.id, newDashboard);
      }
    }
  }

  const deleteTab = () => {
    if (dashboard) {

      const widgetsExist = widgets?.some(widget => widget.tab === item.id);

      if (widgetsExist) {
        toast.error("You cannot delete a tab with widgets, delete all the widgets in the tab and try again");
        return;
      }

      const newTabs = dashboard.tabs.filter((tab) => tab.id !== item.id);
      const newDashboard = {
        ...dashboard,
        tabs: newTabs,
      };

      setDashboard(newDashboard);
      backend?.dashboards.update(dashboard.id, newDashboard);
    }
  }

  const editable = adminMode || dashboard?.settings?.can_edit_tabs;

  return (<div
    ref={componentRef}
    onDoubleClick={() => {
      if (editable) {
        setEditing(true);
      }
    }} >
    {editing ? <input
      className="onvo-text-sm onvo-rounded-md onvo-px-1 onvo-py-1 onvo-border-blue-500"
      value={title}
      onKeyUp={(e) => {
        if (e.key === "Enter") {
          updateDashboard();
        }
      }}
      onChange={(e) => {
        setTitle(e.target.value);
      }} /> :
      <div
        className="onvo-flex onvo-flex-row onvo-items-center onvo-gap-1">
        <Text>
          {item.label}
        </Text>
        {editable && (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <div className="onvo-cursor-pointer hover:onvo-bg-black/10 dark:hover:onvo-bg-white/10 onvo-rounded-full onvo-size-5 onvo-flex onvo-items-center onvo-justify-center onvo-transition-all">
                <svg className="onvo-size-2 onvo-fill-slate-500 dark:onvo-fill-slate-400" fill="#000000" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" viewBox="0 0 96.154 96.154" xmlSpace="preserve"><g id="SVGRepo_bgCarrier" strokeWidth="0"></g><g id="SVGRepo_tracerCarrier" strokeLinecap="round" strokeLinejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path d="M0.561,20.971l45.951,57.605c0.76,0.951,2.367,0.951,3.127,0l45.956-57.609c0.547-0.689,0.709-1.716,0.414-2.61 c-0.061-0.187-0.129-0.33-0.186-0.437c-0.351-0.65-1.025-1.056-1.765-1.056H2.093c-0.736,0-1.414,0.405-1.762,1.056 c-0.059,0.109-0.127,0.253-0.184,0.426C-0.15,19.251,0.011,20.28,0.561,20.971z"></path> </g> </g></svg>
              </div>
            </DropdownMenuTrigger>
            <DropdownMenuContent side="bottom" align="start" container={containerRef?.current} className="!onvo-backdrop-blur-lg onvo-min-w-56 onvo-z-50">

              <div className="onvo-w-full onvo-absolute onvo-top-0 onvo-left-0 onvo-right-0 onvo-bottom-0 onvo-foreground-color onvo-opacity-50 onvo-rounded-lg -onvo-z-10"></div>

              <DropdownMenuGroup>
                <DropdownMenuItem onClick={() => setEditing(true)}>
                  <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                    <DropdownMenuIconWrapper>
                      <PencilIcon className="onvo-size-4 onvo-text-inherit" />
                    </DropdownMenuIconWrapper>
                    <span>Rename</span>
                  </span>
                </DropdownMenuItem>
              </DropdownMenuGroup>
              <DropdownMenuSeparator />
              <DropdownMenuGroup>
                <DropdownMenuItem onClick={() => moveTab("left")}>
                  <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                    <DropdownMenuIconWrapper>
                      <ArrowLeftIcon className="onvo-size-4 onvo-text-inherit" />
                    </DropdownMenuIconWrapper>
                    <span>Move Left</span>
                  </span>
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => moveTab("right")}>
                  <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                    <DropdownMenuIconWrapper>
                      <ArrowRightIcon className="onvo-size-4 onvo-text-inherit" />
                    </DropdownMenuIconWrapper>
                    <span>Move Right</span>
                  </span>
                </DropdownMenuItem>
              </DropdownMenuGroup>
              <DropdownMenuSeparator />
              <DropdownMenuGroup>
                <DropdownMenuItem onClick={() => deleteTab()}>
                  <span className="onvo-flex onvo-items-center onvo-gap-x-2 onvo-text-red-500">
                    <DropdownMenuIconWrapper>
                      <TrashIcon className="onvo-size-4 onvo-text-red-500 onvo-text-inherit" />
                    </DropdownMenuIconWrapper>
                    <span>Delete</span>
                  </span>
                </DropdownMenuItem>
              </DropdownMenuGroup>
            </DropdownMenuContent>
          </DropdownMenu>
        )}
      </div>}

  </div >)
}

export const DashboardHeader: React.FC<{
  children?: React.ReactNode;
  className?: string;
  variant?: "default" | "pdf" | "pptx"
}> = ({ children, className, variant }) => {
  const headerRef = useRef<HTMLElement>(null);
  const [headerHeight, setHeaderHeight] = useState<number>(0);

  // Effect to measure and update header height
  useEffect(() => {
    if (headerRef.current) {
      const resizeObserver = new ResizeObserver(entries => {
        for (const entry of entries) {
          setHeaderHeight(entry.contentRect.height);
        }
      });

      resizeObserver.observe(headerRef.current);
      return () => resizeObserver.disconnect();
    }
  }, []);
  const { setOpen } = useAutomationsModal();
  const { dashboard, tab, setTab, progress, refreshing, setDashboard } = useDashboard();
  const theme = useTheme();
  const { backend, adminMode, containerRef } = useBackend();

  const exportDashboard = useCallback(
    (format: "csv" | "xlsx" | "pdf" | "png" | "jpeg" | "pptx") => {
      if (!backend || !dashboard) {
        return;
      }
      toast.promise(
        async () => {
          return backend.dashboard(dashboard.id).export(format, theme, tab, (event) => {
            // console.log(event);
          });
        },
        {
          loading: `Exporting dashboard as ${format}...`,
          success: async (output: any) => {
            try {
              // Get the file URL, replacing host.docker.internal with localhost if needed
              const fileUrl = output.url.replace("host.docker.internal", "localhost");

              // Create a link element
              const link = document.createElement('a');
              link.href = fileUrl;
              link.download = output.fileName || `export.${format}`; // Set the filename
              link.style.display = 'none';

              // Add to document, click and remove
              document.body.appendChild(link);
              link.click();

              // Clean up
              setTimeout(() => {
                document.body.removeChild(link);
              }, 100);
            } catch (error) {
              console.error('Download failed:', error);
              toast.error('Download failed. Please try again.');
            }
            return "Dashboard exported successfully";
          },
          error: (e: any) => {
            return "Failed to export dashboard: " + e.message;
          },
        }
      );
    },
    [dashboard, backend, tab, theme]
  );

  const ImageDownloadEnabled = useMemo(() => {
    if (dashboard?.settings && dashboard.settings.disable_download_images)
      return false;
    return true;
  }, [dashboard]);


  const DocumentDownloadEnabled = useMemo(() => {
    if (dashboard?.settings && dashboard.settings.disable_download_documents)
      return false;
    return true;
  }, [dashboard]);

  const ReportDownloadEnabled = useMemo(() => {
    if (dashboard?.settings && dashboard.settings.disable_download_reports)
      return false;
    return true;
  }, [dashboard]);

  const filtered = useMemo(() => {
    let filters = dashboard?.filters || [];
    if (filters.length === 0) return [];
    let results = [] as string[];
    for (let filter of filters) {
      if (filter.type === "text" && filter.options.length !== filter.values.length) {
        results.push(filter.label);
      }
      if (filter.type === "number" && (filter.options[0] !== filter.values[0] || filter.options[1] !== filter.values[1])) {
        results.push(filter.label);
      }
      if (filter.type === "date" && (filter.options[0] !== filter.values[0] || filter.options[1] !== filter.values[1])) {
        results.push(filter.label);
      }
    }

    return results;

  }, [dashboard])


  const border_radius = useMemo(() => {
    return dashboard?.settings?.widget_border_radius === undefined
      ? 16
      : dashboard?.settings?.widget_border_radius;
  }, [dashboard]);

  const padding = useMemo(() => {
    return dashboard?.settings?.widget_padding === undefined
      ? 10
      : dashboard?.settings?.widget_padding;
  }, [dashboard]);


  if (dashboard?.settings?.hide_header && !adminMode) return <></>;

  const DownloadDropdown = (<DropdownMenu modal={false}>
    <Tooltip content="Download" side="bottom">
      <DropdownMenuTrigger asChild>
        <Button className="onvo-foreground-color onvo-border-black/10 dark:onvo-border-white/10" variant="secondary" disabled={!dashboard}>
          <ArrowDownTrayIcon className="onvo-size-4" />
        </Button>
      </DropdownMenuTrigger>
    </Tooltip>
    <DropdownMenuContent side="bottom" align="end" container={containerRef?.current} className="onvo-min-w-56 onvo-backdrop-blur-lg onvo-border-black/10 dark:onvo-border-white/10">
      <div className="onvo-w-full onvo-absolute onvo-top-0 onvo-left-0 onvo-right-0 onvo-bottom-0 onvo-foreground-color onvo-opacity-50 onvo-rounded-lg -onvo-z-10"></div>

      {ReportDownloadEnabled && (
        <>
          <DropdownMenuLabel>Report formats</DropdownMenuLabel>
          <DropdownMenuGroup>
            <DropdownMenuItem onClick={() => exportDashboard("xlsx")}>
              <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                <DocumentChartBarIcon className="onvo-size-5" />
                <span>Excel</span>
              </span>
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => exportDashboard("csv")}>
              <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                <DropdownMenuIconWrapper>
                  <DocumentChartBarIcon className="onvo-size-5" />
                </DropdownMenuIconWrapper>
                <span>CSV</span>
              </span>
            </DropdownMenuItem>
          </DropdownMenuGroup>
        </>
      )}

      {DocumentDownloadEnabled && ReportDownloadEnabled && (
        <DropdownMenuSeparator className="onvo-border-black/10 dark:onvo-border-white/10" />
      )}
      {DocumentDownloadEnabled && (
        <>
          <DropdownMenuLabel>Document formats</DropdownMenuLabel>
          <DropdownMenuGroup>
            <DropdownMenuItem onClick={() => exportDashboard("pdf")}>
              <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                <DocumentChartBarIcon className="onvo-size-5" />
                <span>PDF</span>
              </span>
            </DropdownMenuItem>

            <DropdownMenuItem onClick={() => exportDashboard("pptx")}>
              <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                <PresentationChartBarIcon className="onvo-size-5" />
                <span>Powerpoint</span>
              </span>
            </DropdownMenuItem>
          </DropdownMenuGroup>
        </>
      )}
      {ImageDownloadEnabled && (DocumentDownloadEnabled || ReportDownloadEnabled) && (
        <DropdownMenuSeparator className="onvo-border-black/10 dark:onvo-border-white/10" />
      )}
      {ImageDownloadEnabled && (
        <>
          <DropdownMenuLabel>Image formats</DropdownMenuLabel>
          <DropdownMenuGroup>
            <DropdownMenuItem onClick={() => exportDashboard("png")}>
              <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                <DropdownMenuIconWrapper>
                  <PhotoIcon className="onvo-size-5" />
                </DropdownMenuIconWrapper>
                <span>PNG</span>
              </span>
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => exportDashboard("jpeg")}>
              <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                <DropdownMenuIconWrapper>
                  <PhotoIcon className="onvo-size-5" />
                </DropdownMenuIconWrapper>
                <span>JPEG</span>
              </span>
            </DropdownMenuItem>
          </DropdownMenuGroup>
        </>
      )}
    </DropdownMenuContent>
  </DropdownMenu>);

  if (variant === "pdf" || variant === "pptx") {
    return (
      <>
        <div style={{ height: headerHeight }} className="onvo-w-full onvo-flex-shrink-0"></div>
        <section
          ref={headerRef}
          className={`onvo-@container/onvo-dashboard-header onvo-leading-tight onvo-bg-slate-900 onvo-dashboard-header onvo-absolute onvo-z-50 onvo-top-0 onvo-left-0 onvo-right-0 ${className ? className : ""}`}
        >
          <div className="onvo-flex onvo-py-2 onvo-px-5 onvo-flex-row onvo-justify-between onvo-items-center">
            {(dashboard?.tabs || []).filter(a => !a.hidden).length > 1 ? (
              <div className="onvo-flex onvo-flex-row onvo-gap-2">
                {(dashboard?.tabs || []).filter(a => !a.hidden).map(a => (
                  <Button key={a.id + ""} variant={a.id === tab ? "light" : "secondary"} onClick={() => {
                    setTab(a.id);
                  }}>{a.label}</Button>))}
              </div>) : <div></div>}
            {(ImageDownloadEnabled || ReportDownloadEnabled || DocumentDownloadEnabled) &&
              DownloadDropdown
            }
          </div>
        </section>
      </>
    )
  }

  const reorder = (list: any[], startIndex: number, endIndex: number) => {
    const result = Array.from(list);
    const [removed] = result.splice(startIndex, 1);
    result.splice(endIndex, 0, removed);

    return result;
  };

  const onDragEnd = (result: any) => {
    if (!result.destination || !dashboard) {
      return;
    }
    const items = reorder(
      dashboard?.tabs || [],
      result.source.index,
      result.destination.index
    );

    const updatedDashboard = {
      ...dashboard,
      tabs: items
    };

    setDashboard(updatedDashboard);
    backend?.dashboards.update(dashboard.id, updatedDashboard)
  };

  const addTab = () => {
    if (!dashboard) return;
    if (!dashboard.tabs || dashboard.tabs.length === 0) {
      const newTabs = [{
        id: 0,
        label: "New tab"
      }];
      const newDashboard = {
        ...dashboard,
        tabs: newTabs
      };
      setDashboard(newDashboard);
      backend?.dashboards.update(dashboard.id, newDashboard)
    } else {
      const maxTab = Math.max(...dashboard.tabs.map(a => a.id), 0) + 1;
      const newTabs = [...dashboard.tabs, {
        id: maxTab,
        label: "New tab"
      }];
      const newDashboard = {
        ...dashboard,
        tabs: newTabs
      };
      setDashboard(newDashboard);
      backend?.dashboards.update(dashboard.id, newDashboard)
    }
  }

  const hideTab = (tabId: number, hidden: boolean) => {
    if (!dashboard) return;
    const newTabs = dashboard.tabs.map(a => {
      if (a.id === tabId) {
        return {
          ...a,
          hidden
        }
      }
      return a;
    });
    const newDashboard = {
      ...dashboard,
      tabs: newTabs
    };
    setDashboard(newDashboard);
    backend?.dashboards.update(dashboard.id, newDashboard)
  }

  const editable = adminMode || dashboard?.settings?.can_edit_tabs;
  return (
    <>
      <div style={{
        height: (headerHeight) + "px",
        marginTop: padding + "px",
        marginLeft: padding + "px",
        width: "calc(100% - " + (2 * padding) + "px)",
      }}
        className="onvo-w-full onvo-flex-shrink-0"></div>


      <section
        ref={headerRef}
        className={`onvo-@container/onvo-dashboard-header onvo-leading-tight onvo-dashboard-header onvo-backdrop-blur-lg onvo-absolute onvo-z-50 onvo-shadow-sm onvo-border-solid onvo-border onvo-rounded-2xl onvo-border-black/10 dark:onvo-border-white/10 ${className ? className : ""}`}
        style={{
          borderRadius: border_radius + "px",
          left: padding + "px",
          right: padding + "px",
          top: padding + "px",
        }}
      >
        <div className="onvo-w-full -onvo-z-10 onvo-absolute onvo-top-0 onvo-left-0 onvo-right-0 onvo-bottom-0 onvo-foreground-color onvo-opacity-50" style={{ borderRadius: border_radius + "px" }}></div>

        <main className="onvo-mx-auto onvo-px-4 onvo-pt-3 onvo-pb-0 onvo-z-10 onvo-relative onvo-flex onvo-flex-col onvo-items-start onvo-justify-between onvo-gap-2 @lg/onvo-dashboard-header:onvo-flex-row @lg/onvo-dashboard-header:onvo-items-start">

          <div className="onvo-flex-grow onvo-flex onvo-flex-row onvo-gap-3">
            {dashboard && dashboard.thumbnail && dashboard.thumbnail.trim() !== "" && (
              <img
                className={
                  "onvo-rounded-lg onvo-size-11 @lg/onvo-dashboard-header:onvo-size-14 onvo-bg-slate-50 onvo-object-contain dark:onvo-bg-slate-900 onvo-flex-shrink-0 onvo-border onvo-border-slate-200 dark:onvo-border-slate-700"
                }
                src={dashboard.thumbnail}
                alt={dashboard.title} />)}
            <div className="onvo-flex-grow">
              {dashboard ? (
                <>
                  <Metric className="onvo-dashboard-header-title !onvo-font-semibold dark:onvo-text-white onvo-text-black onvo-font-override onvo-text-xl">
                    {dashboard?.title || ""}
                  </Metric>
                  <Label className="onvo-dashboard-header-description !onvo-font-normal onvo-font-override">
                    {dashboard?.description || ""}
                  </Label>
                </>
              ) : (
                <div className="onvo-w-3/5 onvo-animate-pulse">
                  <div className="onvo-mb-2 onvo-h-6 onvo-w-4/5 onvo-rounded-md onvo-bg-gray-100 dark:onvo-bg-gray-700" />
                  <div className="onvo-h-4 onvo-w-2/5 onvo-rounded-md onvo-bg-gray-100 dark:onvo-bg-gray-700" />
                </div>
              )}</div>
          </div>
          <div className="onvo-gap-2 onvo-flex onvo-flex-row @lg/onvo-dashboard-header:onvo-flex-col onvo-justify-between onvo-w-full @lg/onvo-dashboard-header:onvo-w-auto">

            <LastUpdatedBadge />
            <div className="onvo-flex onvo-flex-row onvo-gap-2 onvo-justify-end">
              {dashboard?.settings?.filters && dashboard.filters.length > 0 && (
                <Popover>
                  <Tooltip content="Filters" side="bottom">
                    <PopoverTrigger asChild>

                      <Button className="onvo-relative onvo-foreground-color onvo-border-black/10 dark:onvo-border-white/10" variant="secondary"
                      >
                        <FunnelIcon className="onvo-size-4" />
                        {filtered?.length > 0 && (
                          <>
                            <div className="onvo-size-2"></div>

                            <Tooltip side="bottom" sideOffset={20} content={<p className="onvo-text-xs">The dashboard is currently filtered by {formatList(filtered)}</p>}>
                              <div className="onvo-absolute -onvo-top-2 -onvo-right-2 onvo-rounded-full onvo-bg-red-500 onvo-text-white onvo-text-xs onvo-text-center onvo-font-bold onvo-size-5 onvo-flex onvo-items-center onvo-justify-center">
                                {filtered?.length}
                              </div>
                            </Tooltip>
                          </>
                        )}
                      </Button>
                    </PopoverTrigger>
                  </Tooltip>
                  <PopoverContent side="bottom" align="end" onInteractOutside={e => e.preventDefault()} container={containerRef?.current} className="!onvo-p-0 onvo-z-50 onvo-w-[320px] onvo-backdrop-blur-lg !onvo-bg-transparent">
                    <div className="onvo-w-full onvo-absolute onvo-top-0 onvo-left-0 onvo-right-0 onvo-bottom-0 onvo-foreground-color onvo-opacity-50 onvo-rounded-lg -onvo-z-10"></div>

                    <FilterBar />
                  </PopoverContent>
                </Popover>)}
              {(dashboard?.settings?.can_schedule_reports) && (
                <Tooltip content="Schedule reports" side="bottom" align="end">
                  <Button className="onvo-foreground-color onvo-border-black/10 dark:onvo-border-white/10" variant="secondary"
                    onClick={() => {
                      setOpen(true);
                    }}
                  >
                    <ClockIcon className="onvo-size-4" />
                  </Button>
                </Tooltip>)}
              {(ImageDownloadEnabled || ReportDownloadEnabled || DocumentDownloadEnabled) &&
                DownloadDropdown
              }
              {children}
            </div>
          </div>
        </main>
        <div className="onvo-w-full onvo-h-2"></div>
        {refreshing && <div className={"onvo-w-full onvo-overflow-hidden onvo-left-0 onvo-right-0 onvo-h-2" + (dashboard?.settings?.enable_tabs ? "" : " onvo-rounded-b-2xl")}>
          <div className="onvo-h-2 onvo-bg-blue-500 onvo-rounded-r-2xl onvo-transition-all onvo-duration-300 onvo-ease-in-out" style={{ width: (progress * 100) + "%" }}></div>
        </div>}

        {dashboard?.settings?.enable_tabs && (
          <div className="onvo-h-full onvo-border-t onvo-flex onvo-flex-row  onvo-border-black/10 dark:onvo-border-white/10  onvo-rounded-b-2xl">
            <DragDropContext onDragEnd={onDragEnd}>
              <Droppable droppableId="droppable" direction="horizontal">
                {(provided, snapshot) => (
                  <div
                    ref={provided.innerRef}
                    className="onvo-flex onvo-overflow-x-auto onvo-flex-grow onvo-rounded-b-2xl"
                    {...provided.droppableProps}
                  >
                    {(dashboard?.tabs || []).filter(a => !a.hidden).map((item, index) => (
                      <Draggable isDragDisabled={!editable} key={item.id} draggableId={item.id + ""} index={index}>
                        {(provided, snapshot) => (
                          <div
                            key={item.id + ""}
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}

                            className={
                              "onvo-flex onvo-flex-row onvo-items-center onvo-border-r onvo-border-slate-200 dark:onvo-border-slate-800 onvo-gap-2 onvo-py-0 onvo-px-2 onvo-select-none " +
                              (tab === item.id ? "onvo-bg-blue-500/20 " : "") +
                              (snapshot.isDragging ? "onvo-bg-black/10 dark:onvo-bg-white/10" : "")
                            }
                            onClick={() => {
                              setTab(item.id);
                            }}>
                            <DashboardHeaderTab item={item} />
                          </div>
                        )}
                      </Draggable>
                    ))}
                    {provided.placeholder}
                  </div>
                )}
              </Droppable>
            </DragDropContext>
            <div className="onvo-flex onvo-flex-row onvo-items-center onvo-gap-2 onvo-py-1 onvo-px-2 onvo-select-none onvo-border-l onvo-border-black/10 dark:onvo-border-white/10">
              {editable && (
                <Tooltip side="bottom" content="Add tab">
                  <Icon className="!onvo-px-0.5 !onvo-py-0.5 onvo-cursor-pointer hover:onvo-bg-black/10 dark:onvo-bg-white/10 onvo-rounded-full onvo-transition-all" icon={PlusIcon} onClick={() => {
                    addTab();
                  }} />
                </Tooltip>)}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Icon className="!onvo-px-0.5 !onvo-py-0.5 onvo-cursor-pointer hover:onvo-bg-black/10 dark:onvo-bg-white/10 onvo-rounded-full onvo-transition-all" icon={Bars3Icon} /></DropdownMenuTrigger>
                <DropdownMenuContent side="bottom" align="end" container={containerRef?.current} className="!onvo-backdrop-blur-lg onvo-min-w-56 onvo-z-50">

                  <div className="onvo-w-full onvo-absolute onvo-top-0 onvo-left-0 onvo-right-0 onvo-bottom-0 onvo-foreground-color onvo-opacity-50 onvo-rounded-lg -onvo-z-10"></div>

                  <DropdownMenuGroup>
                    {(dashboard?.tabs || []).map(a => (
                      <DropdownMenuItem key={a.id} className="!onvo-py-1" onClick={() => {
                        setTab(a.id);
                      }}>
                        <Text className="onvo-flex-grow">
                          {a.label}
                        </Text>
                        <div className="onvo-rounded-full onvo-size-6 onvo-flex onvo-items-center onvo-justify-center onvo-mr-2 hover:onvo-bg-black/10 hover:dark:onvo-bg-white/10 onvo-cursor-pointer">
                          {a.hidden ? <EyeSlashIcon onClick={() => {
                            if (editable) {
                              hideTab(a.id, false);
                            }
                          }} className="onvo-size-4" /> : <EyeIcon onClick={() => {
                            if (editable) {
                              hideTab(a.id, true);
                            }
                          }} className="onvo-size-4" />}
                        </div>
                      </DropdownMenuItem>))}
                  </DropdownMenuGroup>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
        )}
      </section>
    </>
  );
};
