"use client";

import { useState, useMemo, useEffect, useRef } from "react";
import type { GraphNode } from "@/lib/types";
import { STATUS_LABELS, STATUS_COLORS, TYPE_ICONS } from "@/lib/types";
import { formatRelativeTime } from "@/lib/utils";

interface Props {
  nodes: GraphNode[];
  isOpen: boolean;
  onClose: () => void;
  onNodeClick: (nodeId: string) => void;
}

/**
 * Shared task list item component used in both desktop and mobile views.
 * Renders a single task with status dot, metadata, and status badge.
 */
function TaskListItem({ node, onClick }: { node: GraphNode; onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className="flex items-start gap-2.5 w-full px-4 py-2.5 hover:bg-zinc-50/50 dark:hover:bg-zinc-800/50 transition-colors text-left group cursor-pointer"
    >
      {/* Status dot */}
      <div className="mt-1.5 shrink-0">
        <div className="w-2 h-2 rounded-full" style={{ backgroundColor: STATUS_COLORS[node.status] }} />
      </div>
      
      {/* Content */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-1.5">
          <span className="text-[11px] font-mono text-zinc-400 dark:text-zinc-500">{node.id}</span>
          {node.priority <= 1 && (
            <span className="text-[10px]">{node.priority === 0 ? "🔥🔥" : "🔥"}</span>
          )}
          <span className="text-[10px]">{TYPE_ICONS[node.issueType] || ""}</span>
        </div>
        <div className="text-xs text-zinc-700 dark:text-zinc-300 truncate mt-0.5 group-hover:text-emerald-600 dark:group-hover:text-emerald-400 transition-colors">
          {node.title}
        </div>
        <div className="flex items-center gap-2 mt-1">
          {node.assignee && (
            <span className="text-[10px] text-zinc-400 dark:text-zinc-500 truncate max-w-[120px]">
              {node.assignee}
            </span>
          )}
          <span className="text-[10px] text-zinc-300 dark:text-zinc-600">
            {formatRelativeTime(node.createdAt)}
          </span>
        </div>
      </div>
      
      {/* Status label badge */}
      <span className="text-[9px] font-medium px-1.5 py-0.5 rounded-full shrink-0 mt-1" style={{
        backgroundColor: STATUS_COLORS[node.status] + "20",
        color: STATUS_COLORS[node.status],
      }}>
        {STATUS_LABELS[node.status]}
      </span>
    </button>
  );
}

/**
 * Full slide-in sidebar panel for tasks/issues.
 * Includes search bar, status filter chips, and task list.
 * Same pattern as ActivityPanel / AllCommentsPanel / NodeDetail.
 */
export function TasksPanel({
  nodes,
  isOpen,
  onClose,
  onNodeClick,
}: Props) {
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [search, setSearch] = useState("");
  const panelRef = useRef<HTMLDivElement>(null);

  // Reset search and filter state when panel closes (beads-map-ipz)
  useEffect(() => {
    if (!isOpen) {
      setSearch('');
      setStatusFilter('all');
    }
  }, [isOpen]);

  // Keyboard navigation: Escape to close (beads-map-eri)
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        onClose();
      }
    };

    if (isOpen) {
      window.addEventListener('keydown', handleKeyDown);
      return () => window.removeEventListener('keydown', handleKeyDown);
    }
  }, [isOpen, onClose]);

  const filteredNodes = useMemo(() => {
    let filtered = nodes;
    if (statusFilter === "open") {
      filtered = filtered.filter(n => n.status === "open" || n.status === "in_progress" || n.status === "blocked");
    } else if (statusFilter === "in_progress") {
      filtered = filtered.filter(n => n.status === "in_progress");
    } else if (statusFilter === "closed") {
      filtered = filtered.filter(n => n.status === "closed" || n.status === "deferred");
    }
    if (search.trim()) {
      const term = search.toLowerCase();
      filtered = filtered.filter(n =>
        n.id.toLowerCase().includes(term) ||
        n.title.toLowerCase().includes(term) ||
        (n.assignee || "").toLowerCase().includes(term)
      );
    }
    return filtered.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
  }, [nodes, statusFilter, search]);

  return (
    <>
      {/* Desktop sidebar */}
      <aside
        className={`hidden md:flex absolute top-0 right-0 h-full w-[360px] bg-white dark:bg-zinc-900 border-l border-zinc-200 dark:border-zinc-700 flex-col shadow-xl z-30 transform transition-transform duration-300 ease-out ${
          isOpen ? "translate-x-0" : "translate-x-full"
        }`}
      >
        {/* Header */}
        <div className="shrink-0 px-5 py-3 border-b border-zinc-100 dark:border-zinc-800 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <h2 className="text-xs font-semibold text-zinc-400 uppercase tracking-wider">
              Tasks
            </h2>
            {nodes.length > 0 && (
              <span className="px-1.5 py-0.5 bg-emerald-50 dark:bg-emerald-950 text-emerald-600 dark:text-emerald-400 rounded-full text-[10px] font-medium">
                {nodes.length}
              </span>
            )}
          </div>
          <button
            onClick={onClose}
            className="p-1 text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors rounded-full hover:bg-zinc-100 dark:hover:bg-zinc-800"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* Filter chips */}
        <div className="flex flex-wrap gap-1.5 px-4 pt-3 pb-2 shrink-0">
          {[
            ["all", "All"],
            ["open", "Open"],
            ["in_progress", "Active"],
            ["closed", "Closed"],
          ].map(([value, label]) => (
            <button
              key={value}
              onClick={() => setStatusFilter(value)}
              className={`px-2.5 py-1 text-[11px] font-medium rounded-full transition-colors ${
                statusFilter === value
                  ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-400"
                  : "text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800"
              }`}
            >
              {label}
            </button>
          ))}
        </div>

        {/* Search */}
        <div className="px-4 pb-3 shrink-0">
          <div className="flex items-center bg-zinc-50/80 dark:bg-zinc-800/80 rounded-full border border-zinc-200/60 dark:border-zinc-700/60 overflow-hidden">
            <div className="pl-3 pr-1 text-zinc-400 dark:text-zinc-500">
              <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
            </div>
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search tasks..."
              className="flex-1 px-2 py-2 text-xs text-zinc-800 dark:text-zinc-200 bg-transparent outline-none placeholder:text-zinc-400 dark:placeholder:text-zinc-500"
            />
            {search && (
              <button
                onClick={() => setSearch("")}
                className="pr-3 text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300"
              >
                <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            )}
          </div>
        </div>

        {/* Task list */}
        <div className="flex-1 overflow-y-auto custom-scrollbar border-t border-zinc-100 dark:border-zinc-800">
          {filteredNodes.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <svg
                className="w-8 h-8 text-zinc-200 dark:text-zinc-700 mb-3"
                fill="none"
                viewBox="0 0 24 24"
                strokeWidth={1.5}
                stroke="currentColor"
              >
                <rect x="2" y="2" width="20" height="20" rx="2" />
                <path d="M6 8h12M6 12h8M6 16h10" strokeLinecap="round" />
              </svg>
              <p className="text-xs text-zinc-400 dark:text-zinc-500">
                {search.trim()
                  ? "No tasks matching your search"
                  : "No tasks yet"}
              </p>
              {search.trim() && (
                <button
                  onClick={() => setSearch("")}
                  className="text-[11px] text-emerald-600 dark:text-emerald-400 hover:text-emerald-700 dark:hover:text-emerald-300 mt-1.5"
                >
                  Clear search
                </button>
              )}
            </div>
          ) : (
            <div className="divide-y divide-zinc-50 dark:divide-zinc-800">
              {filteredNodes.map((node) => (
                <TaskListItem key={node.id} node={node} onClick={() => onNodeClick(node.id)} />
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="shrink-0 px-4 py-2.5 border-t border-zinc-100 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-800/50">
          <div className="text-[10px] text-zinc-400 dark:text-zinc-500">
            {filteredNodes.length} of {nodes.length} issues
          </div>
        </div>
      </aside>

      {/* Mobile drawer */}
      <div
        className={`md:hidden fixed inset-x-0 bottom-0 z-20 transition-transform duration-300 ease-out ${
          isOpen ? "translate-y-0" : "translate-y-full"
        }`}
      >
        <div className="bg-white dark:bg-zinc-900 rounded-t-2xl shadow-xl border-t border-zinc-200 dark:border-zinc-700 max-h-[60vh] flex flex-col">
          {/* Drag handle */}
          <div className="flex justify-center pt-3 pb-1">
            <div className="w-8 h-1 bg-zinc-300 dark:bg-zinc-600 rounded-full" />
          </div>

          {/* Header */}
          <div className="flex items-center justify-between px-5 py-2">
            <div className="flex items-center gap-2">
              <h2 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">Tasks</h2>
              {nodes.length > 0 && (
                <span className="px-1.5 py-0.5 bg-emerald-50 dark:bg-emerald-950 text-emerald-600 dark:text-emerald-400 rounded-full text-[10px] font-medium">
                  {nodes.length}
                </span>
              )}
            </div>
            <button
              onClick={onClose}
              className="p-1 text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* Filter chips */}
          <div className="flex flex-wrap gap-1.5 px-5 pb-3">
            {[
              ["all", "All"],
              ["open", "Open"],
              ["in_progress", "Active"],
              ["closed", "Closed"],
            ].map(([value, label]) => (
              <button
                key={value}
                onClick={() => setStatusFilter(value)}
                className={`px-2.5 py-1 text-[11px] font-medium rounded-full transition-colors ${
                  statusFilter === value
                    ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-400"
                    : "text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800"
                }`}
              >
                {label}
              </button>
            ))}
          </div>

          {/* Task list */}
          <div className="flex-1 overflow-y-auto custom-scrollbar">
            {filteredNodes.length === 0 ? (
              <div className="py-8 text-center text-xs text-zinc-400 dark:text-zinc-500">
                No tasks matching filters
              </div>
            ) : (
              <div className="divide-y divide-zinc-50 dark:divide-zinc-800">
                {filteredNodes.map((node) => (
                  <TaskListItem key={node.id} node={node} onClick={() => onNodeClick(node.id)} />
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
