import { createMemo, createSignal, For, Show } from "solid-js";
import { format, isToday, isPast, parseISO } from "date-fns";
import { ArrowUpDown, CheckCircle, Circle, Filter, LayoutList, Plus } from "lucide-solid";

import Modal from "~/components/modal";
import { useApp } from "~/lib/app-context";
import { colorOptions, getColorStyle } from "~/lib/utils";

type SortField = "title" | "status" | "dueAt" | "createdAt";
type SortDir = "asc" | "desc";

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

  const [sortField, setSortField] = createSignal<SortField>("createdAt");
  const [sortDir, setSortDir] = createSignal<SortDir>("desc");
  const [statusFilter, setStatusFilter] = createSignal<string>("all");
  const [showCompleted, setShowCompleted] = createSignal(false);
  const [selectedTaskId, setSelectedTaskId] = createSignal<string | null>(null);

  const tasks = createMemo(() =>
    app.state.tasks.filter(t => t.workspaceSlug === workspaceSlug() && !t.archived)
  );

  const groups = createMemo(() =>
    [...app.state.boardGroups]
      .filter(g => g.workspaceSlug === workspaceSlug())
      .sort((a, b) => a.order - b.order)
  );

  const labels = createMemo(() =>
    app.state.labels.filter(l => l.workspaceSlug === workspaceSlug())
  );

  const filteredTasks = createMemo(() => {
    let result = tasks();

    // Status filter
    const status = statusFilter();
    if (status !== "all") {
      result = result.filter(t => t.status === status);
    }

    // Show/hide completed
    if (!showCompleted()) {
      result = result.filter(t => t.status !== "done");
    }

    // Sort
    const field = sortField();
    const dir = sortDir();
    result = [...result].sort((a, b) => {
      let cmp = 0;
      switch (field) {
        case "title":
          cmp = a.title.localeCompare(b.title);
          break;
        case "status":
          cmp = a.status.localeCompare(b.status);
          break;
        case "dueAt":
          cmp = (a.dueAt || "").localeCompare(b.dueAt || "");
          break;
        case "createdAt":
          cmp = a.createdAt.localeCompare(b.createdAt);
          break;
      }
      return dir === "asc" ? cmp : -cmp;
    });

    return result;
  });

  const toggleSort = (field: SortField) => {
    if (sortField() === field) {
      setSortDir(sortDir() === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortDir("asc");
    }
  };

  const selectedTask = createMemo(() =>
    tasks().find(t => t.id === selectedTaskId())
  );

  const getGroupName = (groupId: string) => {
    const group = groups().find(g => g.id === groupId);
    return group?.name || "Inbox";
  };

  const getLabelNames = (labelIds: string[]) => {
    return labelIds
      .map(id => labels().find(l => l.id === id)?.name)
      .filter(Boolean)
      .join(", ");
  };

  return (
    <div class="flex flex-col h-full">
      {/* Header */}
      <div class="flex items-center justify-between mb-4">
        <div class="flex items-center gap-3">
          <LayoutList class="w-6 h-6 text-[var(--accent)]" />
          <h1 class="text-2xl font-semibold">List View</h1>
        </div>
        <div class="flex items-center gap-2">
          <select
            value={statusFilter()}
            onChange={e => setStatusFilter(e.currentTarget.value)}
            class="px-3 py-1.5 rounded-lg border border-[var(--border)] bg-[var(--surface)] text-sm"
          >
            <option value="all">All Status</option>
            <option value="todo">To Do</option>
            <option value="in_progress">In Progress</option>
            <option value="done">Done</option>
          </select>
          <label class="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={showCompleted()}
              onChange={e => setShowCompleted(e.currentTarget.checked)}
              class="rounded"
            />
            Show completed
          </label>
        </div>
      </div>

      {/* Table */}
      <div class="flex-1 overflow-auto rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <table class="w-full">
          <thead class="sticky top-0 bg-[var(--surface)] border-b border-[var(--border)]">
            <tr>
              <th class="w-8 px-4 py-3"></th>
              <th
                class="px-4 py-3 text-left text-sm font-medium cursor-pointer hover:bg-[var(--surface-hover)]"
                onClick={() => toggleSort("title")}
              >
                <div class="flex items-center gap-1">
                  Title
                  <Show when={sortField() === "title"}>
                    <ArrowUpDown class="w-3 h-3" />
                  </Show>
                </div>
              </th>
              <th class="px-4 py-3 text-left text-sm font-medium">Group</th>
              <th
                class="px-4 py-3 text-left text-sm font-medium cursor-pointer hover:bg-[var(--surface-hover)]"
                onClick={() => toggleSort("status")}
              >
                <div class="flex items-center gap-1">
                  Status
                  <Show when={sortField() === "status"}>
                    <ArrowUpDown class="w-3 h-3" />
                  </Show>
                </div>
              </th>
              <th
                class="px-4 py-3 text-left text-sm font-medium cursor-pointer hover:bg-[var(--surface-hover)]"
                onClick={() => toggleSort("dueAt")}
              >
                <div class="flex items-center gap-1">
                  Due
                  <Show when={sortField() === "dueAt"}>
                    <ArrowUpDown class="w-3 h-3" />
                  </Show>
                </div>
              </th>
              <th class="px-4 py-3 text-left text-sm font-medium">Labels</th>
            </tr>
          </thead>
          <tbody>
            <For each={filteredTasks()}>
              {task => (
                <tr
                  class="border-b border-[var(--border)] hover:bg-[var(--surface-hover)] cursor-pointer"
                  onClick={() => setSelectedTaskId(task.id)}
                >
                  <td class="px-4 py-3">
                    <button
                      onClick={e => {
                        e.stopPropagation();
                        app.updateTask(task.id, {
                          status: task.status === "done" ? "todo" : "done"
                        });
                      }}
                      class="text-[var(--text-muted)] hover:text-[var(--accent)]"
                    >
                      <Show when={task.status === "done"} fallback={<Circle class="w-5 h-5" />}>
                        <CheckCircle class="w-5 h-5 text-green-500" />
                      </Show>
                    </button>
                  </td>
                  <td class="px-4 py-3">
                    <div class="flex items-center gap-2">
                      <div
                        class="w-2 h-2 rounded-full"
                        style={getColorStyle(task.color)}
                      />
                      <span class={task.status === "done" ? "line-through text-[var(--text-muted)]" : ""}>
                        {task.title}
                      </span>
                    </div>
                  </td>
                  <td class="px-4 py-3 text-sm text-[var(--text-muted)]">
                    {getGroupName(task.boardGroupId)}
                  </td>
                  <td class="px-4 py-3">
                    <span class={`px-2 py-0.5 rounded text-xs ${
                      task.status === "done" ? "bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300" :
                      task.status === "in_progress" ? "bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300" :
                      "bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300"
                    }`}>
                      {task.status === "in_progress" ? "In Progress" : task.status.charAt(0).toUpperCase() + task.status.slice(1)}
                    </span>
                  </td>
                  <td class="px-4 py-3 text-sm">
                    <Show when={task.dueAt}>
                      <span class={`${
                        isPast(parseISO(task.dueAt!)) && task.status !== "done"
                          ? "text-red-500"
                          : isToday(parseISO(task.dueAt!))
                            ? "text-[var(--accent)]"
                            : "text-[var(--text-muted)]"
                      }`}>
                        {format(parseISO(task.dueAt!), "MMM d")}
                      </span>
                    </Show>
                  </td>
                  <td class="px-4 py-3 text-sm text-[var(--text-muted)]">
                    {getLabelNames(task.labelIds)}
                  </td>
                </tr>
              )}
            </For>
          </tbody>
        </table>

        <Show when={filteredTasks().length === 0}>
          <div class="text-center py-12 text-[var(--text-muted)]">
            No tasks found
          </div>
        </Show>
      </div>

      {/* Task detail modal - simplified */}
      <Modal
        open={selectedTaskId() !== null}
        onClose={() => setSelectedTaskId(null)}
        title="Task Details"
      >
        <Show when={selectedTask()}>
          {task => (
            <div class="space-y-4">
              <div class="flex items-center gap-3">
                <div
                  class="w-3 h-3 rounded-full"
                  style={getColorStyle(task.color)}
                />
                <h3 class="text-lg font-medium">{task.title}</h3>
              </div>
              <Show when={task.description}>
                <p class="text-[var(--text-muted)]">{task.description}</p>
              </Show>
              <div class="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span class="text-[var(--text-muted)]">Status:</span>{" "}
                  <span class="capitalize">{task.status.replace("_", " ")}</span>
                </div>
                <div>
                  <span class="text-[var(--text-muted)]">Group:</span>{" "}
                  {getGroupName(task.boardGroupId)}
                </div>
                <Show when={task.dueAt}>
                  <div>
                    <span class="text-[var(--text-muted)]">Due:</span>{" "}
                    {format(parseISO(task.dueAt!), "MMM d, yyyy")}
                  </div>
                </Show>
              </div>
              <div class="flex justify-end gap-2 pt-4">
                <button
                  onClick={() => setSelectedTaskId(null)}
                  class="px-4 py-2 rounded-lg border border-[var(--border)] hover:bg-[var(--surface-hover)]"
                >
                  Close
                </button>
                <button
                  onClick={() => {
                    window.location.href = `/app/${workspaceSlug()}/board`;
                  }}
                  class="px-4 py-2 rounded-lg bg-[var(--accent)] text-white hover:opacity-90"
                >
                  Open in Board
                </button>
              </div>
            </div>
          )}
        </Show>
      </Modal>
    </div>
  );
}