<script lang="ts">
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import { addToast } from '$lib/stores/toast';
  import Button from '$lib/components/ui/Button.svelte';
  import Card from '$lib/components/ui/Card.svelte';
  import EmptyState from '$lib/components/ui/EmptyState.svelte';
  import Skeleton from '$lib/components/ui/Skeleton.svelte';
  import Tabs from '$lib/components/ui/Tabs.svelte';
  import {
    Inbox,
    Sun,
    CalendarClock,
    History,
    Check,
    X as XIcon,
    Pause,
    RotateCcw,
    Plus,
  } from 'lucide-svelte';
  import {
    type EventItem,
    type EventKind,
    KIND_LABEL,
    STATUS_LABEL,
    STATUS_COLOR,
    KIND_COLOR,
    logActivity,
    listToday,
    listInbox,
    listActivity,
    listUpcoming,
    completeEvent,
    cancelEvent,
    deferEvent,
    reactivateEvent,
    formatDateTimeKst,
    relativeTimeKo,
  } from '$lib/utils/events';

  // 활성 탭
  let activeTab = $state('today');

  // 데이터
  let todayItems = $state<EventItem[]>([]);
  let inboxItems = $state<EventItem[]>([]);
  let upcomingItems = $state<EventItem[]>([]);
  let activityItems = $state<EventItem[]>([]);
  let loading = $state<Record<string, boolean>>({ today: true, inbox: true, upcoming: true, activity: true });

  // 빠른 행동 기록 (5초 UX 핵심)
  let quickInput = $state('');
  let quickSubmitting = $state(false);
  let quickInputRef = $state<HTMLInputElement | null>(null);

  // 상대 시각 tick (1분)
  let nowTick = $state(Date.now());
  $effect(() => {
    const id = setInterval(() => { nowTick = Date.now(); }, 60_000);
    return () => clearInterval(id);
  });

  onMount(() => {
    loadAll();
  });

  async function loadAll() {
    await Promise.all([loadToday(), loadInbox(), loadActivity(), loadUpcoming()]);
  }

  async function loadToday() {
    loading.today = true;
    try {
      const res = await listToday();
      todayItems = res.items;
    } catch (err) {
      addToast('error', '오늘 일정 로드 실패');
    } finally {
      loading.today = false;
    }
  }

  async function loadInbox() {
    loading.inbox = true;
    try {
      const res = await listInbox();
      inboxItems = res.items;
    } catch (err) {
      addToast('error', 'Inbox 로드 실패');
    } finally {
      loading.inbox = false;
    }
  }

  async function loadActivity() {
    loading.activity = true;
    try {
      // 최근 7일
      const to = new Date();
      const from = new Date(to.getTime() - 7 * 86400_000);
      const res = await listActivity(from.toISOString(), to.toISOString());
      activityItems = res.items;
    } catch (err) {
      addToast('error', '활동 로드 실패');
    } finally {
      loading.activity = false;
    }
  }

  async function loadUpcoming() {
    loading.upcoming = true;
    try {
      const res = await listUpcoming(7);
      upcomingItems = res.items;
    } catch (err) {
      addToast('error', 'Upcoming 로드 실패');
    } finally {
      loading.upcoming = false;
    }
  }

  // 빠른 행동 기록 — Enter 한 번에 저장
  async function submitQuick(e?: Event) {
    e?.preventDefault();
    const title = quickInput.trim();
    if (!title || quickSubmitting) return;
    quickSubmitting = true;
    try {
      const item = await logActivity(title);
      // 새 항목을 Activity 탭 최상단에 즉시 반영
      activityItems = [item, ...activityItems];
      quickInput = '';
      addToast('success', '기록됨');
      // 입력 포커스 유지 (연속 입력)
      quickInputRef?.focus();
    } catch (err) {
      const detail = (err as { detail?: string })?.detail ?? '저장 실패';
      addToast('error', detail);
    } finally {
      quickSubmitting = false;
    }
  }

  // Lifecycle ops
  async function doComplete(item: EventItem) {
    try {
      const updated = await completeEvent(item.id);
      replaceItem(updated);
      addToast('success', '완료 처리');
    } catch (err) {
      addToast('error', '완료 실패');
    }
  }

  async function doCancel(item: EventItem) {
    if (!confirm(`"${item.title}" 취소할까요?`)) return;
    try {
      const updated = await cancelEvent(item.id);
      replaceItem(updated);
      addToast('success', '취소됨');
    } catch (err) {
      addToast('error', '취소 실패');
    }
  }

  async function doDefer(item: EventItem) {
    // 기본 = 내일 같은 시각
    const dt = new Date(Date.now() + 86400_000);
    const isoLocal = dt.toISOString().slice(0, 16);
    const input = prompt('연기할 시각 (YYYY-MM-DDTHH:MM, KST)', isoLocal);
    if (!input) return;
    try {
      const iso = new Date(input).toISOString();
      const updated = await deferEvent(item.id, iso);
      replaceItem(updated);
      addToast('success', '연기됨');
    } catch (err) {
      addToast('error', '연기 실패');
    }
  }

  async function doReactivate(item: EventItem) {
    try {
      const updated = await reactivateEvent(item.id);
      replaceItem(updated);
      addToast('success', '재활성');
    } catch (err) {
      addToast('error', '재활성 실패');
    }
  }

  function replaceItem(item: EventItem) {
    const replacer = (arr: EventItem[]) =>
      arr.map((x) => (x.id === item.id ? item : x));
    todayItems = replacer(todayItems);
    inboxItems = replacer(inboxItems);
    upcomingItems = replacer(upcomingItems);
    activityItems = replacer(activityItems);
  }

  function timeLabel(item: EventItem): string {
    if (item.kind === 'task') {
      return item.due_at ? `마감 ${formatDateTimeKst(item.due_at)}` : '';
    }
    if (item.kind === 'calendar_event') {
      const s = item.start_at ? formatDateTimeKst(item.start_at) : '';
      const e = item.end_at ? formatDateTimeKst(item.end_at) : '';
      return s && e ? `${s} – ${e}` : s;
    }
    // activity_log
    return item.started_at ? relativeTimeKo(item.started_at, nowTick) : '';
  }

  const tabs = [
    { id: 'today', label: '오늘' },
    { id: 'inbox', label: 'Inbox' },
    { id: 'upcoming', label: '예정' },
    { id: 'activity', label: '활동' },
  ];
