import { createMemo, createSignal, For, Show } from "solid-js";
import { CheckCircle, Inbox, Plus, Trash2, X } from "lucide-solid";

import { useApp } from "~/lib/app-context";
import {
  apiListInboxItems,
  apiCreateInboxItem,
  apiDeleteInboxItem
} from "~/lib/api-crm";
import type { InboxItem } from "~/lib/types-crm";
import { formatPrettyDate } from "~/lib/utils";

export default function InboxRoute() {
  const app = useApp();
  const workspaceSlug = () => app.primaryWorkspace()?.slug ?? "personal";

  const [items, setItems] = createSignal<InboxItem[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [newContent, setNewContent] = createSignal("");

  const loadItems = async () => {
    setLoading(true);
    try {
      const list = await apiListInboxItems(workspaceSlug());
      setItems(list);
    } catch (e) {
      console.error("Failed to load inbox", e);
    }
    setLoading(false);
  };

  if (items().length === 0 && loading()) {
    loadItems();
  }

  const handleAdd = async (e: KeyboardEvent) => {
    if (e.key !== "Enter") return;
    const content = newContent().trim();
    if (!content) return;

    const item = await apiCreateInboxItem({
      workspaceSlug: workspaceSlug(),
      content
    });

    setItems([item, ...items()]);
    setNewContent("");
  };

  const handleDelete = async (id: string) => {
    await apiDeleteInboxItem(id);
    setItems(items().filter(i => i.id !== id));
  };

  const handleConvertToTask = async (item: InboxItem) => {
    // Create task from inbox item
    const task = await app.createTask({
      workspaceSlug: workspaceSlug(),
      boardGroupId: "group-inbox",
      title: item.content,
      color: "slate"
    });

    // Delete inbox item
    await apiDeleteInboxItem(item.id);
    setItems(items().filter(i => i.id !== item.id));

    // Navigate to board
    window.location.href = `/app/${workspaceSlug()}/board`;
  };

  return (
    <div class="max-w-2xl mx-auto py-8">
      <div class="flex items-center gap-3 mb-6">
        <Inbox class="w-8 h-8 text-[var(--accent)]" />
        <h1 class="text-2xl font-semibold">Inbox</h1>
      </div>

      <p class="text-[var(--text-muted)] mb-6">
        Quick capture for ideas, tasks, and notes. Process them later.
      </p>

      {/* Quick add */}
      <div class="relative mb-6">
        <Plus class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-muted)]" />
        <input
          type="text"
          value={newContent()}
          onInput={e => setNewContent(e.currentTarget.value)}
          onKeyPress={handleAdd}
          placeholder="Type something and press Enter..."
          class="w-full pl-10 pr-4 py-3 rounded-lg border border-[var(--border)] bg-[var(--surface)] text-lg focus:border-[var(--accent)] focus:outline-none"
        />
      </div>

      {/* Items list */}
      <Show when={!loading()} fallback={<div class="text-[var(--text-muted)]">Loading...</div>}>
        <div class="space-y-2">
          <Show when={items().length === 0}>
            <div class="text-center py-12 text-[var(--text-muted)]">
              <Inbox class="w-12 h-12 mx-auto mb-3 opacity-50" />
              <p>Your inbox is empty</p>
              <p class="text-sm mt-1">Capture ideas, tasks, or notes above</p>
            </div>
          </Show>
          <For each={items()}>
            {item => (
              <div class="flex items-start gap-3 p-4 rounded-lg border border-[var(--border)] bg-[var(--surface)] group">
                <div class="flex-1">
                  <p class="text-lg">{item.content}</p>
                  <p class="text-sm text-[var(--text-muted)] mt-1">
                    {formatPrettyDate(item.createdAt)}
                  </p>
                </div>
                <div class="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button
                    onClick={() => handleConvertToTask(item)}
                    class="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-[var(--accent)] text-white text-sm hover:opacity-90"
                    title="Convert to task"
                  >
                    <CheckCircle class="w-4 h-4" />
                    Task
                  </button>
                  <button
                    onClick={() => handleDelete(item.id)}
                    class="p-1.5 rounded-lg text-[var(--text-muted)] hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950"
                    title="Delete"
                  >
                    <Trash2 class="w-4 h-4" />
                  </button>
                </div>
              </div>
            )}
          </For>
        </div>
      </Show>
    </div>
  );
}