<?= $this->extend('layouts/mobile') ?>

<?= $this->section('header') ?>
<?= view('layouts/_inner_header', [
    'title'    => ($mode ?? 'create') === 'edit' ? 'Edit Task' : 'Add Task',
    'backHref' => $backHref ?? site_url('dashboard'),
]) ?>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<?php
$mode       = $mode ?? 'create';
$values     = $values ?? [];
$errors     = $errors ?? [];
$categories = $categories ?? [];
$hasCategories = ! empty($hasCategories);
$tieasy     = config('Tieasy');
$priorityColors = [1 => 'q-red', 2 => 'q-green', 3 => 'q-blue', 4 => 'q-orange'];
$val = static fn (string $key): string => (string) ($values[$key] ?? '');
$invalid = static fn (string $key): string => isset($errors[$key]) ? ' is-invalid' : '';
$action = $mode === 'edit'
    ? site_url('tasks/' . (int) ($taskId ?? 0) . '/edit')
    : site_url('tasks/create');
?>

<form class="auth-form task-form" method="post" action="<?= $action ?>">
    <?= csrf_field() ?>

    <label class="field-label" for="task_title">Task Title <span class="req">*</span></label>
    <input class="field-input<?= $invalid('title') ?>" type="text" id="task_title" name="title" maxlength="255" required placeholder="Task title" value="<?= esc($val('title')) ?>">
    <?php if (isset($errors['title'])): ?>
        <p class="field-error" role="alert"><?= esc($errors['title']) ?></p>
    <?php endif; ?>

    <div class="field-row">
        <div>
            <label class="field-label" for="due_date">Due Date</label>
            <input class="field-input<?= $invalid('due_date') ?>" type="date" id="due_date" name="due_date" value="<?= esc($val('due_date')) ?>">
            <p class="field-hint">Leave blank if there is no due date. Recurring tasks use this as the required start date.</p>
            <?php if (isset($errors['due_date'])): ?>
                <p class="field-error" role="alert"><?= esc($errors['due_date']) ?></p>
            <?php endif; ?>
        </div>
        <div>
            <label class="field-label" for="due_time">Due Time</label>
            <input class="field-input<?= $invalid('due_time') ?>" type="time" id="due_time" name="due_time" value="<?= esc($val('due_time')) ?>">
            <?php if (isset($errors['due_time'])): ?>
                <p class="field-error" role="alert"><?= esc($errors['due_time']) ?></p>
            <?php endif; ?>
        </div>
    </div>

    <label class="recurring-row">
        <input type="checkbox" id="is_recurring" name="is_recurring" value="1" <?= ($val('is_recurring') === '1' || ! empty($errors['is_recurring'])) ? 'checked' : '' ?>>
        <span>Select to mark as recurring task</span>
    </label>
    <?php
    $recurringOn = $val('is_recurring') === '1';
    $weekDays = $values['weekly_days'] ?? [];
    $weekDays = is_array($weekDays) ? array_map('strval', $weekDays) : [];
    $recType = $val('recurrence_type') !== '' ? $val('recurrence_type') : 'daily';
    $monthType = $val('monthly_type') !== '' ? $val('monthly_type') : 'day_of_month';
    ?>
    <div class="recurrence-panel" id="recurrence-panel" <?= $recurringOn || $val('is_recurring') === '1' ? '' : 'hidden' ?>>
        <p class="field-label">Repeat</p>
        <div class="type-pills" role="radiogroup" aria-label="Recurrence type">
            <?php foreach (['daily' => 'Daily', 'weekly' => 'Weekly', 'monthly' => 'Monthly'] as $type => $label): ?>
                <label class="type-pill <?= $recType === $type ? 'is-selected' : '' ?>">
                    <input type="radio" name="recurrence_type" value="<?= esc($type) ?>" <?= $recType === $type ? 'checked' : '' ?>>
                    <span><?= esc($label) ?></span>
                </label>
            <?php endforeach; ?>
        </div>
        <?php if (isset($errors['recurrence_type'])): ?>
            <p class="field-error" role="alert"><?= esc($errors['recurrence_type']) ?></p>
        <?php endif; ?>

        <p class="recurrence-copy" data-recurrence-copy>
            <?php if ($recType === 'weekly'): ?>
                Occurs every <?= (int) ($val('interval_value') ?: 1) ?> week(s).
            <?php elseif ($recType === 'monthly'): ?>
                Occurs every <?= (int) ($val('interval_value') ?: 1) ?> month(s).
            <?php else: ?>
                Occurs on a daily basis.
            <?php endif; ?>
        </p>

        <label class="field-label" for="interval_value">Repeat every</label>
        <div class="interval-row">
            <input class="field-input interval-input<?= $invalid('interval_value') ?>" type="number" id="interval_value" name="interval_value" min="1" max="365" value="<?= esc($val('interval_value') !== '' ? $val('interval_value') : '1') ?>">
            <span class="interval-unit" data-interval-unit><?= $recType === 'weekly' ? 'week(s)' : ($recType === 'monthly' ? 'month(s)' : 'day(s)') ?></span>
        </div>
        <?php if (isset($errors['interval_value'])): ?>
            <p class="field-error" role="alert"><?= esc($errors['interval_value']) ?></p>
        <?php endif; ?>

        <div class="recurrence-weekly" data-recurrence-section="weekly" <?= $recType === 'weekly' ? '' : 'hidden' ?>>
            <p class="field-label">Repeat on</p>
            <div class="weekday-pills">
                <?php foreach ($tieasy->weekdays as $day => $label): ?>
                    <label class="weekday-pill">
                        <input type="checkbox" name="weekly_days[]" value="<?= (int) $day ?>" <?= in_array((string) $day, $weekDays, true) ? 'checked' : '' ?>>
                        <span><?= esc(substr($label, 0, 3)) ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
            <?php if (isset($errors['weekly_days'])): ?>
                <p class="field-error" role="alert"><?= esc($errors['weekly_days']) ?></p>
            <?php endif; ?>
        </div>

        <div class="recurrence-monthly" data-recurrence-section="monthly" <?= $recType === 'monthly' ? '' : 'hidden' ?>>
            <p class="field-label">Repeat on</p>
            <label class="choice-row">
                <input type="radio" name="monthly_type" value="day_of_month" <?= $monthType === 'day_of_month' ? 'checked' : '' ?>>
                <span>Day</span>
                <input class="field-input month-day-input<?= $invalid('monthly_day') ?>" type="number" name="monthly_day" min="1" max="31" value="<?= esc($val('monthly_day')) ?>">
                <span>of the month</span>
            </label>
            <?php if (isset($errors['monthly_day'])): ?>
                <p class="field-error" role="alert"><?= esc($errors['monthly_day']) ?></p>
            <?php endif; ?>
            <label class="choice-row">
                <input type="radio" name="monthly_type" value="weekday_position" <?= $monthType === 'weekday_position' ? 'checked' : '' ?>>
                <span>
                    <select class="field-input inline-select<?= $invalid('monthly_week_position') ?>" name="monthly_week_position">
                        <?php foreach (['first' => 'First', 'second' => 'Second', 'third' => 'Third', 'fourth' => 'Fourth', 'last' => 'Last'] as $pos => $posLabel): ?>
                            <option value="<?= esc($pos) ?>" <?= $val('monthly_week_position') === $pos ? 'selected' : '' ?>><?= esc($posLabel) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select class="field-input inline-select<?= $invalid('monthly_weekday') ?>" name="monthly_weekday">
                        <?php foreach ($tieasy->weekdays as $day => $label): ?>
                            <option value="<?= (int) $day ?>" <?= $val('monthly_weekday') === (string) $day ? 'selected' : '' ?>><?= esc($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </span>
            </label>
            <?php if (isset($errors['monthly_type'])): ?>
                <p class="field-error" role="alert"><?= esc($errors['monthly_type']) ?></p>
            <?php endif; ?>
            <?php if (isset($errors['monthly_week_position'])): ?>
                <p class="field-error" role="alert"><?= esc($errors['monthly_week_position']) ?></p>
            <?php endif; ?>
            <?php if (isset($errors['monthly_weekday'])): ?>
                <p class="field-error" role="alert"><?= esc($errors['monthly_weekday']) ?></p>
            <?php endif; ?>
        </div>

        <label class="field-label" for="recurrence_end_date">Ends (optional)</label>
        <input class="field-input<?= $invalid('recurrence_end_date') ?>" type="date" id="recurrence_end_date" name="recurrence_end_date" value="<?= esc($val('recurrence_end_date')) ?>">
        <?php if (isset($errors['recurrence_end_date'])): ?>
            <p class="field-error" role="alert"><?= esc($errors['recurrence_end_date']) ?></p>
        <?php endif; ?>
        <p class="field-hint">Due Time above is used for each occurrence. Leave it blank for no time.</p>
    </div>
    <?php if (isset($errors['is_recurring'])): ?>
        <p class="field-error" role="alert"><?= esc($errors['is_recurring']) ?></p>
    <?php endif; ?>

    <p class="field-label">Priority <span class="req">*</span></p>
    <div class="priority-grid" role="radiogroup" aria-label="Priority">
        <?php foreach ($tieasy->priorities as $id => $label): ?>
            <label class="priority-choice <?= esc($priorityColors[$id] ?? '') ?> <?= $val('priority') === (string) $id ? 'is-selected' : '' ?>">
                <input type="radio" name="priority" value="<?= (int) $id ?>" <?= $val('priority') === (string) $id ? 'checked' : '' ?>>
                <span><?= esc($label) ?></span>
            </label>
        <?php endforeach; ?>
    </div>
    <?php if (isset($errors['priority'])): ?>
        <p class="field-error" role="alert"><?= esc($errors['priority']) ?></p>
    <?php endif; ?>

    <label class="field-label" for="category_id">Category <span class="req">*</span></label>
    <?php if (! $hasCategories): ?>
        <p class="field-error" role="alert"><?= esc($errors['category_id'] ?? \App\Services\TaskService::MSG_NO_CATEGORIES) ?></p>
        <a class="text-link" href="<?= site_url('categories') ?>">Go to Category Manager</a>
    <?php else: ?>
        <select class="field-input<?= $invalid('category_id') ?>" id="category_id" name="category_id" required>
            <option value="">- Select -</option>
            <?php foreach ($categories as $category): ?>
                <option value="<?= (int) $category['id'] ?>" <?= $val('category_id') === (string) $category['id'] ? 'selected' : '' ?>><?= esc($category['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <?php if (isset($errors['category_id'])): ?>
            <p class="field-error" role="alert"><?= esc($errors['category_id']) ?></p>
        <?php endif; ?>
    <?php endif; ?>

    <?php if ($hasCategories): ?>
        <button class="btn-primary" type="submit">Save &amp; Continue</button>
    <?php endif; ?>
    <a class="text-link" href="<?= esc($backHref ?? site_url('dashboard')) ?>">Cancel</a>
</form>
<?= $this->endSection() ?>
