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

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 = {
  log: LogDto;
};
export const LogView: FC<Props> = ({ log }) => {
  const [toggleValues, setToggleValues] = useState(["sort"]);
  const jsonView = toggleValues.includes("json");
  const sortAscending = toggleValues.includes("sort");

  return (
    <div className={"ml-4"}>
      <div className={"mb-2 flex justify-between"}>
        <h1 className={"flex items-center gap-2 text-xl"}>
          {SourceToIconMap[log.source]} {log.name}
        </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 pb-1"}>
        <LogAnalytics log={log} />
      </div>

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