</script>

<svelte:head>
  <title>events · hyungi PKM</title>
</svelte:head>

<div class="mx-auto max-w-[1240px] space-y-6 px-4 py-6 sm:px-6 lg:px-8">
  <header class="flex items-end justify-between gap-3">
    <div class="space-y-1">
      <h1 class="text-2xl font-semibold">events</h1>
      <p class="text-sm text-slate-500">개인 운영 로그 · 일정 · 할 일 · 회고</p>
    </div>
    <Button variant="secondary" size="sm" icon={Plus} href="/events/new">새 항목</Button>
  </header>

  <!-- 빠른 행동 기록 (5초 UX 핵심) -->
  <form onsubmit={submitQuick} class="flex items-stretch gap-2 rounded-lg border border-slate-200 bg-white p-2 shadow-sm">
    <input
      bind:this={quickInputRef}
      bind:value={quickInput}
      type="text"
      placeholder="방금 한 일 기록… (Enter 저장)"
      class="flex-1 rounded-md border-0 bg-transparent px-2 py-2 text-sm outline-none focus:ring-0"
      disabled={quickSubmitting}
      autocomplete="off"
    />
    <Button type="submit" variant="primary" size="sm" loading={quickSubmitting} disabled={!quickInput.trim()} icon={Plus}>
      기록
    </Button>
  </form>

  <Tabs {tabs} bind:value={activeTab}>
    {#snippet children(activeId)}
      {#if activeId === 'today'}
        {@render eventList(todayItems, loading.today, 'today', Sun, '오늘 할 일이 없습니다')}
      {:else if activeId === 'inbox'}
        {@render eventList(inboxItems, loading.inbox, 'inbox', Inbox, 'Inbox 가 비어 있습니다')}
      {:else if activeId === 'upcoming'}
        {@render eventList(upcomingItems, loading.upcoming, 'upcoming', CalendarClock, '예정된 일정 없음')}
      {:else if activeId === 'activity'}
        {@render eventList(activityItems, loading.activity, 'activity', History, '최근 활동 없음')}
      {/if}
    {/snippet}
  </Tabs>
</div>

{#snippet eventList(items: EventItem[], isLoading: boolean, tabId: string, EmptyIcon: typeof Sun, emptyMsg: string)}
  {#if isLoading}
    <div class="space-y-2">
      {#each Array(3) as _}
        <Skeleton class="h-16 rounded-lg" />
      {/each}
    </div>
  {:else if items.length === 0}
    <EmptyState icon={EmptyIcon} message={emptyMsg} />
  {:else}
    <ul class="space-y-2">
      {#each items as item (item.id)}
        <li>
          <Card class="flex items-start gap-3 p-3 {KIND_COLOR[item.kind]}">
            <div class="flex-1 min-w-0">
              <div class="flex min-w-0 items-center gap-2 text-xs text-slate-500">
                <span>{KIND_LABEL[item.kind]}</span>
                <span class="rounded px-1.5 py-0.5 text-[10px] {STATUS_COLOR[item.status]}">
                  {STATUS_LABEL[item.status]}
                </span>
                {#if item.project_tag}
                  <span class="min-w-0 break-all text-slate-400">#{item.project_tag}</span>
                {/if}
              </div>
              <a href="/events/{item.id}" class="mt-1 block break-words text-sm font-medium hover:underline">
                {item.title}
              </a>
              {#if timeLabel(item)}
                <div class="mt-0.5 text-xs text-slate-500">{timeLabel(item)}</div>
              {/if}
            </div>
            <div class="flex shrink-0 items-center gap-1">
              {#if item.status !== 'done' && item.status !== 'cancelled' && item.kind !== 'activity_log'}
                <Button variant="ghost" size="sm" icon={Check} onclick={() => doComplete(item)} title="완료" />
                <Button variant="ghost" size="sm" icon={Pause} onclick={() => doDefer(item)} title="연기" />
                <Button variant="ghost" size="sm" icon={XIcon} onclick={() => doCancel(item)} title="취소" />
              {:else if (item.status === 'done' || item.status === 'cancelled') && item.kind !== 'activity_log'}
                <Button variant="ghost" size="sm" icon={RotateCcw} onclick={() => doReactivate(item)} title="재활성" />
              {/if}
            </div>
          </Card>
        </li>
      {/each}
    </ul>
  {/if}
{/snippet}
