<script>
  import { getTasks, addTask, updateTask, deleteTask } from './api.js';
  import UserManager from './UserManager.svelte';

  let selectedUserId = $state(null);
  let tasks = $state([]);
  let error = $state('');

  // Add task form state
  let newTitle = $state('');
  let newDueDay = $state('');
  let newDueTime = $state('');
  let showAddForm = $state(false);

  // Edit state
  let editingTaskId = $state(null);
  let editTitle = $state('');
  let editDueDay = $state('');
  let editDueTime = $state('');

  // Confirm delete
  let confirmDeleteId = $state(null);

  async function fetchTasks() {
    if (!selectedUserId) {
      tasks = [];
      return;
    }
    try {
      tasks = await getTasks(selectedUserId);
      // Sort by due_date ascending
      tasks.sort((a, b) => a.due_date - b.due_date);
      error = '';
    } catch (e) {
      error = e.message;
    }
  }

  // Refetch when selected user changes
  $effect(() => {
    if (selectedUserId) {
      fetchTasks();
    } else {
      tasks = [];
    }
  });

  async function handleAddTask(e) {
    e.preventDefault();
    if (!newTitle.trim() || !newDueDay || !newDueTime) return;

    const dueTimestamp = Math.floor(new Date(`${newDueDay}T${newDueTime}`).getTime() / 1000);
    try {
      await addTask(selectedUserId, newTitle.trim(), dueTimestamp);
      newTitle = '';
      newDueDay = '';
      newDueTime = '';
      showAddForm = false;
      await fetchTasks();
    } catch (e) {
      error = e.message;
    }
  }

  async function handleToggleComplete(task) {
    try {
      await updateTask(task.id, { completed: !task.completed });
      await fetchTasks();
    } catch (e) {
      error = e.message;
    }
  }

  function startEditing(task) {
    editingTaskId = task.id;
    editTitle = task.title;
    const parts = formatDateForInput(task.due_date);
    editDueDay = parts.day;
    editDueTime = parts.time;
  }

  async function saveEdit(e) {
    e.preventDefault();
    if (!editTitle.trim()) return;

    const dueTimestamp = Math.floor(new Date(`${editDueDay}T${editDueTime}`).getTime() / 1000);
    try {
      await updateTask(editingTaskId, {
        title: editTitle.trim(),
        due_date: dueTimestamp
      });
      editingTaskId = null;
      await fetchTasks();
    } catch (e) {
      error = e.message;
    }
  }

  async function handleDelete(id) {
    try {
      await deleteTask(id);
      confirmDeleteId = null;
      await fetchTasks();
    } catch (e) {
      error = e.message;
    }
  }

  function formatDateForInput(timestamp) {
    const d = new Date(timestamp * 1000);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const dayNum = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const mins = String(d.getMinutes()).padStart(2, '0');
    return { day: `${year}-${month}-${dayNum}`, time: `${hours}:${mins}` };
  }

  function setNowForNewTask() {
    const parts = formatDateForInput(Date.now() / 1000);
    newDueDay = parts.day;
    newDueTime = parts.time;
  }

  function formatRelativeDate(timestamp) {
    const now = Date.now() / 1000;
    const diff = timestamp - now;
    const absDiff = Math.abs(diff);

    if (absDiff < 3600) {
      const mins = Math.round(absDiff / 60);
      return diff < 0 ? `${mins}m ago` : `in ${mins}m`;
    }
    if (absDiff < 86400) {
      const hours = Math.round(absDiff / 3600);
      return diff < 0 ? `${hours}h ago` : `in ${hours}h`;
    }
    const days = Math.round(absDiff / 86400);
    return diff < 0 ? `${days}d ago` : `in ${days}d`;
  }

  function isOverdue(timestamp) {
    return timestamp < Date.now() / 1000;
  }
</script>

