<script lang="ts">
  import { goto } from '$app/navigation';
  import { page } from '$app/stores';
  import IssueModal from '$lib/components/IssueModal.svelte';
  import ParticipantsModal from '$lib/components/ParticipantsModal.svelte';
  import { toast } from '$lib/stores/toast';
  import { api } from '$lib/utils/api';
  import { onMount } from 'svelte';

  let showParticipants = false;
  let showIssueModal = false;
  let issues = [];
  let ticketId: string;
  let ticket = null;
  let comments = [];
  let attachments = [];
  let users = [];
  let isLoading = false;
  let newComment = '';
  let isSubmittingComment = false;
  let pollingInterval: any = null;

  const STATUSES = [
    { value: 'NEW', label: 'Nuevo', color: 'blue' },
    { value: 'IN_PROGRESS', label: 'En Progreso', color: 'indigo' },
    { value: 'WAITING_CUSTOMER', label: 'Esperando Cliente', color: 'orange' },
    { value: 'RESOLVED', label: 'Resuelto', color: 'green' },
    { value: 'CLOSED', label: 'Cerrado', color: 'gray' },
    { value: 'REOPENED', label: 'Reabierto', color: 'red' }
  ];

  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' }
  ];

  async function loadComments() {
    try {
      const commentsData = await api.get(`/tickets/${ticketId}/comments`);
      comments = commentsData;
    } catch (e) {
      // No mostrar error en polling silencioso
      console.error('Error recargando comentarios:', e);
    }
  }

  async function loadData() {
  isLoading = true;
  try {
    const [ticketData, commentsData, attachmentsData, usersData, issuesData] = await Promise.all([
      api.get(`/tickets/${ticketId}`),
      api.get(`/tickets/${ticketId}/comments`),
      api.get(`/tickets/${ticketId}/attachments`),
      api.get('/users/'),
      api.get(`/tickets/${ticketId}/issues`)
    ]);
    ticket = ticketData;
    comments = commentsData;
    attachments = attachmentsData;
    users = usersData;
    issues = issuesData;
  } catch (e) {
    toast.error('Error cargando ticket: ' + (e.message || 'Error desconocido'));
  } finally {
    isLoading = false;
  }
}

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

    isSubmittingComment = true;
    try {
      const comment = await api.post(`/tickets/${ticketId}/issues`, {
              content: content.trim(),
              priority,
              tagged_user_ids: taggedUserIds

      });
      comments = [...comments, comment];
      newComment = '';
      toast.success('Comentario agregado');
    } catch (e) {
      toast.error(e.message || 'Error al agregar comentario');
    } finally {
      isSubmittingComment = false;
    }
  }

  function getStatusBadge(status) {
    const statusObj = STATUSES.find(s => s.value === status);
    return statusObj || { label: status, color: 'gray' };
  }

  function getPriorityBadge(priority) {
    const priorityObj = PRIORITIES.find(p => p.value === priority);
    return priorityObj || { label: priority, color: 'gray' };
  }

  function getUserName(id) {
    if (!id) return 'Desconocido';
    const user = users.find(u => u.id === id);
    return user ? `${user.first_name} ${user.last_name}` : 'Desconocido';
  }

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

  async function handleDownloadAttachment(attachment: any) {
    try {
      await api.downloadFile(
        `/tickets/${ticketId}/attachments/${attachment.id}/download`,
        attachment.original_filename
      );
      toast.success('Descarga iniciada');
    } catch (error) {
      console.error('Download error:', error);
      toast.error('Error al descargar el archivo');
    }
  }

  onMount(() => {
    ticketId = $page.params.id;
    if (ticketId) {
      loadData();
      // Polling cada 3 segundos
      pollingInterval = setInterval(() => {
        loadComments();
      }, 3000);
    }

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

<div class="px-4 py-8 mx-auto max-w-7xl sm:px-6 lg:px-8">
  {#if isLoading}
    <div class="text-center py-12">
      <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-700" />
      <p class="mt-2 text-gray-600">Cargando ticket...</p>
    </div>
  {:else if ticket}
    <!-- Breadcrumb -->
    <div class="flex items-center space-x-2 text-sm text-gray-500 mb-6">
      <a href="/tickets" class="hover:text-blue-700">Tickets</a>
      <span>/</span>
      <span>#{ticket.ticket_number || ticket.id.substring(0, 8)}</span>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- Main Content -->
      <div class="lg:col-span-2 space-y-6">
        <!-- Ticket Header -->
        <div class="bg-white shadow rounded-lg">
          <div class="px-6 py-5 border-b border-gray-200">
            <div class="flex justify-between items-start">
              <div class="flex-1">
                <h1 class="text-2xl font-bold text-gray-900 mb-2">
                  {ticket.subject || ticket.title}
                </h1>
                <div class="flex items-center space-x-3">
                  <span
                    class="inline-flex rounded-full px-2 text-xs font-semibold leading-5 bg-{getStatusBadge(
                      ticket.status
                    ).color}-100 text-{getStatusBadge(ticket.status).color}-800"
                  >
                    {getStatusBadge(ticket.status).label}
                  </span>
                  <span
                    class="inline-flex rounded-full px-2 text-xs font-semibold leading-5 bg-{getPriorityBadge(
                      ticket.priority
                    ).color}-100 text-{getPriorityBadge(ticket.priority).color}-800"
                  >
                    {getPriorityBadge(ticket.priority).label}
                  </span>
                  <span class="text-sm text-gray-500">
                    Creado {formatDate(ticket.created_at)}
                  </span>
                </div>
              </div>

              <button
                on:click={() => goto('/tickets')}
                class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
              >
                Volver
              </button>
            </div>
          </div>

          <div class="px-6 py-5">
            <div class="prose max-w-none">
              <p class="whitespace-pre-wrap text-gray-700">
                {ticket.description}
              </p>
            </div>
          </div>
        </div>

        <!-- Attachments Section -->
        {#if attachments && attachments.length > 0}
          <div class="bg-white shadow rounded-lg">
            <div class="px-6 py-5 border-b border-gray-200">
              <h3 class="text-lg font-semibold text-gray-900">
                Archivos Adjuntos ({attachments.length})
              </h3>
            </div>
            <div class="px-6 py-5">
              <div class="space-y-2">
                {#each 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-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0"
                      >
                        <span class="text-xs font-bold text-blue-700">ADJ</span>
                      </div>
                      <div class="flex-1 min-w-0">
                        <p class="text-sm font-medium text-gray-900 truncate">
                          {attachment.original_filename}
                        </p>
                        <p class="text-xs text-gray-500">
                          {Math.round(attachment.size_bytes / 1024)} KB
                          {#if attachment.uploaded_by_name}
                            • Subido por {attachment.uploaded_by_name}
                          {/if}
                          {#if attachment.uploaded_at}
                            • {formatDate(attachment.uploaded_at)}
                          {/if}
                        </p>
                      </div>
                    </div>
                    <button
                      on:click={() => handleDownloadAttachment(attachment)}
                      class="inline-flex items-center px-2 py-2 text-sm font-medium text-blue-700 hover:bg-blue-50 rounded-md transition-colors"
                      title="Descargar {attachment.original_filename}"
                    >
                      Descargar
                    </button>
                  </div>
                {/each}
              </div>
            </div>
          </div>
        {/if}

        <!-- Comments Section -->
        <div class="bg-white shadow rounded-lg">
          <div class="px-6 py-5 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-900">Conversación</h3>
          </div>
          <div class="px-6 py-5">
            {#if 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 comments as comment}
                  <div class="flex space-x-3">
                    <div
                      class="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center flex-shrink-0"
                    >
                      <span class="text-blue-700 text-xs font-medium">
                        {comment.author_name
                          ? comment.author_name
                              .split(' ')
                              .map(n => n[0])
                              .join('')
                          : 'U'}
                      </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 || 'Usuario Desconocido'}
                        </span>
                        <span class="text-xs text-gray-500">
                          {formatDate(comment.created_at)}
                        </span>
                        {#if comment.is_internal}
                          <span
                            class="bg-gray-50 text-red-700 text-xs px-2 py-0.5 rounded border border-red-200"
                          >
                            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">
              <form on:submit|preventDefault={handleAddComment} class="space-y-4">
                <textarea
                  rows="4"
                  class="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm border p-2"
                  placeholder="Escribe tu comentario o respuesta..."
                  bind:value={newComment}
                  disabled={isSubmittingComment}
                />

                <div class="flex justify-end">
                  <button
                    type="submit"
                    class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
                    disabled={isSubmittingComment || !newComment.trim()}
                  >
                    {#if isSubmittingComment}
                      <div class="flex items-center space-x-2">
                        <div
                          class="inline-block animate-spin rounded-full h-4 w-4 border-b-2 border-white"
                        />
                        <span>Enviando...</span>
                      </div>
                    {:else}
                      Enviar Comentario
                    {/if}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>

      <!-- Sidebar -->
      <div class="space-y-6">
        <!-- Ticket Info -->
        <div class="bg-white shadow rounded-lg">
          <div class="px-6 py-5 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-900">Información</h3>
          </div>
          <div class="px-6 py-5 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">
                #{ticket.ticket_number || ticket.id.substring(0, 8)}
              </dd>
            </div>

            <div>
              <dt class="text-sm font-medium text-gray-500">Creado por</dt>
              <dd class="text-sm text-gray-900">{getUserName(ticket.created_by)}</dd>
            </div>

            {#if ticket.assigned_to}
              <div>
                <dt class="text-sm font-medium text-gray-500">Asignado a</dt>
                <dd class="text-sm text-gray-900">{getUserName(ticket.assigned_to)}</dd>
              </div>
            {/if}

            <div>
              <dt class="text-sm font-medium text-gray-500">Creado</dt>
              <dd class="text-sm text-gray-900">{formatDate(ticket.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(ticket.updated_at)}</dd>
            </div>

            <!-- Participantes -->
            <div class="bg-white shadow rounded-lg">
              <div class="px-6 py-5 border-b border-gray-200 flex justify-between items-center">
                <h3 class="text-lg font-semibold text-gray-900">
                  Asuntos {#if issues.length > 0}<span class="text-gray-400 font-normal"
                      >({issues.length})</span
                    >{/if}
                </h3>
                <button
                  type="button"
                  on:click={() => (showIssueModal = true)}
                  class="text-sm text-blue-600 hover:text-blue-700 font-medium"
                >
                  Crear asunto
                </button>
              </div>
              {#if issues.length > 0}
                <div class="divide-y divide-gray-100">
                  {#each issues as issue}
                    <div class="px-6 py-4">
                      <div class="flex items-start justify-between gap-2">
                        <p class="text-sm text-gray-700 flex-1">{issue.content}</p>
                        <span
                          class="text-xs font-medium px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 shrink-0"
                        >
                          {issue.priority}
                        </span>
                      </div>
                      {#if issue.tagged_users?.length > 0}
                        <div class="mt-2 flex flex-wrap gap-1">
                          {#each issue.tagged_users as u}
                            <span class="text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full">
                              {u.full_name}
                            </span>
                          {/each}
                        </div>
                      {/if}
                      <p class="text-xs text-gray-400 mt-1">{issue.created_by_name}</p>
                    </div>
                  {/each}
                </div>
              {:else}
                <p class="px-6 py-4 text-sm text-gray-500">No hay asuntos creados.</p>
              {/if}
            </div>

            <!-- SLA Information -->
            {#if ticket.sla_response_due || ticket.sla_resolution_due}
              <div class="pt-4 border-t border-gray-200">
                <h4 class="text-sm font-semibold text-gray-900 mb-3">
                  SLA (Acuerdos de Nivel de Servicio)
                </h4>

                {#if ticket.sla_response_due}
                  <div class="mb-3">
                    <dt class="text-xs font-medium text-gray-500">Tiempo de Respuesta</dt>
                    <dd class="text-sm text-gray-900 mt-1">
                      {formatDate(ticket.sla_response_due)}
                      {#if new Date(ticket.sla_response_due) < new Date() && !ticket.sla_response_met}
                        <span
                          class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-50 text-red-700 border border-red-200"
                        >
                          Vencido
                        </span>
                      {:else if ticket.sla_response_met}
                        <span
                          class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-50 text-green-700 border border-green-200"
                        >
                          Cumplido
                        </span>
                      {:else}
                        <span
                          class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-50 text-blue-700 border border-blue-200"
                        >
                          En plazo
                        </span>
                      {/if}
                    </dd>
                  </div>
                {/if}

                {#if ticket.sla_resolution_due}
                  <div>
                    <dt class="text-xs font-medium text-gray-500">Tiempo de Resolución</dt>
                    <dd class="text-sm text-gray-900 mt-1">
                      {formatDate(ticket.sla_resolution_due)}
                      {#if new Date(ticket.sla_resolution_due) < new Date() && !ticket.sla_resolution_met}
                        <span
                          class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-50 text-red-700 border border-red-200"
                        >
                          Vencido
                        </span>
                      {:else if ticket.sla_resolution_met}
                        <span
                          class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-50 text-green-700 border border-green-200"
                        >
                          Cumplido
                        </span>
                      {:else}
                        <span
                          class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-50 text-blue-700 border border-blue-200"
                        >
                          En plazo
                        </span>
                      {/if}
                    </dd>
                  </div>
                {/if}
              </div>
            {/if}
          </div>
        </div>
      </div>
    </div>
  {/if}
  {#if showParticipants && ticket}
    <ParticipantsModal
      ticketId={ticket.id}
      createdBy={ticket.created_by}
      on:close={() => (showParticipants = false)}
    />
  {/if}
  {#if showIssueModal && ticket}
    <IssueModal
      ticketId={ticket.id}
      {users}
      on:close={() => (showIssueModal = false)}
      on:created={() => {
        showIssueModal = false;
        loadData();
      }}
    />
  {/if}
</div>
