"use client";
import React, { useState, useEffect, useRef } from "react";
import { useI18n } from "@/lib/i18n";
import { Task } from "../tasks/TaskList";

interface CommandPaletteProps {
  isOpen: boolean;
  onClose: () => void;
  tasks: Task[];
  onSelectTask: (task: Task) => void;
}

export function CommandPalette({ isOpen, onClose, tasks, onSelectTask }: CommandPaletteProps) {
  const { t } = useI18n();
  const [query, setQuery] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (isOpen) {
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  }, [isOpen]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === "k") {
        e.preventDefault();
        if (isOpen) onClose();
        else {
          // Open handled by parent
          document.dispatchEvent(new CustomEvent("checkflow:openCommandPalette"));
        }
      }
      if (e.key === "Escape" && isOpen) {
        onClose();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  // Flatten recursive tasks for search
  const flattenTasks = (list: Task[]): Task[] => {
    let result: Task[] = [];
    for (const item of list) {
      result.push(item);
      if (item.children && item.children.length > 0) {
        result = result.concat(flattenTasks(item.children));
      }
    }
    return result;
  };

  const allTasks = flattenTasks(tasks);
  const filtered = query.trim()
    ? allTasks.filter(
        (task) =>
          task.title.toLowerCase().includes(query.toLowerCase()) ||
          (task.note && task.note.toLowerCase().includes(query.toLowerCase())) ||
          (task.tags && task.tags.some((t) => t.tag.name.toLowerCase().includes(query.toLowerCase())))
      )
    : allTasks.slice(0, 8);

  return (
    <div className="modal-overlay" onClick={onClose} style={{ zIndex: 99999, alignItems: "flex-start", paddingTop: "12vh" }}>
      <div
        className="modal command-palette-modal"
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 580, width: "90%", padding: 0, overflow: "hidden", borderRadius: "var(--radius-md)" }}
      >
        {/* Search Header */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px 18px", borderBottom: "1px solid var(--border)" }}>
          <span style={{ fontSize: 16, opacity: 0.6 }}>🔍</span>
          <input
            ref={inputRef}
            className="form-input"
            placeholder={t("searchPlaceholder") || "Search all tasks, notes, tags (Ctrl+K)..."}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            style={{ border: "none", background: "none", fontSize: 15, padding: 0, outline: "none", boxShadow: "none" }}
          />
          <span style={{ fontSize: 11, color: "var(--text-tertiary)", background: "var(--bg-secondary)", padding: "2px 6px", borderRadius: 4 }}>
            ESC
          </span>
        </div>

        {/* Results List */}
        <div style={{ maxHeight: 340, overflowY: "auto", padding: "8px 0" }}>
          {filtered.length === 0 ? (
            <div style={{ padding: "24px 20px", textAlign: "center", color: "var(--text-tertiary)", fontSize: 13 }}>
              No matching tasks or notes found
            </div>
          ) : (
            filtered.map((task) => (
              <div
                key={task.id}
                className="context-menu-item"
                style={{ padding: "10px 18px", gap: 12, borderRadius: 0 }}
                onClick={() => {
                  onSelectTask(task);
                  onClose();
                }}
              >
                <button
                  className={`task-check-btn${task.completed ? " checked" : ""}`}
                  style={{ width: 16, height: 16, flexShrink: 0 }}
                  type="button"
                />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-primary)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                    {task.title}
                  </div>
                  {task.note && (
                    <div style={{ fontSize: 11, color: "var(--text-tertiary)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                      {task.note.replace(/[#*`]/g, "").slice(0, 60)}
                    </div>
                  )}
                </div>
                {task.tags && task.tags.length > 0 && (
                  <div style={{ display: "flex", gap: 4 }}>
                    {task.tags.map((tg) => (
                      <span key={tg.tag.id} className="badge" style={{ background: tg.tag.color + "22", color: tg.tag.color, fontSize: 10, padding: "1px 6px" }}>
                        #{tg.tag.name}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}