import { TraceWithLogsDto } from "@montelo/browser-client";
import { TooltipProvider } from "@radix-ui/react-tooltip";
import { ArrowDownAzIcon, BracesIcon, GanttChart } from "lucide-react";
import { FC, ReactNode, useState } from "react";
import { ToggleGroup, ToggleGroupItem } from "../ui/toggle-group";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
import { TraceAnalytics } from "./LogAnalytics/TraceAnalytics";
import { MessagesView } from "./MessagesView/MessagesView";

const TooltipWrapper: FC<{ children: ReactNode; tooltip: ReactNode }> = ({ children, tooltip }) => (
  <TooltipProvider delayDuration={350}>
    <Tooltip>
      <TooltipTrigger asChild>
        <div className="px-2">{children}</div>
      </TooltipTrigger>
      <TooltipContent className="bg-secondary">{tooltip}</TooltipContent>
    </Tooltip>
  </TooltipProvider>
);

type Props = {
  trace: TraceWithLogsDto;
};
export const TraceView: FC<Props> = ({ trace }) => {
  const [toggleValues, setToggleValues] = useState(["sort"]);
  const jsonView = toggleValues.includes("json");
  const sortAscending = toggleValues.includes("sort");

  const firstLog = trace.logs[0];
  const lastLog = trace.logs[trace.logs.length - 1];

  return (
    <div className={"ml-4"}>
      <div className={"mb-2 flex justify-between"}>
        <h1 className={"flex items-center gap-2 text-xl"}>
          <GanttChart className="bg-primary h-6 w-6 rounded p-1" /> Trace Overview
        </h1>

        <ToggleGroup
          size="sm"
          type="multiple"
          variant="outline"
          defaultChecked
          value={toggleValues}
          onValueChange={setToggleValues}
          defaultValue={["sort"]}
        >
          <ToggleGroupItem value="sort" className="p-0">
            <TooltipWrapper tooltip={sortAscending ? "Sort Descending" : "Sort Ascending"}>
              <ArrowDownAzIcon size={14} />
            </TooltipWrapper>
          </ToggleGroupItem>
          <ToggleGroupItem value="json" className="p-0">
            <TooltipWrapper tooltip={jsonView ? "Pretty View" : "JSON View"}>
              <BracesIcon size={14} />
            </TooltipWrapper>
          </ToggleGroupItem>
        </ToggleGroup>
      </div>
      <div className={"mb-4 flex flex-row gap-4"}>
        <TraceAnalytics trace={trace} />
      </div>

      <MessagesView
        input={firstLog.input}
        output={lastLog.output}
        inputSource={firstLog.source}
        outputSource={lastLog.source}
        jsonView={jsonView}
        sortAscending={sortAscending}
      />
    </div>
  );
};
