import React, { useEffect, useRef } from "react";
import { Card } from "../../tremor/Card";
import { Title, Text, Label } from "../../tremor/Text";
import { useDashboard } from "./useDashboard";
import { useBackend } from "../Wrapper";
import { useTheme } from "./useTheme";
import { DashboardHeader } from "../../components/DashboardHeader";
import { DashboardGrid } from "../../components/DashboardGrid";
import { Copilot, CopilotButton, useCopilot } from "../Copilot";
import { CreateToolbar } from "../../components/CreateToolbar";
import { LogType } from "@onvo-ai/js";
import { Toaster } from "sonner";
import { Root } from "@radix-ui/react-tabs";
import { AutomationsModal } from "../../components/AutomationsModal";
import { useWidgetSuggestionsModal, WidgetSuggestionsModal } from "../../components/WidgetSuggestionsModal";
import { useIsMobile } from "../../lib/utils";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";

export const DashboardWrapper: React.FC<{
  id: string;
  children: React.ReactNode;
}> = ({ id: dashboardId, children }) => {
  const { backend } = useBackend();
  const { setId, refreshWidgets } = useDashboard();
  const theme = useTheme();

  useEffect(() => {
    if (dashboardId && backend) {
      setId(dashboardId, backend);
      refreshWidgets(backend);
    }
  }, [dashboardId, backend]);
  return children;
};

export const Dashboard: React.FC<{
  id: string;
  className?: string;
  variant?: "default" | "pdf" | "pptx"
}> = ({ id: dashboardId, className, variant = "default" }): React.ReactNode => {
  const { backend, setContainerRef } = useBackend();
  const theme = useTheme();
  const { dashboard, unauthorized, queue, tab } = useDashboard();
  const isMobile = useIsMobile();
  const localRef = useRef<HTMLDivElement>(null);
  const style = dashboard?.settings?.custom_css || "";

  const { open: suggestionsModalOpen, setOpen: setSuggestionsModalOpen } = useWidgetSuggestionsModal();
  const { open: copilotOpen, setOpen: setCopilotOpen, variant: copilotVariant } = useCopilot();

  useEffect(() => {
    if (dashboardId && backend) {

      backend.logs.create({
        type: LogType.ViewDashboard,
        dashboard: dashboardId,
      })
    }

    return () => {
      queue.flush();
    }
  }, [dashboardId, backend]);

  useEffect(() => {
    if (localRef?.current) {
      setContainerRef(localRef);
    }
  }, [localRef])

  let initialTab = 0;
  if (dashboard?.tabs && dashboard?.tabs.length > 0) {
    initialTab = Math.min(...(dashboard?.tabs.map(a => a.id))) || 0;
  }

  return (
    <DashboardWrapper id={dashboardId}>
      <div ref={localRef}
        key={theme === "dark" ? "dark" : "light"}
        className={`onvo-root-style onvo-dashboard-context  onvo-bg-opacity-100 onvo-relative onvo-scrollbar-thumb-rounded-full onvo-scrollbar-track-transparent onvo-translate-x-0 onvo-h-full onvo-background-color onvo-flex onvo-flex-col ${theme === "dark"
          ? "onvo-dark onvo-scrollbar-thumb-slate-500"
          : "onvo-scrollbar-thumb-slate-400"
          } ${className}`}
      >
        <style>{style}</style>
        <Toaster position="bottom-right" richColors />

        {unauthorized && (
          <div className="onvo-absolute onvo-top-0 onvo-left-0 onvo-right-0 onvo-bottom-0 onvo-bg-black/50 onvo-z-[1000] onvo-backdrop-blur-md onvo-flex onvo-justify-center onvo-items-center">
            <Card className="onvo-max-w-screen-md">
              <Title>Dashboard unavailable</Title>
              <Text>
                The dashboard you are trying to access is currently unavailable.
                If you are the administrator, click{" "}
                <a
                  href="https://dashboard.onvo.ai/settings/billing"
                  className="onvo-text-blue-500 onvo-underline"
                >
                  here
                </a>{" "}
                to update your billing.
              </Text>
            </Card>
          </div>
        )}
        <Root
          key={initialTab + ""}
          defaultValue={initialTab + ""}
          value={tab + ""}
          className="onvo-h-full onvo-flex onvo-flex-row onvo-w-full"
        >
          <PanelGroup autoSaveId="dashboard-sidebar" direction="horizontal">
            <Panel minSize={isMobile ? 0 : 50} className="onvo-relative">
              <DashboardHeader variant={variant} />
              <div className="onvo-h-full onvo-flex onvo-flex-col onvo-overflow-y-auto onvo-overflow-x-hidden onvo-scrollbar-thin onvo-flex-grow onvo-relative">
                <DashboardGrid className="onvo-pb-20" />
              </div>
              {(!variant || variant === "default") && (
                <CreateToolbar />
              )}
            </Panel>

            {suggestionsModalOpen && (
              <>
                <PanelResizeHandle className="onvo-w-3 onvo-border-0 onvo-transition-all onvo-bg-black/10 dark:onvo-bg-white/10 hover:onvo-bg-black/20 dark:hover:onvo-bg-white/20 active:onvo-bg-black/40 dark:active:onvo-bg-white/40 onvo-flex onvo-justify-center onvo-items-center">
                  <div className="onvo-w-1 onvo-h-12 onvo-rounded-full onvo-bg-black/30 dark:onvo-bg-white/30"></div>
                </PanelResizeHandle>
                <Panel defaultSize={isMobile ? 100 : 25} minSize={0} maxSize={isMobile ? 100 : 50} onResize={(size) => {
                  if (size === 0) {
                    setSuggestionsModalOpen(false);
                  }
                }}>
                  <div className={"onvo-h-full onvo-transition-all " + (suggestionsModalOpen ? "onvo-w-full onvo-flex-shrink-0 onvo-flex-grow" : "onvo-w-0")}>
                    <WidgetSuggestionsModal />
                  </div>
                </Panel>
              </>)}

            {(copilotOpen && copilotVariant === "default" && !isMobile && dashboard?.settings?.copilot_enabled) && (
              <>
                <PanelResizeHandle className="onvo-w-3 onvo-border-0 onvo-transition-all onvo-bg-black/10 dark:onvo-bg-white/10 hover:onvo-bg-black/20 dark:hover:onvo-bg-white/20 active:onvo-bg-black/40 dark:active:onvo-bg-white/40 onvo-flex onvo-justify-center onvo-items-center">
                  <div className="onvo-w-1 onvo-h-12 onvo-rounded-full onvo-bg-black/30 dark:onvo-bg-white/30"></div>
                </PanelResizeHandle>
                <Panel defaultSize={25} minSize={0} maxSize={50} onResize={(size) => {
                  if (size === 0) {
                    setCopilotOpen(false);
                  }
                }}>
                  <Copilot coupled /></Panel>
              </>
            )}

            {((copilotVariant === "modal" || isMobile) && dashboard?.settings?.copilot_enabled) && (
              <Copilot coupled />
            )}

            {!copilotOpen && dashboard?.settings?.copilot_enabled && (
              <CopilotButton />
            )}
          </PanelGroup>
        </Root>

        <AutomationsModal />
      </div>
    </DashboardWrapper>
  );
};