<div class="task-manager">
  <UserManager bind:selectedUserId onUsersChanged={fetchTasks} />

  {#if selectedUserId}
    <div class="task-header">
      <h2 class="task-title">Tasks</h2>
      {#if !showAddForm}
        <button class="add-task-btn" onclick={() => { showAddForm = true; setNowForNewTask(); }}>+ Add Task</button>
      {/if}
    </div>

    {#if showAddForm}
      <form class="add-task-form" onsubmit={handleAddTask}>
        <!-- svelte-ignore a11y_autofocus -->
        <input
          type="text"
          bind:value={newTitle}
          placeholder="Task title..."
          class="task-input"
          autofocus
        />
        <div class="date-time-row">
          <label class="date-time-field">
            <span class="field-label">Date</span>
            <input type="date" bind:value={newDueDay} class="task-date-input" />
          </label>
          <label class="date-time-field">
            <span class="field-label">Time</span>
            <input type="time" bind:value={newDueTime} class="task-time-input" />
          </label>
        </div>
        <div class="form-actions">
          <button type="submit" class="btn-primary" disabled={!newTitle.trim() || !newDueDay || !newDueTime}>Add</button>
          <button type="button" class="btn-secondary" onclick={() => { showAddForm = false; newTitle = ''; newDueDay = ''; newDueTime = ''; }}>Cancel</button>
        </div>
      </form>
    {/if}

    <div class="task-list">
      {#each tasks as task}
        <div class="task-item {task.completed ? 'completed' : ''} {isOverdue(task.due_date) && !task.completed ? 'overdue' : ''}">
          {#if editingTaskId === task.id}
            <form class="edit-form" onsubmit={saveEdit}>
              <input type="text" bind:value={editTitle} class="task-input" />
              <div class="date-time-row">
                <label class="date-time-field">
                  <span class="field-label">Date</span>
                  <input type="date" bind:value={editDueDay} class="task-date-input" />
                </label>
                <label class="date-time-field">
                  <span class="field-label">Time</span>
                  <input type="time" bind:value={editDueTime} class="task-time-input" />
                </label>
              </div>
              <div class="form-actions">
                <button type="submit" class="btn-primary btn-sm">Save</button>
                <button type="button" class="btn-secondary btn-sm" onclick={() => editingTaskId = null}>Cancel</button>
              </div>
            </form>
          {:else}
            <div class="task-left">
              <input
                type="checkbox"
                checked={task.completed}
                onchange={() => handleToggleComplete(task)}
                class="task-checkbox"
              />
              <div class="task-info">
                <span class="task-text">{task.title}</span>
                <span class="task-due {isOverdue(task.due_date) && !task.completed ? 'text-overdue' : ''}">
                  {formatRelativeDate(task.due_date)}
                </span>
              </div>
            </div>
            <div class="task-actions">
              <button class="action-btn" onclick={() => startEditing(task)} title="Edit">✏️</button>
              {#if confirmDeleteId === task.id}
                <button class="action-btn text-danger" onclick={() => handleDelete(task.id)} title="Confirm">✓</button>
                <button class="action-btn" onclick={() => confirmDeleteId = null} title="Cancel">✕</button>
              {:else}
                <button class="action-btn" onclick={() => confirmDeleteId = task.id} title="Delete">🗑️</button>
              {/if}
            </div>
          {/if}
        </div>
      {:else}
        <div class="empty-state">No tasks yet. Add one above!</div>
      {/each}
    </div>
  {:else}
    <div class="empty-state">Select or add a user to see their tasks.</div>
  {/if}

  {#if error}
    <div class="task-error">{error}</div>
  {/if}
</div>

<style>
  .task-manager {
    width: 100%;
  }

  .task-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
  }

  .task-title {
    font-size: 14px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--color-text-primary);
  }

  .add-task-btn {
    padding: 6px 14px;
    border-radius: 8px;
    border: 1px solid var(--color-accent);
    background: color-mix(in srgb, var(--color-accent) 10%, transparent);
    color: var(--color-accent);
    cursor: pointer;
    font-size: 12px;
    font-weight: 600;
    transition: all 0.15s;
  }

  .add-task-btn:hover {
    background: color-mix(in srgb, var(--color-accent) 20%, transparent);
  }

  .add-task-form, .edit-form {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 12px;
    border-radius: 10px;
    border: 1px solid var(--color-border);
    background: var(--color-bg-card);
    margin-bottom: 12px;
  }

  .task-input {
    padding: 8px 12px;
    border-radius: 8px;
    border: 1px solid var(--color-border);
    background: var(--color-bg-primary);
    color: var(--color-text-primary);
    font-size: 13px;
    outline: none;
    width: 100%;
    box-sizing: border-box;
  }

  .task-input:focus {
    border-color: var(--color-accent);
  }

  .date-time-row {
    display: flex;
    gap: 8px;
  }

  .date-time-field {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .date-time-field:first-child {
    flex: 1;
  }

  .field-label {
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--color-text-secondary);
  }

  .task-date-input {
    padding: 8px 12px;
    border-radius: 8px;
    border: 1px solid var(--color-border);
    background: var(--color-bg-primary);
    color: var(--color-text-primary);
    font-size: 13px;
    outline: none;
    color-scheme: dark;
    flex: 1;
    cursor: pointer;
    position: relative;
  }

  .task-time-input {
    padding: 8px 12px;
    border-radius: 8px;
    border: 1px solid var(--color-border);
    background: var(--color-bg-primary);
    color: var(--color-text-primary);
    font-size: 13px;
    outline: none;
    color-scheme: dark;
    width: 110px;
    cursor: pointer;
    position: relative;
  }

  /* Make the native picker icon cover the entire input (Chrome/Edge only) */
  .task-date-input::-webkit-calendar-picker-indicator,
  .task-time-input::-webkit-calendar-picker-indicator {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: auto;
    height: auto;
    opacity: 0;
    cursor: pointer;
  }

  .task-date-input:focus, .task-time-input:focus {
    border-color: var(--color-accent);
  }

  .form-actions {
    display: flex;
    gap: 6px;
  }

  .btn-primary {
    padding: 6px 16px;
    border-radius: 8px;
    border: none;
    background: var(--color-accent);
    color: white;
    cursor: pointer;
    font-size: 12px;
    font-weight: 600;
    transition: filter 0.15s;
  }

  .btn-primary:hover {
    filter: brightness(1.1);
  }

  .btn-primary:disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }

  .btn-secondary {
    padding: 6px 16px;
    border-radius: 8px;
    border: 1px solid var(--color-border);
    background: transparent;
    color: var(--color-text-secondary);
    cursor: pointer;
    font-size: 12px;
    transition: all 0.15s;
  }

  .btn-secondary:hover {
    background: var(--color-bg-card-hover);
  }

  .btn-sm {
    padding: 4px 10px;
    font-size: 11px;
  }

  .task-list {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .task-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 14px;
    border-radius: 10px;
    border: 1px solid var(--color-border);
    background: var(--color-bg-card);
    transition: all 0.15s;
  }

  .task-item:hover {
    background: var(--color-bg-card-hover);
  }

  .task-item.completed {
    opacity: 0.5;
  }

  .task-item.overdue {
    border-color: color-mix(in srgb, var(--color-danger) 40%, transparent);
  }

  .task-left {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
    min-width: 0;
  }

  .task-checkbox {
    width: 16px;
    height: 16px;
    accent-color: var(--color-accent);
    cursor: pointer;
    flex-shrink: 0;
  }

  .task-info {
    display: flex;
    flex-direction: column;
    gap: 2px;
    min-width: 0;
  }

  .task-text {
    font-size: 13px;
    color: var(--color-text-primary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .completed .task-text {
    text-decoration: line-through;
    color: var(--color-text-secondary);
  }

  .task-due {
    font-size: 10px;
    color: var(--color-text-secondary);
    font-weight: 500;
  }

  .text-overdue {
    color: var(--color-danger) !important;
  }

  .text-danger {
    color: var(--color-danger);
  }

  .task-actions {
    display: flex;
    gap: 4px;
    align-items: center;
    flex-shrink: 0;
  }

  .action-btn {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 12px;
    padding: 4px;
    border-radius: 4px;
    transition: background 0.15s;
    opacity: 0.6;
  }

  .action-btn:hover {
    opacity: 1;
    background: var(--color-bg-card-hover);
  }

  .empty-state {
    text-align: center;
    padding: 32px;
    color: var(--color-text-secondary);
    font-size: 13px;
  }

  .task-error {
    margin-top: 8px;
    padding: 6px 10px;
    border-radius: 6px;
    background: color-mix(in srgb, var(--color-danger) 10%, transparent);
    border: 1px solid color-mix(in srgb, var(--color-danger) 20%, transparent);
    color: var(--color-danger);
    font-size: 11px;
  }
</style>
