import { createSignal, createMemo, For, Show, onCleanup, onMount } from "solid-js";
import { Play, Pause, Square, Clock } from "lucide-solid";
import { format, parseISO, differenceInSeconds } from "date-fns";

import { useApp } from "~/lib/app-context";
import {
  apiListTimeEntries,
  apiCreateTimeEntry,
  apiUpdateTimeEntry,
  apiDeleteTimeEntry
} from "~/lib/api-crm";
import type { TimeEntry } from "~/lib/types-crm";

interface TimeTrackerProps {
  taskId?: string;
  workspaceSlug: string;
}

export function TimeTracker(props: TimeTrackerProps) {
  const app = useApp();
  const [entries, setEntries] = createSignal<TimeEntry[]>([]);
  const [activeEntry, setActiveEntry] = createSignal<TimeEntry | null>(null);
  const [now, setNow] = createSignal(Date.now());
  const [description, setDescription] = createSignal("");

  let timer: number | null = null;

  onMount(() => {
    timer = window.setInterval(() => setNow(Date.now()), 1000);
    loadEntries();
  });

  onCleanup(() => {
    if (timer) window.clearInterval(timer);
  });

  const loadEntries = async () => {
    try {
      const list = await apiListTimeEntries(props.workspaceSlug);
      setEntries(list.filter(e => !props.taskId || e.taskId === props.taskId));

      // Find active entry (no end time)
      const active = list.find(e => !e.endedAt && (!props.taskId || e.taskId === props.taskId));
      if (active) {
        setActiveEntry(active);
        setDescription(active.description);
      }
    } catch (e) {
      console.error("Failed to load time entries", e);
    }
  };

  const startTimer = async () => {
    const entry = await apiCreateTimeEntry({
      workspaceSlug: props.workspaceSlug,
      taskId: props.taskId,
      description: description(),
      startedAt: new Date().toISOString()
    });
    setActiveEntry(entry);
    setEntries([entry, ...entries()]);
  };

  const stopTimer = async () => {
    const entry = activeEntry();
    if (!entry) return;

    const updated = await apiUpdateTimeEntry(entry.id, {
      endedAt: new Date().toISOString()
    });

    setActiveEntry(null);
    setEntries(entries().map(e => e.id === updated.id ? updated : e));
  };

  const deleteEntry = async (id: string) => {
    await apiDeleteTimeEntry(id);
    setEntries(entries().filter(e => e.id !== id));
  };

  const elapsedSeconds = createMemo(() => {
    const entry = activeEntry();
    if (!entry) return 0;
    return differenceInSeconds(new Date(), parseISO(entry.startedAt));
  });

  const formatDuration = (seconds: number) => {
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    if (h > 0) {
      return `${h}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
    }
    return `${m}:${s.toString().padStart(2, "0")}`;
  };

  const totalTime = createMemo(() => {
    return entries()
      .filter(e => e.endedAt)
      .reduce((sum, e) => sum + e.durationSeconds, 0);
  });

  return (
    <div class="space-y-4">
      {/* Active timer */}
      <div class="flex items-center gap-4 p-4 rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <Show when={activeEntry()} fallback={
          <button
            onClick={startTimer}
            class="flex items-center gap-2 px-4 py-2 rounded-lg bg-[var(--accent)] text-white hover:opacity-90"
          >
            <Play class="w-4 h-4" />
            Start Timer
          </button>
        }>
          <button
            onClick={stopTimer}
            class="flex items-center gap-2 px-4 py-2 rounded-lg bg-red-500 text-white hover:opacity-90"
          >
            <Square class="w-4 h-4" />
            Stop
          </button>
          <div class="flex-1">
            <div class="text-2xl font-mono">{formatDuration(elapsedSeconds())}</div>
            <input
              type="text"
              value={description()}
              onInput={e => setDescription(e.currentTarget.value)}
              placeholder="What are you working on?"
              class="w-full bg-transparent text-sm text-[var(--text-muted)] outline-none"
            />
          </div>
        </Show>
      </div>

      {/* Total time */}
      <div class="flex items-center gap-2 text-sm text-[var(--text-muted)]">
        <Clock class="w-4 h-4" />
        Total logged: {formatDuration(totalTime())}
      </div>

      {/* Time entries list */}
      <Show when={entries().length > 0}>
        <div class="space-y-2">
          <h4 class="text-sm font-medium">Time Log</h4>
          <For each={entries().filter(e => e.endedAt).slice(0, 5)}>
            {entry => (
              <div class="flex items-center justify-between p-3 rounded-lg border border-[var(--border)] bg-[var(--surface)]">
                <div>
                  <div class="text-sm">{entry.description || "No description"}</div>
                  <div class="text-xs text-[var(--text-muted)]">
                    {format(parseISO(entry.startedAt), "MMM d, h:mm a")} • {formatDuration(entry.durationSeconds)}
                  </div>
                </div>
                <button
                  onClick={() => deleteEntry(entry.id)}
                  class="text-[var(--text-muted)] hover:text-red-500"
                >
                  <Square class="w-4 h-4" />
                </button>
              </div>
            )}
          </For>
        </div>
      </Show>
    </div>
  );
}