<script lang="ts">
  import { onMount } from 'svelte';
  import { page } from '$app/stores';
  import { auth } from '$lib/stores/auth.js';
  import { tickets } from '$lib/stores/tickets.js';
  import { toast } from '$lib/stores/toast.js';
  import { goto } from '$app/navigation';

  let ticketId: string;
  let newComment = '';
  let isSubmittingComment = false;
  let isClosingTicket = false;
  let showCloseDialog = false;
  let closeResolution = '';
  let fileInput: HTMLInputElement;
  let isUploading = false;
  let pollingInterval: any = null;
  let showAttachments = true; // Variable para controlar la visibilidad de attachments

  async function loadComments() {
    try {
      await tickets.reloadComments(ticketId);
    } catch (error) {
      // No mostrar error en polling silencioso
      console.error('Error recargando comentarios:', error);
    }
  }

  onMount(() => {
    // Redirect if not authenticated
    if (!$auth.isAuthenticated) {
      goto('/login');
      return;
    }

    ticketId = $page.params.id;
    if (ticketId) {
      tickets.loadTicket(ticketId);

      // Polling cada 3 segundos
      pollingInterval = setInterval(() => {
        loadComments();
      }, 3000);
    }

    // Cleanup cuando se desmonte el componente
    return () => {
      if (pollingInterval) {
        clearInterval(pollingInterval);
      }
    };
  });

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

  // Status mapping
  const statusConfig = {
    NEW: { label: 'Nuevo', class: 'badge-new' },
    IN_PROGRESS: { label: 'En Progreso', class: 'badge-in-progress' },
    WAITING_FOR_CLIENT: { label: 'Esperando Cliente', class: 'badge-waiting' },
    RESOLVED: { label: 'Resuelto', class: 'badge-resolved' },
    CLOSED: { label: 'Cerrado', class: 'badge-closed' },
    REOPENED: { label: 'Reabierto', class: 'badge-reopened' }
  };

  // Priority mapping
  const priorityConfig = {
    LOW: { label: 'Baja', class: 'badge-priority-low' },
    MEDIUM: { label: 'Media', class: 'badge-priority-medium' },
    HIGH: { label: 'Alta', class: 'badge-priority-high' },
    URGENT: { label: 'Urgente', class: 'badge-priority-urgent' }
  };

  async function handleAddComment() {
    if (!newComment.trim()) return;

    isSubmittingComment = true;
    try {
      await tickets.addComment(ticketId, newComment.trim());
      newComment = '';
      toast.success('Comentario agregado');
    } catch (error: any) {
      toast.error(error.message || 'Error al agregar comentario');
    } finally {
      isSubmittingComment = false;
    }
  }

  async function handleFileUpload(event: Event) {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (!file) return;

    // Validate file size (max 10MB)
    if (file.size > 10 * 1024 * 1024) {
      toast.error('El archivo es demasiado grande. Máximo 10MB');
      target.value = '';
      return;
    }

    // Validate file type
    const allowedTypes = [
      'image/jpeg',
      'image/png',
      'image/gif',
      'image/webp',
      'application/pdf',
      'text/plain',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ];

    if (!allowedTypes.includes(file.type)) {
      toast.error('Tipo de archivo no permitido');
      target.value = '';
      return;
    }

    isUploading = true;
    try {
      await tickets.uploadAttachment(ticketId, file);
      toast.success('Archivo adjuntado correctamente');
      target.value = '';
    } catch (error: any) {
      toast.error(error.message || 'Error al subir archivo');
    } finally {
      isUploading = false;
    }
  }

  async function handleDownloadAttachment(attachment: any) {
    try {
      await tickets.downloadAttachment(ticketId, attachment.id, attachment.original_filename);
      toast.success('Descarga iniciada');
    } catch (error: any) {
      console.error('Download error:', error);
      toast.error(error.message || 'Error al descargar el archivo');
    }
  }

  function handleCloseTicket() {
    showCloseDialog = true;
  }

  async function confirmCloseTicket() {
    isClosingTicket = true;
    try {
      await tickets.closeTicket(ticketId, closeResolution.trim() || undefined);
      showCloseDialog = false;
      closeResolution = '';
      toast.success('Ticket cerrado exitosamente');
    } catch (error: any) {
      toast.error(error.message || 'Error al cerrar ticket');
    } finally {
      isClosingTicket = false;
    }
  }

  function cancelCloseTicket() {
    showCloseDialog = false;
    closeResolution = '';
  }

  // Check if user can close ticket
  $: canClose =
    $tickets.currentTicket &&
    ['RESOLVED', 'WAITING_FOR_CLIENT'].includes($tickets.currentTicket.status);
