import { Label, Text, Title } from "../../tremor/Text";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import React, { memo, useEffect, useMemo, useState } from "react";
import { useBackend } from "../../layouts/Wrapper";
import { Question } from "@onvo-ai/js";
import { useDashboard } from "../../layouts/Dashboard/useDashboard";
import { DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator } from "../../tremor/DropdownMenu";
dayjs.extend(relativeTime);

function groupTextsByTime(entries: Pick<Question, "id" | "created_at" | "query">[]) {
  const groups: Record<string, Pick<Question, "id" | "created_at" | "query">[]> = {};

  entries.forEach((entry) => {
    const groupKey = `${dayjs(entry.created_at).fromNow(true)}`;

    if (!groups[groupKey]) {
      groups[groupKey] = [];
    }

    groups[groupKey].push(entry);
  });

  const sortedKeys = Object.keys(groups).sort(
    (a, b) => parseInt(a, 10) - parseInt(b, 10)
  );

  return sortedKeys.reduce((acc, key) => {
    acc[key] = groups[key];
    return acc;
  }, {} as Record<string, Pick<Question, "id" | "created_at" | "query">[]>);
}


const QuestionHistoryRaw: React.FC<{
  onSelect: (question: any | undefined) => void;
  variant: "list" | "dropdown";
  limit?: number;
  selectedId?: string;
}> = ({ onSelect, variant, limit }) => {
  const { backend } = useBackend();
  const { dashboard } = useDashboard();

  const [loading, setLoading] = useState(true);
  const [questions, setQuestions] = useState<Question[]>([]);

  const getQuestions = async () => {
    setLoading(true);
    if (!backend || !dashboard) return;
    let qs: any[] = await backend.questions.list({ dashboard: dashboard.id });

    let sorted = qs.sort((a, b) => {
      return (
        new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
      );
    });

    setQuestions(sorted);
    setLoading(false);
  };

  useEffect(() => {
    if (dashboard && dashboard.id) {
      getQuestions();
    }
  }, [dashboard?.id]);

  const filtered = useMemo(() => {
    if (!limit) return questions;
    return questions.slice(0, limit);
  }, [questions, limit]);

  if (!loading && questions.length === 0) {
    return <></>;
  }

  if (variant === "dropdown") {

    const grouped = groupTextsByTime(filtered);
    return (
      <>
        {Object.entries(grouped).map(([key, value]) => {
          return (
            <>
              <DropdownMenuLabel>{key}</DropdownMenuLabel>

              <DropdownMenuGroup>
                {
                  value.map((a) => {
                    let truncated = a.query.slice(0, 60) + "...";
                    return (
                      <DropdownMenuItem key={a.id} onClick={() => onSelect(a)}>
                        <span className="onvo-flex onvo-items-center onvo-gap-x-2">
                          <span>{truncated}</span>
                        </span>
                      </DropdownMenuItem>
                    )
                  })
                }
              </DropdownMenuGroup>

              <DropdownMenuSeparator />
            </>
          )
        })}
      </>
    )
  }


  return (
    <div className={"onvo-w-full onvo-flex onvo-flex-col onvo-h-full onvo-justify-end"}>
      <div className="onvo-flex onvo-w-full onvo-p-2 onvo-flex-row onvo-items-center onvo-justify-between">
        <Title>History</Title>
      </div>
      <div
        className={
          "onvo-w-full onvo-grid onvo-gap-0 onvo-grid-cols-1"
        }
      >
        {loading &&
          [1, 2, 3, 4].map((a) => (
            <div
              key={"question-history-loader-" + a}
              className="onvo-transition-all onvo-group onvo-relative onvo-flex onvo-flex-col onvo-w-full onvo-px-2 onvo-py-2 onvo-rounded-2xl"
            >
              <div className="onvo-flex-grow onvo-flex onvo-flex-row onvo-justify-between onvo-cursor-pointer onvo-items-center onvo-gap-4">
                <div className="onvo-flex-grow onvo-w-full onvo-flex onvo-flex-col onvo-gap-1">
                  <div className="onvo-h-3 onvo-bg-slate-200 onvo-rounded-md dark:onvo-bg-slate-700 onvo-w-full onvo-flex-grow"></div>
                  <div className="onvo-h-3 onvo-bg-slate-200 onvo-rounded-md dark:onvo-bg-slate-700 onvo-w-[60%] onvo-flex-grow"></div>
                </div>
                <div className="onvo-w-16 onvo-h-3 onvo-bg-slate-200 onvo-rounded-md dark:onvo-bg-slate-700"></div>
              </div>
            </div>
          ))}
        {filtered.map((a) => {
          let truncated = a.query.slice(0, 240) + "...";
          return (
            <div
              className={
                "onvo-transition-all onvo-group onvo-relative onvo-flex onvo-w-full onvo-px-2 onvo-py-2 hover:onvo-bg-black/5 hover:onvo-dark:bg-white/10 onvo-rounded-lg"
              }
            >
              <div className="onvo-flex-grow onvo-flex onvo-flex-row onvo-justify-between onvo-cursor-pointer onvo-items-center onvo-gap-4" onClick={() => onSelect(a)}>
                <Text className="onvo-text-md">{truncated}</Text>
                <Label className="onvo-font-semibold onvo-text-xs onvo-w-16 onvo-flex-shrink-0 onvo-text-right">
                  {dayjs(a.created_at).fromNow(true)}
                </Label>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export const QuestionHistory = memo(QuestionHistoryRaw);
