import { createSignal, For, onCleanup, onMount, Show } from "solid-js";
import { Search, X, CheckCircle, Calendar, FileText, User, Building2, Mail } from "lucide-solid";
import { useNavigate } from "@solidjs/router";
import { format, parseISO } from "date-fns";

import { useApp } from "~/lib/app-context";

interface SearchResult {
  id: string;
  type: "task" | "event" | "note" | "contact" | "company" | "email";
  title: string;
  subtitle?: string;
  href: string;
}

export function GlobalSearch() {
  const app = useApp();
  const navigate = useNavigate();
  const [open, setOpen] = createSignal(false);
  const [query, setQuery] = createSignal("");

  const workspaceSlug = () => app.primaryWorkspace()?.slug ?? "personal";

  const results = (): SearchResult[] => {
    const q = query().toLowerCase().trim();
    if (!q || q.length < 2) return [];

    const results: SearchResult[] = [];

    // Search tasks
    for (const task of app.state.tasks) {
      if (task.workspaceSlug !== workspaceSlug()) continue;
      if (task.title.toLowerCase().includes(q) || task.description.toLowerCase().includes(q)) {
        results.push({
          id: task.id,
          type: "task",
          title: task.title,
          subtitle: task.status.replace("_", " "),
          href: `/app/${workspaceSlug()}/board`
        });
      }
    }

    // Search events
    for (const event of app.state.events) {
      if (event.workspaceSlug !== workspaceSlug()) continue;
      if (event.title.toLowerCase().includes(q)) {
        results.push({
          id: event.id,
          type: "event",
          title: event.title,
          subtitle: format(parseISO(event.startsAt), "MMM d, yyyy"),
          href: `/app/${workspaceSlug()}/calendar`
        });
      }
    }

    // Search notes
    for (const note of app.state.notes) {
      if (note.workspaceSlug !== workspaceSlug()) continue;
      if (note.title.toLowerCase().includes(q) || note.content.toLowerCase().includes(q)) {
        results.push({
          id: note.id,
          type: "note",
          title: note.title || "Untitled",
          subtitle: note.content.slice(0, 50) + "...",
          href: `/app/${workspaceSlug()}/notes`
        });
      }
    }

    return results.slice(0, 10);
  };

  const handleKeyDown = (e: KeyboardEvent) => {
    // Open with Cmd/Ctrl + /
    if ((e.metaKey || e.ctrlKey) && e.key === "/") {
      e.preventDefault();
      setOpen(!open());
      setQuery("");
    }
    if (e.key === "Escape" && open()) {
      setOpen(false);
    }
  };

  onMount(() => {
    window.addEventListener("keydown", handleKeyDown);
  });

  onCleanup(() => {
    window.removeEventListener("keydown", handleKeyDown);
  });

  const getIcon = (type: SearchResult["type"]) => {
    switch (type) {
      case "task": return CheckCircle;
      case "event": return Calendar;
      case "note": return FileText;
      case "contact": return User;
      case "company": return Building2;
      case "email": return Mail;
    }
  };

  const selectResult = (result: SearchResult) => {
    navigate(result.href);
    setOpen(false);
    setQuery("");
  };

  return (
    <Show when={open()}>
      <div class="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]">
        <div
          class="absolute inset-0 bg-black/50 backdrop-blur-sm"
          onClick={() => setOpen(false)}
        />

        <div class="relative w-full max-w-xl bg-[var(--surface)] rounded-xl shadow-2xl border border-[var(--border)] overflow-hidden">
          <div class="flex items-center gap-3 px-4 py-3 border-b border-[var(--border)]">
            <Search class="w-5 h-5 text-[var(--text-muted)]" />
            <input
              type="text"
              value={query()}
              onInput={e => setQuery(e.currentTarget.value)}
              placeholder="Search tasks, events, notes..."
              class="flex-1 bg-transparent text-lg outline-none"
              autofocus
            />
            <kbd class="px-2 py-0.5 rounded bg-[var(--surface-hover)] text-xs text-[var(--text-muted)]">
              ESC
            </kbd>
          </div>

          <div class="max-h-[50vh] overflow-auto p-2">
            <Show when={query().length < 2}>
              <div class="text-center py-8 text-[var(--text-muted)]">
                Type at least 2 characters to search
              </div>
            </Show>

            <Show when={query().length >= 2 && results().length === 0}>
              <div class="text-center py-8 text-[var(--text-muted)]">
                No results found for "{query()}"
              </div>
            </Show>

            <For each={results()}>
              {result => {
                const Icon = getIcon(result.type);
                return (
                  <button
                    onClick={() => selectResult(result)}
                    class="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-[var(--surface-hover)] text-left"
                  >
                    <Icon class="w-5 h-5 text-[var(--text-muted)]" />
                    <div class="flex-1 min-w-0">
                      <div class="font-medium truncate">{result.title}</div>
                      <Show when={result.subtitle}>
                        <div class="text-sm text-[var(--text-muted)] truncate">
                          {result.subtitle}
                        </div>
                      </Show>
                    </div>
                    <span class="text-xs text-[var(--text-muted)] capitalize">
                      {result.type}
                    </span>
                  </button>
                );
              }}
            </For>
          </div>
        </div>
      </div>
    </Show>
  );
}