package views

import (
	"strconv"
	"xtablo-backend/internal/web/ui"
)

// TabloDetailPage renders the full tablo detail page.
templ TabloDetailPage(vm TabloDetailViewModel) {
	<div class="tablo-detail-page">
		@TabloDetailHeader(vm)
		@TabloDetailTabBar(vm.TabloID)
		<div id="tab-content">
			@TabloDetailKanbanBoard(vm.Columns, vm.TabloID)
			if len(vm.Etapes) > 0 {
				@TabloDetailEtapesSection(vm.Etapes)
			}
		</div>
		@TabloDetailSortableScript(vm.TabloID)
	</div>
}

// TabloDetailHeader renders the header with avatar, title, and metadata row.
templ TabloDetailHeader(vm TabloDetailViewModel) {
	<header class="tablo-detail-header">
		<div class="tablo-detail-title-row">
			<div class="tablo-detail-avatar" style={ "background:" + vm.Color }>{ vm.Initial }</div>
			<h1 class="tablo-detail-title">{ vm.TabloName }</h1>
		</div>
		<div class="tablo-metadata-row">
			<span class="tablo-meta-segment">
				<div class="w-6 h-6 rounded-full bg-gray-300 flex items-center justify-center text-xs font-medium text-white">{ vm.Initial }</div>
				{ " " + vm.OwnerName }
			</span>
			<span class="tablo-meta-segment">
				@ActionIcon("calendar")
				if vm.DueDate != "" {
					{ vm.DueDate }
				} else {
					{ "—" }
				}
			</span>
			<span class="tablo-meta-segment">
				@ui.Badge(ui.BadgeProps{Label: vm.StatusLabel, Variant: badgeVariantForTone(vm.StatusTone)})
			</span>
			<span class="tablo-meta-segment tablo-meta-progress">
				<div class="project-progress-track" style="min-width:120px">
					<div class="tablo-progress-bar" style={ "width:" + vm.ProgressLabel }></div>
				</div>
				<strong>{ vm.ProgressLabel }</strong>
			</span>
		</div>
	</header>
}

// TabloDetailTabBar renders the HTMX tab navigation.
templ TabloDetailTabBar(tabloID string) {
	<nav class="tablo-tab-bar">
		<a
			hx-get={ string(templ.SafeURL("/tablos/" + tabloID + "/overview")) }
			hx-target="#tab-content"
			hx-push-url="true"
			class="tab-nav-item"
		>Vue d&apos;ensemble</a>
		<a
			hx-get={ string(templ.SafeURL("/tablos/" + tabloID + "/tasks")) }
			hx-target="#tab-content"
			hx-push-url="true"
			class="tab-nav-item tab-nav-item--active"
		>Tâches</a>
		<a
			hx-get={ string(templ.SafeURL("/tablos/" + tabloID + "/files")) }
			hx-target="#tab-content"
			hx-push-url="true"
			class="tab-nav-item"
		>Fichiers</a>
		<a
			hx-get={ string(templ.SafeURL("/tablos/" + tabloID + "/discussion")) }
			hx-target="#tab-content"
			hx-push-url="true"
			class="tab-nav-item"
		>Discussion</a>
		<a
			hx-get={ string(templ.SafeURL("/tablos/" + tabloID + "/events")) }
			hx-target="#tab-content"
			hx-push-url="true"
			class="tab-nav-item"
		>Événements</a>
	</nav>
}

// TabloDetailKanbanBoard renders the full kanban board with 4 columns.
templ TabloDetailKanbanBoard(columns []TabloDetailColumnView, tabloID string) {
	<div class="tablo-kanban-board">
		for _, col := range columns {
			@TabloDetailKanbanColumn(col, tabloID)
		}
	</div>
}

// TabloDetailKanbanColumn renders a single kanban column with header, task list, reorder form, and create zone.
templ TabloDetailKanbanColumn(col TabloDetailColumnView, tabloID string) {
	<div class="tablo-kanban-column" data-status={ col.ID }>
		<div class="tablo-kanban-column-header">
			<span class="tablo-kanban-column-title">{ col.Label }</span>
			<span class="tablo-kanban-task-count">{ strconv.Itoa(len(col.Tasks)) }</span>
			<a class="tablo-kanban-add-link" href={ templ.SafeURL(col.CreateHref) }>+ Ajouter</a>
		</div>
		<div id={ "task-list-" + col.ID } class="task-list sortable-column" data-status={ col.ID }>
			if len(col.Tasks) == 0 {
				<div class="tablo-kanban-empty">Aucune tâche</div>
			} else {
				for _, task := range col.Tasks {
					@TabloDetailTaskCard(task, tabloID)
				}
			}
		</div>
		<form
			id={ "reorder-form-" + col.ID }
			style="display:none"
			hx-post={ "/tablos/" + tabloID + "/tasks/reorder?status=" + col.ID }
			hx-target={ "#task-list-" + col.ID }
			hx-swap="innerHTML"
		></form>
		<div id={ "create-zone-" + col.ID }></div>
	</div>
}

// TabloDetailTaskCard renders a single task card with drag handle and delete button.
templ TabloDetailTaskCard(task TabloDetailTaskView, tabloID string) {
	<article class="task-card" data-task-id={ task.ID }>
		<div class="task-card-top-row">
			<span class="task-drag-handle" aria-hidden="true">⠿</span>
			<span class="task-card-title">{ task.Title }</span>
			@ui.IconButton(ui.IconButtonProps{
				Label:   "Supprimer la tâche",
				Icon:    "trash",
				Variant: ui.IconButtonVariantDanger,
				Tone:    ui.IconButtonToneGhost,
				Type:    "button",
				Attrs: templ.Attributes{
					"class":      "task-card-delete",
					"hx-delete":  task.DeleteHref,
					"hx-target":  "#app-main-content",
					"hx-swap":    "outerHTML",
					"hx-confirm": "Supprimer cette tâche ?",
				},
			})
		</div>
	</article>
}

// TabloDetailEtapesSection renders the etapes summary list below the kanban board.
templ TabloDetailEtapesSection(etapes []TabloDetailEtapeView) {
	<section class="tablo-etapes-section">
		<h2>Étapes</h2>
		<ul>
			for _, etape := range etapes {
				<li class="tablo-etape-row">
					<span class="tablo-etape-name">{ etape.Name }</span>
					<span class="tablo-etape-count">{ strconv.Itoa(etape.TaskCount) + " tâche(s)" }</span>
				</li>
			}
		</ul>
	</section>
}

// TabloDetailSortableScript emits the Sortable.js initialization script.
templ TabloDetailSortableScript(tabloID string) {
	@templ.Raw(`<script>
function initTabloDetailSortable() {
  document.querySelectorAll('.sortable-column').forEach(function(el) {
    if (el._sortable) return;
    el._sortable = Sortable.create(el, {
      group: 'tablo-tasks',
      animation: 150,
      handle: '.task-drag-handle',
      draggable: '.task-card',
      onEnd: function(evt) {
        var form = document.getElementById('reorder-form-' + el.dataset.status);
        if (form) form.requestSubmit();
      }
    });
  });
}
document.addEventListener('DOMContentLoaded', initTabloDetailSortable);
document.addEventListener('htmx:afterSettle', initTabloDetailSortable);
</script>`)
}
