import { Sidebar } from "@/components/Option/Sidebar.tsx"
import React, { useContext, useState } from "react"
import { useMessageOption } from "@/hooks/useMessageOption.tsx"
import { useStoreChatModelSettings } from "@/store/model.tsx"
import { Card, Tooltip } from "antd"
import { PageAssitDatabase } from "@/db"
import { EraserIcon } from "lucide-react"
import { useTranslation } from "react-i18next"
import { useQueryClient } from "@tanstack/react-query"
import { HistoryContext } from "@/components/Layouts/Layout.tsx"

export const PlaygroundHistory = () => {
  const { setSystemPrompt } = useStoreChatModelSettings()

  const { show, setShow } = useContext(HistoryContext)

  const {
    setMessages,
    setHistory,
    setHistoryId,
    historyId,
    clearChat,
    setSelectedModel,
    temporaryChat,
    setSelectedSystemPrompt
  } = useMessageOption()

  const { t } = useTranslation(["option", "common", "settings"])

  const queryClient = useQueryClient()

  return (
    <Card
      className={`flex flex-col [&>:nth-child(2)]:flex-1 [&>:nth-child(2)]:overflow-y-auto w-[300px] h-full pt-16 pb-5 transition-all duration-300 ease-in-out`}
      style={{ paddingTop: "4rem", width: show ? "300px" : "0" }}
      title={
        <div className="flex items-center justify-between w-full">
          {t("sidebarTitle")}
          <Tooltip
            title={t("settings:generalSettings.system.deleteChatHistory.label")}
            placement="right">
            <button
              onClick={async () => {
                const confirm = window.confirm(
                  t("settings:generalSettings.system.deleteChatHistory.confirm")
                )

                if (confirm) {
                  const db = new PageAssitDatabase()
                  await db.deleteAllChatHistory()
                  await queryClient.invalidateQueries({
                    queryKey: ["fetchChatHistory"]
                  })
                  clearChat()
                }
              }}
              className="text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-gray-100">
              <EraserIcon className="size-5" />
            </button>
          </Tooltip>
        </div>
      }>
      <div className="overflow-y-auto">
        <Sidebar
          onClose={() => setShow(true)}
          setMessages={setMessages}
          setHistory={setHistory}
          setHistoryId={setHistoryId}
          setSelectedModel={setSelectedModel}
          setSelectedSystemPrompt={setSelectedSystemPrompt}
          clearChat={clearChat}
          historyId={historyId}
          setSystemPrompt={setSystemPrompt}
          temporaryChat={temporaryChat}
          history={history}
        />
      </div>
    </Card>
  )
}
