"use client";

import { useState, useEffect, useCallback } from "react";
import { FilePlus, Pencil, Trash2, MessageSquare, Check, X } from "lucide-react";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import {
  fetchSessions,
  updateSession,
  deleteSession,
  type SessionInfo,
} from "@/lib/api/sessions";

type SessionPanelProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  currentSessionId: string | null;
  onSelectSession: (sessionId: string) => void;
  onNewSession: () => void;
};

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return "just now";
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return `${days}d ago`;
}

export function SessionPanel({
  open,
  onOpenChange,
  currentSessionId,
  onSelectSession,
  onNewSession,
}: SessionPanelProps) {
  const [sessions, setSessions] = useState<SessionInfo[]>([]);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editTitle, setEditTitle] = useState("");

  const loadSessions = useCallback(async () => {
    try {
      const data = await fetchSessions();
      setSessions(data);
    } catch (e) {
      console.error("Failed to load sessions:", e);
    }
  }, []);

  useEffect(() => {
    if (open) loadSessions();
  }, [open, loadSessions]);

  const handleRename = async (id: string) => {
    if (!editTitle.trim()) return;
    try {
      await updateSession(id, editTitle.trim());
      setEditingId(null);
      loadSessions();
    } catch (e) {
      console.error("Failed to rename session:", e);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteSession(id);
      loadSessions();
    } catch (e) {
      console.error("Failed to delete session:", e);
    }
  };

  const handleSelect = (id: string) => {
    onSelectSession(id);
    onOpenChange(false);
  };

  const handleNew = () => {
    onNewSession();
    onOpenChange(false);
  };

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent
        side="left"
        className="w-[340px] sm:max-w-[340px] bg-background/95 backdrop-blur-2xl border-foreground/10 p-0 flex flex-col"
        showCloseButton={false}
      >
        <SheetHeader className="px-5 pt-5 pb-3 border-b border-foreground/5">
          <div className="flex items-center justify-between">
            <div>
              <SheetTitle className="text-xs font-black uppercase tracking-[0.2em] text-foreground/90">
                Mission Archive
              </SheetTitle>
              <SheetDescription className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground/50 mt-0.5">
                {sessions.length} session{sessions.length !== 1 ? "s" : ""} logged
              </SheetDescription>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleNew}
              className="h-8 gap-1.5 rounded-full text-[10px] font-black uppercase tracking-wider text-primary hover:text-primary hover:bg-primary/10"
            >
              <FilePlus className="w-3.5 h-3.5" />
              New
            </Button>
          </div>
        </SheetHeader>

        <div className="flex-1 overflow-y-auto px-3 py-3 space-y-1.5">
          {sessions.length === 0 && (
            <div className="flex flex-col items-center justify-center h-40 text-muted-foreground/30">
              <MessageSquare className="w-8 h-8 mb-2" />
              <span className="text-[10px] font-bold uppercase tracking-widest">No sessions yet</span>
            </div>
          )}

          {sessions.map((session) => {
            const isActive = session.id === currentSessionId;
            const isEditing = editingId === session.id;

            return (
              <div
                key={session.id}
                className={cn(
                  "group relative rounded-xl border transition-all duration-200 cursor-pointer",
                  isActive
                    ? "bg-primary/10 border-primary/20"
                    : "bg-foreground/[0.02] border-foreground/5 hover:bg-foreground/5 hover:border-foreground/10"
                )}
                onClick={() => !isEditing && handleSelect(session.id)}
              >
                <div className="px-4 py-3">
                  {isEditing ? (
                    <div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
                      <Input
                        value={editTitle}
                        onChange={(e) => setEditTitle(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") handleRename(session.id);
                          if (e.key === "Escape") setEditingId(null);
                        }}
                        className="h-7 text-xs border-primary/30 bg-background/50"
                        autoFocus
                      />
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 shrink-0 text-emerald-400 hover:text-emerald-300"
                        onClick={() => handleRename(session.id)}
                      >
                        <Check className="w-3.5 h-3.5" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 shrink-0 text-muted-foreground hover:text-foreground"
                        onClick={() => setEditingId(null)}
                      >
                        <X className="w-3.5 h-3.5" />
                      </Button>
                    </div>
                  ) : (
                    <>
                      <div className="flex items-start justify-between gap-2">
                        <h3 className="text-[11px] font-bold text-foreground/90 leading-tight line-clamp-1 flex-1">
                          {session.title}
                        </h3>
                        <div
                          className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-6 w-6 text-muted-foreground/50 hover:text-foreground"
                            onClick={() => {
                              setEditingId(session.id);
                              setEditTitle(session.title);
                            }}
                          >
                            <Pencil className="w-3 h-3" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-6 w-6 text-muted-foreground/50 hover:text-red-400"
                            onClick={() => handleDelete(session.id)}
                          >
                            <Trash2 className="w-3 h-3" />
                          </Button>
                        </div>
                      </div>
                      {session.preview && (
                        <p className="text-[10px] text-muted-foreground/50 leading-relaxed line-clamp-2 mt-1">
                          {session.preview}
                        </p>
                      )}
                      <div className="flex items-center gap-3 mt-2">
                        <span className="text-[9px] font-bold text-muted-foreground/30 uppercase tracking-wider">
                          {timeAgo(session.updated_at)}
                        </span>
                        <span className="text-[9px] font-bold text-muted-foreground/30 uppercase tracking-wider">
                          {session.message_count} msg{session.message_count !== 1 ? "s" : ""}
                        </span>
                      </div>
                    </>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </SheetContent>
    </Sheet>
  );
}
