import React, { useState, useEffect } from "react";
import type { SessionEntry } from "../lib/types";

interface Props {
  sessions: SessionEntry[];
  loading: boolean;
  selectedId?: string;
  onSelect: (id: string) => void;
}

export function SessionList({ sessions, loading, selectedId, onSelect }: Props) {
  const [selectedProject, setSelectedProject] = useState<string | null>(null);

  // Group by project
  const grouped = new Map<string, SessionEntry[]>();
  for (const session of sessions) {
    const group = grouped.get(session.project) || [];
    group.push(session);
    grouped.set(session.project, group);
  }

  // Auto-select project when selectedId changes
  useEffect(() => {
    if (selectedId) {
      const match = sessions.find((s) => s.id === selectedId);
      if (match) {
        setSelectedProject(match.project);
      }
    }
  }, [selectedId, sessions]);

  if (loading) {
    return (
      <div className="p-4 space-y-3">
        {[...Array(5)].map((_, i) => (
          <div key={i} className="space-y-2 px-1">
            <div className="skeleton h-4 w-3/4" />
            <div className="skeleton h-3 w-1/2" />
          </div>
        ))}
      </div>
    );
  }

  if (sessions.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-12 px-6 text-center">
        <div className="w-10 h-10 rounded-xl bg-surface-inset flex items-center justify-center mb-3">
          <svg className="w-5 h-5 text-foreground-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193-.34.027-.68.052-1.02.072v3.091l-3-3c-1.354 0-2.694-.055-4.02-.163a2.115 2.115 0 01-.825-.242m9.345-8.334a2.126 2.126 0 00-.476-.095 48.64 48.64 0 00-8.048 0c-1.131.094-1.976 1.057-1.976 2.192v4.286c0 .837.46 1.58 1.155 1.951m9.345-8.334V6.637c0-1.621-1.152-3.026-2.76-3.235A48.455 48.455 0 0011.25 3c-2.115 0-4.198.137-6.24.402-1.608.209-2.76 1.614-2.76 3.235v6.226c0 1.621 1.152 3.026 2.76 3.235.577.075 1.157.14 1.74.194V21l4.155-4.155" />
          </svg>
        </div>
        <p className="text-body font-medium text-foreground-secondary">No sessions found</p>
        <p className="text-caption text-foreground-muted mt-1">Sessions will appear here once created</p>
      </div>
    );
  }

  // Session list for selected project
  if (selectedProject !== null) {
    const projectSessions = grouped.get(selectedProject) || [];
    return (
      <div className="animate-slide-in">
        <button
          onClick={() => setSelectedProject(null)}
          className="w-full text-left px-4 py-2.5 text-caption font-medium text-accent hover:text-accent-dark hover:bg-surface-overlay flex items-center gap-1.5 border-b border-border-muted transition-colors"
        >
          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
          </svg>
          <span>All Projects</span>
        </button>
        <div className="px-4 py-2 text-caption font-semibold text-foreground-muted uppercase tracking-wider border-b border-border-muted" style={{ background: "var(--color-surface-inset)" }}>
          {formatProjectName(selectedProject)}
        </div>
        <div className="py-1">
          {projectSessions.map((session, idx) => {
            const isSelected = selectedId === session.id;
            return (
              <button
                key={session.id}
                onClick={() => onSelect(session.id)}
                className={`
                  w-full text-left mx-2 my-0.5 px-3 py-2.5 rounded-lg transition-all duration-200
                  ${isSelected
                    ? "bg-accent-light shadow-glow-accent ring-1 ring-accent/25"
                    : "hover:bg-surface-overlay"
                  }
                `}
                style={{ width: "calc(100% - 1rem)", animationDelay: `${idx * 30}ms` }}
              >
                <div className={`text-body font-medium truncate ${isSelected ? "text-accent-dark" : "text-foreground"}`}>
                  {session.summary || session.firstPrompt || "Untitled Session"}
                </div>
                <div className="flex items-center gap-1.5 mt-1 text-caption text-foreground-muted">
                  <span>{formatDate(session.modified || session.created)}</span>
                  <span className="text-border">·</span>
                  <span className="tabular-nums">{session.messageCount} msgs</span>
                  {session.duration && session.duration > 0 && (
                    <>
                      <span className="text-border">·</span>
                      <span className="tabular-nums">{formatSessionDuration(session.duration)}</span>
                    </>
                  )}
                </div>
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  // Project list
  return (
    <div className="py-1 animate-fade-in">
      {[...grouped.entries()].map(([project, projectSessions]) => {
        const latest = projectSessions.reduce((a, b) =>
          (a.modified || a.created) > (b.modified || b.created) ? a : b
        );
        const count = projectSessions.length;
        return (
          <button
            key={project}
            onClick={() => setSelectedProject(project)}
            className="w-full text-left mx-2 my-0.5 px-3 py-2.5 rounded-lg hover:bg-surface-overlay transition-all duration-200 group"
            style={{ width: "calc(100% - 1rem)" }}
          >
            <div className="flex items-center justify-between">
              <div className="text-body font-medium text-foreground truncate">
                {formatProjectName(project)}
              </div>
              <svg className="w-4 h-4 text-foreground-muted opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
              </svg>
            </div>
            <div className="flex items-center gap-1.5 mt-1 text-caption text-foreground-muted">
              <span className="tabular-nums">{count} {count === 1 ? "session" : "sessions"}</span>
              <span className="text-border">·</span>
              <span>{formatDate(latest.modified || latest.created)}</span>
            </div>
          </button>
        );
      })}
    </div>
  );
}

/**
 * Best-effort decode of Claude Code's project directory name back to a path.
 * Claude encodes project paths by replacing '/' with '-', but this is lossy:
 * a path like /home/user/my-cool-app encodes as -home-user-my-cool-app and
 * decodes as /home/user/my/cool/app (hyphens in the original name are lost).
 * There is no way to distinguish path separators from literal hyphens.
 */
function formatProjectName(project: string): string {
  if (project.startsWith("-")) {
    return project.replace(/^-/, "/").replace(/-/g, "/");
  }
  return project;
}

function formatSessionDuration(ms: number): string {
  const minutes = Math.floor(ms / 60000);
  if (minutes < 1) return "<1m";
  if (minutes < 60) return `${minutes}m`;
  const hours = Math.floor(minutes / 60);
  const rem = minutes % 60;
  if (rem === 0) return `${hours}h`;
  return `${hours}h ${rem}m`;
}

function formatDate(dateStr: string): string {
  if (!dateStr) return "";
  const d = new Date(dateStr);
  if (isNaN(d.getTime())) return dateStr;
  return d.toLocaleDateString(undefined, {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}