</script>

<svelte:head>
  <title>
    {$tickets.currentTicket ? `Ticket: ${$tickets.currentTicket.title}` : 'Cargando...'} - ServiceManager
  </title>
</svelte:head>

<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
  {#if $tickets.isLoading}
    <div class="text-center py-12">
      <div class="spinner w-8 h-8 mx-auto mb-4" />
      <p class="text-gray-600">Cargando ticket...</p>
    </div>
  {:else if $tickets.error}
    <div class="text-center py-12">
      <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center mx-auto mb-4">
        <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
          />
        </svg>
      </div>
      <h3 class="text-lg font-medium text-gray-900 mb-2">Error al cargar ticket</h3>
      <p class="text-gray-600 mb-4">{$tickets.error}</p>
      <button on:click={() => tickets.loadTicket(ticketId)} class="btn-primary px-4 py-2">
        Reintentar
      </button>
    </div>
  {:else if $tickets.currentTicket}
    <!-- Breadcrumb -->
    <div class="flex items-center space-x-2 text-sm text-gray-500 mb-6">
      <a href="/tickets" class="hover:text-primary-600">Mis Tickets</a>
      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
      </svg>
      <span>#{$tickets.currentTicket.id.substring(0, 8)}</span>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
      <!-- Main Content -->
      <div class="lg:col-span-2 space-y-6">
        <!-- Ticket Header -->
        <div class="card">
          <div class="card-header">
            <div class="flex justify-between items-start">
              <div class="flex-1">
                <h1 class="text-2xl font-bold text-gray-900 mb-2">
                  {$tickets.currentTicket.title}
                </h1>
                <div class="flex items-center space-x-3">
                  <span class={statusConfig[$tickets.currentTicket.status].class}>
                    {statusConfig[$tickets.currentTicket.status].label}
                  </span>
                  <span class={priorityConfig[$tickets.currentTicket.priority].class}>
                    {priorityConfig[$tickets.currentTicket.priority].label}
                  </span>
                  <span class="text-sm text-gray-500">
                    Creado {formatDate($tickets.currentTicket.created_at)}
                  </span>
                </div>
              </div>

              {#if canClose}
                <button
                  on:click={handleCloseTicket}
                  class="btn-success px-4 py-2"
                  disabled={isClosingTicket}
                >
                  Cerrar Ticket
                </button>
              {/if}
            </div>
          </div>

          <div class="card-content">
            <div class="prose max-w-none">
              <p class="whitespace-pre-wrap text-gray-700">
                {$tickets.currentTicket.description}
              </p>
            </div>

            {#if $tickets.currentTicket.resolution}
              <div class="mt-6 p-4 bg-green-50 border border-green-200 rounded-lg">
                <h4 class="font-medium text-green-900 mb-2">Resolución:</h4>
                <p class="text-green-800 whitespace-pre-wrap">
                  {$tickets.currentTicket.resolution}
                </p>
              </div>
            {/if}
          </div>
        </div>

        <!-- Attachments -->
        {#if $tickets.attachments.length > 0}
          <div class="card">
            <div class="card-header">
              <div class="flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-900 flex items-center space-x-2">
                  <span>Archivos Adjuntos</span>
                  <span
                    class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                  >
                    {$tickets.attachments.length} archivo{$tickets.attachments.length !== 1
                      ? 's'
                      : ''}
                  </span>
                </h3>
                <button
                  class="text-sm text-gray-500 hover:text-gray-700"
                  title="Ver/Ocultar archivos adjuntos"
                  on:click={() => (showAttachments = !showAttachments)}
                >
                  {showAttachments ? 'Ocultar' : 'Ver'} archivos
                </button>
              </div>
            </div>
            {#if showAttachments}
              <div class="card-content">
                <div class="space-y-3">
                  {#each $tickets.attachments as attachment}
                    <div
                      class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
                    >
                      <div class="flex items-center space-x-3">
                        <div class="w-8 h-8 bg-gray-200 rounded flex items-center justify-center">
                          <svg
                            class="w-4 h-4 text-gray-600"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <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>
                        </div>
                        <div>
                          <p class="text-sm font-medium text-gray-900">
                            {attachment.original_filename}
                          </p>
                          <p class="text-xs text-gray-500">
                            {Math.round(attachment.size_bytes / 1024)} KB • Subido por {attachment.uploaded_by_name}
                            •
                            {formatDate(attachment.uploaded_at)}
                          </p>
                        </div>
                      </div>
                      <button
                        on:click={() => handleDownloadAttachment(attachment)}
                        class="btn-ghost p-2 hover:bg-blue-100 rounded-md transition-colors"
                        title="Descargar archivo"
                      >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                          />
                        </svg>
                      </button>
                    </div>
                  {/each}
                </div>
              </div>
            {/if}
          </div>
        {/if}

        <!-- Comments -->
        <div class="card">
          <div class="card-header">
            <h3 class="text-lg font-semibold text-gray-900">Conversación</h3>
          </div>
          <div class="card-content">
            {#if $tickets.comments.length === 0}
              <p class="text-gray-500 text-center py-4">
                No hay comentarios aún. ¡Sé el primero en comentar!
              </p>
            {:else}
              <div class="space-y-4">
                {#each $tickets.comments as comment}
                  {console.log('Comment:', comment)}
                  <div class="flex space-x-3">
                    <div
                      class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center flex-shrink-0"
                    >
                      <span class="text-primary-600 text-xs font-medium">
                        {comment.author_name
                          ? comment.author_name
                              .split(' ')
                              .map(n => n[0])
                              .join('')
                          : '??'}
                      </span>
                    </div>
                    <div class="flex-1 min-w-0">
                      <div class="flex items-center space-x-2 mb-1">
                        <span class="text-sm font-medium text-gray-900">
                          {comment.author_name}
                        </span>
                        <span class="text-xs text-gray-500">
                          {formatDate(comment.created_at)}
                        </span>
                        {#if comment.is_internal}
                          <span class="bg-red-100 text-red-700 text-xs px-2 py-0.5 rounded">
                            Interno
                          </span>
                        {/if}
                      </div>
                      <p class="text-gray-700 whitespace-pre-wrap">
                        {comment.content}
                      </p>
                    </div>
                  </div>
                {/each}
              </div>
            {/if}

            <!-- Add Comment Form -->
            <div class="mt-6 pt-6 border-t border-gray-200">
              <div class="space-y-4">
                <textarea
                  rows="4"
                  class="form-input"
                  placeholder="Escribe tu comentario o respuesta..."
                  bind:value={newComment}
                  disabled={isSubmittingComment}
                />

                <div class="flex justify-between items-center">
                  <div class="flex items-center space-x-4">
                    <input
                      type="file"
                      bind:this={fileInput}
                      on:change={handleFileUpload}
                      class="hidden"
                      accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.txt,.doc,.docx,.xls,.xlsx"
                      disabled={isUploading}
                    />
                    <button
                      type="button"
                      on:click={() => fileInput.click()}
                      class="btn-ghost p-2 flex items-center space-x-2"
                      disabled={isUploading}
                    >
                      {#if isUploading}
                        <div class="spinner w-4 h-4" />
                      {:else}
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <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>
                      {/if}
                      <span class="text-sm">Adjuntar archivo</span>
                    </button>
                  </div>

                  <button
                    on:click={handleAddComment}
                    class="btn-primary px-4 py-2"
                    disabled={isSubmittingComment || !newComment.trim()}
                  >
                    {#if isSubmittingComment}
                      <div class="flex items-center space-x-2">
                        <div class="spinner w-4 h-4" />
                        <span>Enviando...</span>
                      </div>
                    {:else}
                      Enviar Comentario
                    {/if}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Sidebar -->
      <div class="space-y-6">
        <!-- Ticket Info -->
        <div class="card">
          <div class="card-header">
            <h3 class="text-lg font-semibold text-gray-900">Información</h3>
          </div>
          <div class="card-content space-y-4">
            <div>
              <dt class="text-sm font-medium text-gray-500">ID del Ticket</dt>
              <dd class="text-sm text-gray-900 font-mono">
                #{$tickets.currentTicket.id.substring(0, 8)}
              </dd>
            </div>

            <div>
              <dt class="text-sm font-medium text-gray-500">Categoría</dt>
              <dd class="text-sm text-gray-900">
                {$tickets.currentTicket.category_name || 'Sin categoría'}
              </dd>
            </div>

            {#if $tickets.currentTicket.assigned_to_name}
              <div>
                <dt class="text-sm font-medium text-gray-500">Asignado a</dt>
                <dd class="text-sm text-gray-900">{$tickets.currentTicket.assigned_to_name}</dd>
              </div>
            {/if}

            <div>
              <dt class="text-sm font-medium text-gray-500">Creado</dt>
              <dd class="text-sm text-gray-900">{formatDate($tickets.currentTicket.created_at)}</dd>
            </div>

            <div>
              <dt class="text-sm font-medium text-gray-500">Última actualización</dt>
              <dd class="text-sm text-gray-900">{formatDate($tickets.currentTicket.updated_at)}</dd>
            </div>

            {#if $tickets.currentTicket.due_date}
              <div>
                <dt class="text-sm font-medium text-gray-500">Fecha límite</dt>
                <dd
                  class="text-sm text-gray-900 {new Date($tickets.currentTicket.due_date) <
                  new Date()
                    ? 'text-red-600'
                    : ''}"
                >
                  {formatDate($tickets.currentTicket.due_date)}
                  {#if new Date($tickets.currentTicket.due_date) < new Date()}
                    <span class="block text-xs text-red-500">¡Vencido!</span>
                  {/if}
                </dd>
              </div>
            {/if}
          </div>
        </div>
      </div>
    </div>
  {/if}
</div>

<!-- Close Ticket Dialog -->
{#if showCloseDialog}
  <div class="fixed inset-0 z-50 overflow-y-auto">
    <div
      class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
    >
      <div
        class="fixed inset-0 transition-opacity"
        role="dialog"
        tabindex="0"
        on:click={cancelCloseTicket}
        on:keydown={e => e.key === 'Escape' && cancelCloseTicket()}
      >
        <div class="absolute inset-0 bg-gray-500 opacity-75" />
      </div>

      <div
        class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
      >
        <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
          <div class="sm:flex sm:items-start">
            <div
              class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-green-100 sm:mx-0 sm:h-10 sm:w-10"
            >
              <svg
                class="h-6 w-6 text-green-600"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M5 13l4 4L19 7"
                />
              </svg>
            </div>
            <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
              <h3 class="text-lg leading-6 font-medium text-gray-900">Cerrar Ticket</h3>
              <div class="mt-2">
                <p class="text-sm text-gray-500">
                  ¿Estás seguro de que quieres cerrar este ticket? Esta acción indica que el
                  problema ha sido resuelto satisfactoriamente.
                </p>
              </div>

              <div class="mt-4">
                <label for="close-resolution" class="form-label">
                  Comentario de cierre (opcional)
                </label>
                <textarea
                  id="close-resolution"
                  rows="3"
                  class="form-input"
                  placeholder="Describe cómo se resolvió el problema o agrega comentarios finales..."
                  bind:value={closeResolution}
                  disabled={isClosingTicket}
                />
              </div>
            </div>
          </div>
        </div>
        <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
          <button
            type="button"
            class="w-full inline-flex justify-center btn-success px-4 py-2 sm:ml-3 sm:w-auto disabled:opacity-50"
            disabled={isClosingTicket}
            on:click={confirmCloseTicket}
          >
            {#if isClosingTicket}
              <div class="flex items-center space-x-2">
                <div class="spinner w-4 h-4" />
                <span>Cerrando...</span>
              </div>
            {:else}
              Cerrar Ticket
            {/if}
          </button>
          <button
            type="button"
            class="mt-3 w-full inline-flex justify-center btn-secondary px-4 py-2 sm:mt-0 sm:w-auto"
            disabled={isClosingTicket}
            on:click={cancelCloseTicket}
          >
            Cancelar
          </button>
        </div>
      </div>
    </div>
  </div>
{/if}
