"use client";
import { jsxs, jsx } from 'react/jsx-runtime';
import { useState } from 'react';
import { Button } from '../../../../../../ui/src/components/button.mjs';
import { Input } from '../../../../../../ui/src/components/input.mjs';
import { ScrollArea } from '../../../../../../ui/src/components/scroll-area.mjs';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '../../../../../../ui/src/components/dropdown-menu.mjs';
import { AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription, AlertDialogFooter, AlertDialogCancel, AlertDialogAction } from '../../../../../../ui/src/components/alert-dialog.mjs';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '../../../../../../ui/src/components/dialog.mjs';
import { MessageSquarePlus, MessageSquare, MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
import { cn } from '../../../../../../ui/src/lib/utils.mjs';
import { usePluginOverrides, useBasePath } from '@btst/stack/context';
import { useConversations, useRenameConversation, useDeleteConversation } from '../hooks/chat-hooks.mjs';
import { AI_CHAT_LOCALIZATION } from '../localization/index.mjs';

function ChatSidebar({
  currentConversationId,
  onNewChat,
  className
}) {
  const { navigate, localization: customLocalization } = usePluginOverrides("ai-chat", {});
  const basePath = useBasePath();
  const localization = { ...AI_CHAT_LOCALIZATION, ...customLocalization };
  const { conversations, isLoading } = useConversations();
  const renameMutation = useRenameConversation();
  const deleteMutation = useDeleteConversation();
  const [renameDialogOpen, setRenameDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [selectedConversation, setSelectedConversation] = useState(null);
  const [newTitle, setNewTitle] = useState("");
  const handleNewChat = () => {
    if (navigate) {
      navigate(`${basePath}/chat`);
    }
    if (onNewChat) {
      onNewChat();
    }
  };
  const handleConversationClick = (conversation) => {
    if (navigate) {
      navigate(`${basePath}/chat/${conversation.id}`);
    }
  };
  const handleRenameClick = (conversation) => {
    setSelectedConversation(conversation);
    setNewTitle(conversation.title);
    setRenameDialogOpen(true);
  };
  const handleDeleteClick = (conversation) => {
    setSelectedConversation(conversation);
    setDeleteDialogOpen(true);
  };
  const handleRenameConfirm = async () => {
    if (selectedConversation && newTitle.trim()) {
      await renameMutation.mutateAsync({
        id: selectedConversation.id,
        title: newTitle.trim()
      });
      setRenameDialogOpen(false);
      setSelectedConversation(null);
      setNewTitle("");
    }
  };
  const handleDeleteConfirm = async () => {
    if (selectedConversation) {
      await deleteMutation.mutateAsync({ id: selectedConversation.id });
      setDeleteDialogOpen(false);
      setSelectedConversation(null);
      if (selectedConversation.id === currentConversationId && navigate) {
        navigate(`${basePath}/chat`);
      }
    }
  };
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    const now = /* @__PURE__ */ new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 6e4);
    const diffHours = Math.floor(diffMs / 36e5);
    const diffDays = Math.floor(diffMs / 864e5);
    if (diffMins < 1) return localization.TIME_JUST_NOW;
    if (diffMins < 60)
      return localization.TIME_MINUTES_AGO.replace("{count}", String(diffMins));
    if (diffHours < 24)
      return localization.TIME_HOURS_AGO.replace("{count}", String(diffHours));
    if (diffDays === 1) return localization.TIME_YESTERDAY;
    if (diffDays < 7)
      return localization.TIME_DAYS_AGO.replace("{count}", String(diffDays));
    return date.toLocaleDateString();
  };
  return /* @__PURE__ */ jsxs(
    "div",
    {
      "data-testid": "chat-sidebar",
      className: cn("flex flex-col h-full bg-muted/30 border-r", className),
      children: [
        /* @__PURE__ */ jsx("div", { className: "p-4 border-b", children: /* @__PURE__ */ jsxs(
          Button,
          {
            onClick: handleNewChat,
            className: "w-full justify-start gap-2",
            variant: "outline",
            children: [
              /* @__PURE__ */ jsx(MessageSquarePlus, { className: "h-4 w-4" }),
              localization.SIDEBAR_NEW_CHAT
            ]
          }
        ) }),
        /* @__PURE__ */ jsx(ScrollArea, { className: "flex-1 [&_[data-slot=scroll-area-viewport]>div]:!block", children: /* @__PURE__ */ jsx("div", { className: "p-2", children: isLoading ? /* @__PURE__ */ jsx("div", { className: "p-4 text-center text-sm text-muted-foreground", children: localization.CHAT_LOADING }) : conversations.length === 0 ? /* @__PURE__ */ jsx("div", { className: "p-4 text-center text-sm text-muted-foreground", children: localization.SIDEBAR_NO_CONVERSATIONS }) : /* @__PURE__ */ jsx("div", { className: "space-y-1", children: conversations.map((conversation) => /* @__PURE__ */ jsxs(
          "div",
          {
            className: cn(
              "group flex items-center gap-2 rounded-lg px-3 py-2 hover:bg-accent cursor-pointer transition-colors overflow-hidden",
              currentConversationId === conversation.id && "bg-accent"
            ),
            children: [
              /* @__PURE__ */ jsxs(
                "button",
                {
                  type: "button",
                  className: "flex-1 flex items-center gap-2 text-left min-w-0 overflow-hidden",
                  onClick: () => handleConversationClick(conversation),
                  children: [
                    /* @__PURE__ */ jsx(MessageSquare, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
                    /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 overflow-hidden", children: [
                      /* @__PURE__ */ jsx("p", { className: "text-sm font-medium truncate", children: conversation.title }),
                      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground truncate", children: formatDate(conversation.updatedAt) })
                    ] })
                  ]
                }
              ),
              /* @__PURE__ */ jsxs(DropdownMenu, { children: [
                /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
                  Button,
                  {
                    variant: "ghost",
                    size: "icon",
                    className: "h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity",
                    children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" })
                  }
                ) }),
                /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", children: [
                  /* @__PURE__ */ jsxs(
                    DropdownMenuItem,
                    {
                      onClick: (e) => {
                        e.stopPropagation();
                        handleRenameClick(conversation);
                      },
                      children: [
                        /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4 mr-2" }),
                        localization.CONVERSATION_RENAME
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsxs(
                    DropdownMenuItem,
                    {
                      onClick: (e) => {
                        e.stopPropagation();
                        handleDeleteClick(conversation);
                      },
                      className: "text-destructive focus:text-destructive",
                      children: [
                        /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 mr-2" }),
                        localization.CONVERSATION_DELETE
                      ]
                    }
                  )
                ] })
              ] })
            ]
          },
          conversation.id
        )) }) }) }),
        /* @__PURE__ */ jsx(Dialog, { open: renameDialogOpen, onOpenChange: setRenameDialogOpen, children: /* @__PURE__ */ jsxs(DialogContent, { children: [
          /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: localization.CONVERSATION_RENAME }) }),
          /* @__PURE__ */ jsx(
            Input,
            {
              value: newTitle,
              onChange: (e) => setNewTitle(e.target.value),
              placeholder: localization.CONVERSATION_RENAME_PLACEHOLDER,
              onKeyDown: (e) => {
                if (e.key === "Enter") {
                  void handleRenameConfirm();
                }
              }
            }
          ),
          /* @__PURE__ */ jsxs(DialogFooter, { children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "outline",
                onClick: () => setRenameDialogOpen(false),
                children: localization.CONVERSATION_RENAME_CANCEL
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                onClick: handleRenameConfirm,
                disabled: !newTitle.trim() || renameMutation.isPending,
                children: localization.CONVERSATION_RENAME_SAVE
              }
            )
          ] })
        ] }) }),
        /* @__PURE__ */ jsx(AlertDialog, { open: deleteDialogOpen, onOpenChange: setDeleteDialogOpen, children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [
          /* @__PURE__ */ jsxs(AlertDialogHeader, { children: [
            /* @__PURE__ */ jsx(AlertDialogTitle, { children: localization.CONVERSATION_DELETE_CONFIRM_TITLE }),
            /* @__PURE__ */ jsx(AlertDialogDescription, { children: localization.CONVERSATION_DELETE_CONFIRM_DESCRIPTION })
          ] }),
          /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [
            /* @__PURE__ */ jsx(AlertDialogCancel, { children: localization.CONVERSATION_DELETE_CANCEL }),
            /* @__PURE__ */ jsx(
              AlertDialogAction,
              {
                onClick: handleDeleteConfirm,
                className: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
                children: localization.CONVERSATION_DELETE_CONFIRM_BUTTON
              }
            )
          ] })
        ] }) })
      ]
    }
  );
}

export { ChatSidebar };
