<script lang="ts">
  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 TextInput from '$lib/components/ui/TextInput.svelte';
  import Textarea from '$lib/components/ui/Textarea.svelte';
  import { ArrowLeft } from 'lucide-svelte';
  import {
    type EventKind,
    type EventCreatePayload,
    KIND_LABEL,
    createEvent,
  } from '$lib/utils/events';

  let kind = $state<EventKind>('task');
  let title = $state('');
  let description = $state('');
  let dueAt = $state('');
  let startAt = $state('');
  let endAt = $state('');
  let allDay = $state(false);
  let startedAt = $state('');
  let endedAt = $state('');
  let priority = $state<number | ''>('');
  let projectTag = $state('');
  let submitting = $state(false);

  function localToIso(s: string): string | null {
    if (!s) return null;
    const d = new Date(s);
    return isNaN(d.getTime()) ? null : d.toISOString();
  }

  async function submit() {
    if (submitting) return;
    if (!title.trim()) {
      addToast('error', '제목을 입력하세요');
      return;
    }
    submitting = true;
    try {
      const payload: EventCreatePayload = {
        title: title.trim(),
        kind,
      };
      if (description.trim()) payload.description = description.trim();
      if (kind === 'task') {
        if (dueAt) payload.due_at = localToIso(dueAt);
        if (startAt) payload.start_at = localToIso(startAt);
      } else if (kind === 'calendar_event') {
        if (!startAt) {
          addToast('error', 'calendar_event 는 시작 시간 필수');
          submitting = false;
          return;
        }
        payload.start_at = localToIso(startAt);
        if (endAt) payload.end_at = localToIso(endAt);
        payload.all_day = allDay;
      } else if (kind === 'activity_log') {
        if (startedAt) payload.started_at = localToIso(startedAt);
        if (endedAt) payload.ended_at = localToIso(endedAt);
        // 모두 비우면 서버 default (now())
      }
      if (priority !== '') payload.priority = Number(priority);
      if (projectTag.trim()) payload.project_tag = projectTag.trim();

      const item = await createEvent(payload);
      addToast('success', '생성됨');
      goto(`/events/${item.id}`);
    } catch (err) {
      const detail = (err as { detail?: string })?.detail ?? '생성 실패';
      addToast('error', detail);
    } finally {
      submitting = false;
    }
  }
</script>

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

<div class="mx-auto max-w-xl space-y-4 px-4 py-6">
  <div class="flex items-center gap-2">
    <Button variant="ghost" size="sm" icon={ArrowLeft} href="/events" />
    <h1 class="text-xl font-semibold">새 events</h1>
  </div>

  <Card class="space-y-4 p-4">
    <div>
      <span class="block text-xs text-slate-500">유형</span>
      <div class="mt-1 flex gap-2">
        {#each ['task', 'calendar_event', 'activity_log'] as k}
          <button
            type="button"
            class="rounded-md border px-3 py-1.5 text-sm transition {kind === k ? 'border-indigo-500 bg-indigo-50 text-indigo-700' : 'border-slate-200 hover:bg-slate-50'}"
            onclick={() => (kind = k as EventKind)}
          >
            {KIND_LABEL[k as EventKind]}
          </button>
        {/each}
      </div>
    </div>

    <label class="block">
      <span class="block text-xs text-slate-500">제목 *</span>
      <TextInput bind:value={title} placeholder="할 일 / 일정 / 기록한 행동" />
    </label>

    <label class="block">
      <span class="block text-xs text-slate-500">설명 (markdown, 선택)</span>
      <Textarea bind:value={description} rows={3} />
    </label>

    {#if kind === 'task'}
      <label class="block">
        <span class="block text-xs text-slate-500">마감 (due_at, 선택)</span>
        <input type="datetime-local" bind:value={dueAt} class="rounded-md border border-slate-200 px-2 py-1 text-sm" />
      </label>
      <label class="block">
        <span class="block text-xs text-slate-500">시작 (start_at, 선택 — "14:00 전화" 같은 경우)</span>
        <input type="datetime-local" bind:value={startAt} class="rounded-md border border-slate-200 px-2 py-1 text-sm" />
      </label>
    {:else if kind === 'calendar_event'}
      <div class="flex flex-wrap gap-3">
        <label class="block">
          <span class="block text-xs text-slate-500">시작 (start_at) *</span>
          <input type="datetime-local" bind:value={startAt} class="rounded-md border border-slate-200 px-2 py-1 text-sm" required />
        </label>
        <label class="block">
          <span class="block text-xs text-slate-500">종료 (end_at, 선택)</span>
          <input type="datetime-local" bind:value={endAt} class="rounded-md border border-slate-200 px-2 py-1 text-sm" />
        </label>
      </div>
      <label class="inline-flex items-center gap-2 text-sm">
        <input type="checkbox" bind:checked={allDay} />
        <span>all-day</span>
      </label>
    {:else if kind === 'activity_log'}
      <p class="text-xs text-slate-500">
        비워두면 시작·종료 모두 <code>now()</code> 로 기록됩니다 (방금 한 일).
      </p>
      <div class="flex flex-wrap gap-3">
        <label class="block">
          <span class="block text-xs text-slate-500">시작 시각 (선택)</span>
          <input type="datetime-local" bind:value={startedAt} class="rounded-md border border-slate-200 px-2 py-1 text-sm" />
        </label>
        <label class="block">
          <span class="block text-xs text-slate-500">종료 시각 (선택)</span>
          <input type="datetime-local" bind:value={endedAt} class="rounded-md border border-slate-200 px-2 py-1 text-sm" />
        </label>
      </div>
    {/if}

    <div class="flex flex-wrap gap-3">
      <label class="block">
        <span class="block text-xs text-slate-500">우선순위 (1–4)</span>
        <input type="number" min="1" max="4" bind:value={priority} class="w-20 rounded-md border border-slate-200 px-2 py-1 text-sm" />
      </label>
      <label class="block">
        <span class="block text-xs text-slate-500">프로젝트 태그</span>
        <TextInput bind:value={projectTag} placeholder="예: doc-server" />
      </label>
    </div>

    <div class="flex justify-end">
      <Button variant="primary" size="md" loading={submitting} onclick={submit}>생성</Button>
    </div>
  </Card>
</div>
