<script lang="ts">
  import { auth } from '$lib/stores/auth';
  import { toast } from '$lib/stores/toast';
  import { api } from '$lib/utils/api';
  import { createEventDispatcher } from 'svelte';

  export let issue: any;
  export let ticketId: string;

  const dispatch = createEventDispatcher();

  const STATUSES = [
    { value: 'OPEN', label: 'Abierto', color: 'blue' },
    { value: 'IN_PROGRESS', label: 'En Progreso', color: 'indigo' },
    { value: 'RESOLVED', label: 'Resuelto', color: 'green' },
    { value: 'CLOSED', label: 'Cerrado', color: 'gray' }
  ];

  const PRIORITIES = [
    { value: 'LOW', label: 'Baja', color: 'gray' },
    { value: 'MEDIUM', label: 'Media', color: 'blue' },
    { value: 'HIGH', label: 'Alta', color: 'orange' },
    { value: 'URGENT', label: 'Urgente', color: 'red' }
  ];

  let isUpdatingStatus = false;
  let isDeleting = false;

  $: canManage = $auth.user?.role === 'ADMIN' || $auth.user?.role === 'CLIENT_ADMIN';
  $: statusObj = STATUSES.find(s => s.value === issue.status) || STATUSES[0];
  $: priorityObj = PRIORITIES.find(p => p.value === issue.priority) || PRIORITIES[1];

  function formatDate(dateString: string) {
    return new Date(dateString).toLocaleString('es-ES', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  async function handleStatusChange(e: Event) {
    const newStatus = (e.target as HTMLSelectElement).value;
    isUpdatingStatus = true;
    try {
      const updated = await api.patch(`/tickets/${ticketId}/issues/${issue.id}/status`, {
        status: newStatus
      });
      issue = updated;
      toast.success('Estado actualizado');
      dispatch('updated', updated);
    } catch (err: any) {
      toast.error(err.message || 'Error al actualizar estado');
    } finally {
      isUpdatingStatus = false;
    }
  }

  async function handleDelete() {
    if (!confirm('¿Eliminar este asunto? Esta acción no se puede deshacer.')) return;
    isDeleting = true;
    try {
      await api.delete(`/tickets/${ticketId}/issues/${issue.id}`);
      toast.success('Asunto eliminado');
      dispatch('deleted', issue.id);
      dispatch('close');
    } catch (err: any) {
      toast.error(err.message || 'Error al eliminar');
    } finally {
      isDeleting = false;
    }
  }

  function handleClose() {
    dispatch('close');
  }
</script>

<div class="fixed inset-0 z-50 overflow-y-auto">
  <div class="flex min-h-full items-center justify-center p-4">
    <div
      class="fixed inset-0 bg-gray-500 bg-opacity-75"
      on:click={handleClose}
      role="button"
      tabindex="-1"
      on:keydown={e => e.key === 'Escape' && handleClose()}
    />

    <div class="relative bg-white rounded-lg shadow-xl w-full max-w-lg z-10">
      <!-- Header -->
      <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
        <h3 class="text-lg font-semibold text-gray-900">Detalle del Asunto</h3>
        <button type="button" on:click={handleClose} class="text-gray-400 hover:text-gray-500">
          <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>
      </div>

      <!-- Body -->
      <div class="px-6 py-5 space-y-4">
        <!-- Status + Priority -->
        <div class="flex items-center gap-3">
          <span
            class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
            bg-{priorityObj.color}-100 text-{priorityObj.color}-800"
          >
            {priorityObj.label}
          </span>
          <span
            class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
            bg-{statusObj.color}-100 text-{statusObj.color}-800"
          >
            {statusObj.label}
          </span>
        </div>

        <!-- Contenido -->
        <div>
          <p class="text-sm font-medium text-gray-500 mb-1">Descripción</p>
          <p class="text-sm text-gray-900 whitespace-pre-wrap bg-gray-50 rounded-md p-3">
            {issue.content}
          </p>
        </div>

        <!-- Creado por / cuando -->
        <div class="flex justify-between text-sm text-gray-500">
          <span
            >Creado por <span class="font-medium text-gray-700">{issue.created_by_name}</span></span
          >
          <span>{formatDate(issue.created_at)}</span>
        </div>

        <!-- Usuarios etiquetados -->
        {#if issue.tagged_users?.length > 0}
          <div>
            <p class="text-sm font-medium text-gray-500 mb-2">Usuarios etiquetados</p>
            <div class="flex flex-wrap gap-2">
              {#each issue.tagged_users as user}
                <div
                  class="flex items-center gap-1.5 bg-blue-50 text-blue-700 px-2.5 py-1 rounded-full text-xs"
                >
                  <span class="font-medium">{user.full_name}</span>
                  <span class="text-blue-400">·</span>
                  <span>{user.email}</span>
                </div>
              {/each}
            </div>
          </div>
        {/if}

        <!-- Adjunto -->
        {#if issue.attachment_filename}
          <div>
            <p class="text-sm font-medium text-gray-500 mb-1">Adjunto</p>
            <div class="flex items-center gap-2 bg-gray-50 rounded-md p-2">
              <svg
                class="h-4 w-4 text-gray-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"
                />
              </svg>
              <span class="text-sm text-gray-700">{issue.attachment_filename}</span>
            </div>
          </div>
        {/if}

        <!-- Cambiar status (solo admins) -->
        {#if canManage}
          <div>
            <label class="block text-sm font-medium text-gray-500 mb-1">Cambiar estado</label>
            <select
              value={issue.status}
              on:change={handleStatusChange}
              disabled={isUpdatingStatus}
              class="block w-full rounded-md border border-gray-300 shadow-sm
                     focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2
                     disabled:opacity-50"
            >
              {#each STATUSES as s}
                <option value={s.value}>{s.label}</option>
              {/each}
            </select>
          </div>
        {/if}
      </div>

      <!-- Footer -->
      <div class="flex justify-between px-6 py-4 border-t border-gray-200">
        {#if canManage}
          <button
            type="button"
            on:click={handleDelete}
            disabled={isDeleting}
            class="px-4 py-2 text-sm font-medium text-red-700 bg-red-50 border
                   border-red-200 rounded-md hover:bg-red-100 disabled:opacity-50"
          >
            {isDeleting ? 'Eliminando...' : 'Eliminar asunto'}
          </button>
        {:else}
          <div />
        {/if}
        <button
          type="button"
          on:click={handleClose}
          class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border
                 border-gray-300 rounded-md shadow-sm hover:bg-gray-50"
        >
          Cerrar
        </button>
      </div>
    </div>
  </div>
</div>
