import { createMemo, createSignal, For, Show } from "solid-js";
import { isToday, parseISO } from "date-fns";

import { useApp } from "~/lib/app-context";
import { classifyActivity, getActivityTypeLabel, listActivityTypeOptions, type ActivityType } from "~/lib/activity";
import { formatPrettyDate, getColorStyle } from "~/lib/utils";

export default function TodayRoute() {
  const app = useApp();
  const [capture, setCapture] = createSignal("");
  const [activityType, setActivityType] = createSignal<ActivityType>("all");
  const [activityQuery, setActivityQuery] = createSignal("");
  const workspaceSlug = () => app.primaryWorkspace()?.slug ?? "personal";

  const dueToday = createMemo(() =>
    app.state.tasks.filter(task => task.workspaceSlug === workspaceSlug() && task.dueAt && isToday(parseISO(task.dueAt))),
  );

  const agenda = createMemo(() => {
    const taskItems = app.state.tasks
      .filter(task => task.workspaceSlug === workspaceSlug() && task.scheduledStart)
      .map(task => ({ kind: "task" as const, title: task.title, startsAt: task.scheduledStart!, color: task.color }));
    const eventItems = app.state.events
      .filter(event => event.workspaceSlug === workspaceSlug())
      .map(event => ({ kind: "event" as const, title: event.title, startsAt: event.startsAt, color: event.color }));

    return [...taskItems, ...eventItems]
      .filter(item => isToday(parseISO(item.startsAt)))
      .sort((left, right) => left.startsAt.localeCompare(right.startsAt));
  });

  const focusMinutes = createMemo(() =>
    app.state.focusSessions.reduce((sum, session) => sum + Math.round(session.durationSeconds / 60), 0),
  );

  const recentActivity = createMemo(() => {
    const selectedType = activityType();
    const query = activityQuery().trim().toLowerCase();

    return app.state.activities
      .filter(entry => entry.workspaceSlug === workspaceSlug())
      .filter(entry => (selectedType === "all" ? true : classifyActivity(entry) === selectedType))
      .filter(entry => {
        if (!query) {
          return true;
        }
        return entry.title.toLowerCase().includes(query) || entry.detail.toLowerCase().includes(query);
      })
      .slice(0, 8);
  });

  const quickTask = () => {
    if (!capture().trim()) {
      return;
    }
    app.createTask({
      workspaceSlug: workspaceSlug(),
      boardGroupId: "group-inbox",
      title: capture(),
      color: "slate"
    });
    setCapture("");
  };

  return (
    <div class="space-y-8">
      {/* Page header */}
      <div class="fade-in">
        <h1 class="page-title">Today</h1>
        <p class="mt-2 text-base text-[var(--text-muted)]">Plan the next useful move</p>
      </div>

      {/* Stats row */}
      <div class="grid gap-4 sm:grid-cols-3">
        <div class="stagger-item rounded-xl border border-[var(--border)] bg-gradient-to-br from-[var(--surface)] to-[var(--surface-tinted)] p-6 shadow-sm hover-lift">
          <p class="section-title text-[var(--text-muted)]">Due today</p>
          <p class="mt-3 text-3xl font-bold" style="font-family: var(--font-serif);">{dueToday().length}</p>
        </div>
        <div class="stagger-item rounded-xl border border-[var(--border)] bg-gradient-to-br from-[var(--surface)] to-[var(--surface-tinted)] p-6 shadow-sm hover-lift">
          <p class="section-title text-[var(--text-muted)]">Agenda items</p>
          <p class="mt-3 text-3xl font-bold" style="font-family: var(--font-serif);">{agenda().length}</p>
        </div>
        <div class="stagger-item rounded-xl border border-[var(--border)] bg-gradient-to-br from-[var(--surface)] to-[var(--surface-tinted)] p-6 shadow-sm hover-lift">
          <p class="section-title text-[var(--text-muted)]">Focus minutes</p>
          <p class="mt-3 text-3xl font-bold" style="font-family: var(--font-serif);">{focusMinutes()}</p>
        </div>
      </div>

      {/* Quick capture */}
      <div class="rounded-xl border border-[var(--border-accent)] bg-[var(--bg-accent)] p-6 shadow-md">
        <div class="flex flex-col gap-4 sm:flex-row">
          <input
            class="input-base flex-1"
            placeholder="Quick capture a task..."
            value={capture()}
            onInput={event => setCapture(event.currentTarget.value)}
            onKeyDown={event => event.key === "Enter" && quickTask()}
          />
          <button class="button-primary px-6 py-3 text-base font-semibold whitespace-nowrap" onClick={quickTask}>
            Add to inbox
          </button>
        </div>
      </div>

      {/* Main content grid */}
      <div class="grid gap-8 lg:grid-cols-[1.2fr_0.8fr]">
        {/* Agenda */}
        <div class="rounded-xl border border-[var(--border)] bg-[var(--surface)] shadow-md overflow-hidden">
          <div class="border-b border-[var(--border)] px-6 py-4 bg-[var(--bg-subtle)]">
            <h2 class="text-base font-semibold" style="font-family: var(--font-serif);">Agenda</h2>
          </div>
          <div class="divide-y divide-[var(--border)]">
            <Show when={agenda().length === 0}>
              <div class="px-6 py-12 text-center text-sm text-[var(--text-muted)]">
                No scheduled items for today
              </div>
            </Show>
            <For each={agenda()}>
              {item => {
                const color = getColorStyle(item.color);
                return (
                  <div class="flex items-center gap-4 px-6 py-4 transition-all hover:bg-[var(--bg-subtle)]">
                    <span
                      class="shrink-0 rounded-lg px-3 py-1.5 text-xs font-semibold"
                      style={{ background: color.bg, color: color.text }}
                    >
                      {item.kind}
                    </span>
                    <div class="min-w-0 flex-1">
                      <p class="truncate text-base font-medium">{item.title}</p>
                      <p class="text-sm text-[var(--text-muted)] mt-0.5">{formatPrettyDate(item.startsAt)}</p>
                    </div>
                  </div>
                );
              }}
            </For>
          </div>
        </div>

        {/* Right column */}
        <div class="space-y-8">
          {/* Due soon */}
          <div class="rounded-xl border border-[var(--border)] bg-[var(--surface)] shadow-md overflow-hidden">
            <div class="border-b border-[var(--border)] px-6 py-4 bg-[var(--bg-subtle)]">
              <h2 class="text-base font-semibold" style="font-family: var(--font-serif);">Due soon</h2>
            </div>
            <div class="divide-y divide-[var(--border)]">
              <Show when={dueToday().length === 0}>
                <div class="px-6 py-10 text-center text-sm text-[var(--text-muted)]">
                  Nothing due today
                </div>
              </Show>
              <For each={dueToday()}>
                {task => {
                  const color = getColorStyle(task.color);
                  return (
                    <div class="px-6 py-4 transition-all hover:bg-[var(--bg-subtle)]">
                      <div class="flex items-center justify-between gap-3 mb-2">
                        <p class="truncate text-base font-medium">{task.title}</p>
                        <span
                          class="shrink-0 rounded-lg px-3 py-1 text-xs font-semibold"
                          style={{ background: color.bg, color: color.text }}
                        >
                          {task.status.replace("_", " ")}
                        </span>
                      </div>
                      <Show when={task.description}>
                        <p class="text-sm text-[var(--text-muted)] line-clamp-2">{task.description}</p>
                      </Show>
                    </div>
                  );
                }}
              </For>
            </div>
          </div>

          {/* Recent activity */}
          <div class="rounded-xl border border-[var(--border)] bg-[var(--surface)] shadow-md overflow-hidden">
            <div class="border-b border-[var(--border)] px-6 py-4 bg-[var(--bg-subtle)]">
              <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <h2 class="text-base font-semibold" style="font-family: var(--font-serif);">Recent activity</h2>
                <div class="flex gap-2">
                  <input
                    class="input-base h-9 w-full text-sm sm:w-36"
                    placeholder="Search..."
                    value={activityQuery()}
                    onInput={event => setActivityQuery(event.currentTarget.value)}
                  />
                  <select
                    class="input-base h-9 w-24 text-sm"
                    value={activityType()}
                    onInput={event => setActivityType(event.currentTarget.value as ActivityType)}
                  >
                    <For each={listActivityTypeOptions()}>
                      {option => <option value={option.value}>{option.label}</option>}
                    </For>
                  </select>
                </div>
              </div>
            </div>
            <div class="divide-y divide-[var(--border)]">
              <Show when={recentActivity().length === 0}>
                <div class="px-6 py-10 text-center text-sm text-[var(--text-muted)]">
                  No activity matches this filter
                </div>
              </Show>
              <For each={recentActivity()}>
                {entry => {
                  const entryType = classifyActivity(entry);
                  return (
                    <div class="px-6 py-4 transition-all hover:bg-[var(--bg-subtle)]">
                      <div class="flex items-center justify-between gap-3 mb-1">
                        <p class="truncate text-base font-medium">{entry.title}</p>
                        <span class="shrink-0 text-xs font-semibold text-[var(--text-muted)]">
                          {getActivityTypeLabel(entryType)}
                        </span>
                      </div>
                      <p class="text-sm text-[var(--text-muted)] line-clamp-1 mb-1">{entry.detail}</p>
                      <p class="text-xs text-[var(--text-subtle)]">{formatPrettyDate(entry.createdAt)}</p>
                    </div>
                  );
                }}
              </For>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
