"use client";

import { useEchoStore } from "@/stores/echo-store";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
import { Plus, MessageSquare, Trash2, PanelLeftClose, PanelLeft } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { useEffect } from "react";

export function ConversationSidebar() {
  const {
    conversations,
    activeConversationId,
    isLoadingConversations,
    sidebarOpen,
    setSidebarOpen,
    setActiveConversation,
    loadConversations,
    createConversation,
    deleteConversation,
  } = useEchoStore();

  useEffect(() => {
    loadConversations();
  }, [loadConversations]);

  const handleNew = async () => {
    await createConversation();
  };

  return (
    <>
      {/* Mobile overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black/50 z-40 md:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={cn(
          "fixed md:relative z-50 h-full bg-card border-r border-border flex flex-col transition-all duration-300 ease-in-out",
          sidebarOpen ? "w-72 translate-x-0" : "w-0 -translate-x-full md:translate-x-0"
        )}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-border">
          <h2 className="font-semibold text-sm uppercase tracking-wider text-muted-foreground">
            Conversations
          </h2>
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 md:hidden"
            onClick={() => setSidebarOpen(false)}
          >
            <PanelLeftClose className="h-4 w-4" />
          </Button>
        </div>

        {/* New chat button */}
        <div className="p-3">
          <Button
            onClick={handleNew}
            className="w-full justify-start gap-2"
            variant="outline"
          >
            <Plus className="h-4 w-4" />
            New Conversation
          </Button>
        </div>

        {/* Conversation list */}
        <ScrollArea className="flex-1 px-2">
          {isLoadingConversations ? (
            <div className="flex items-center justify-center py-8 text-muted-foreground text-sm">
              Loading...
            </div>
          ) : conversations.length === 0 ? (
            <div className="flex items-center justify-center py-8 text-muted-foreground text-sm text-center px-4">
              No conversations yet. Start a new one!
            </div>
          ) : (
            <div className="space-y-1 pb-4">
              {conversations.map((conv) => (
                <div
                  key={conv.id}
                  className={cn(
                    "group flex items-center gap-2 rounded-lg px-3 py-2.5 cursor-pointer transition-colors",
                    activeConversationId === conv.id
                      ? "bg-primary text-primary-foreground"
                      : "hover:bg-accent text-accent-foreground"
                  )}
                  onClick={() => setActiveConversation(conv.id)}
                >
                  <MessageSquare className="h-4 w-4 shrink-0" />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium truncate">{conv.title}</p>
                    <p
                      className={cn(
                        "text-xs truncate",
                        activeConversationId === conv.id
                          ? "text-primary-foreground/70"
                          : "text-muted-foreground"
                      )}
                    >
                      {formatDistanceToNow(new Date(conv.updatedAt), {
                        addSuffix: true,
                      })}
                    </p>
                  </div>
                  <Button
                    variant="ghost"
                    size="icon"
                    className={cn(
                      "h-7 w-7 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity",
                      activeConversationId === conv.id &&
                        "hover:bg-primary-foreground/20"
                    )}
                    onClick={(e) => {
                      e.stopPropagation();
                      deleteConversation(conv.id);
                    }}
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </Button>
                </div>
              ))}
            </div>
          )}
        </ScrollArea>
      </aside>

      {/* Toggle button (visible when sidebar is closed) */}
      {!sidebarOpen && (
        <Button
          variant="ghost"
          size="icon"
          className="fixed left-3 top-3 z-30 h-9 w-9 bg-card border border-border shadow-sm"
          onClick={() => setSidebarOpen(true)}
        >
          <PanelLeft className="h-4 w-4" />
        </Button>
      )}
    </>
  );
}
