<script lang="ts">
  interface Event {
    id: string;
    email_subject: string;
    email_body: string;
  }

  let { 
    event, 
    loading, 
    updatingEmail, 
    onUpdateEmail 
  } = $props<{
    event: Event | null;
    loading: boolean;
    updatingEmail: boolean;
    onUpdateEmail: (eventId: string, subject: string, body: string) => void;
  }>();
  
  // State for form
  let isEditing = $state(false);
  let emailSubject = $state('');
  let emailBody = $state('');
  
  // Update form values when event changes
  $effect(() => {
    if (event) {
      emailSubject = event.email_subject;
      emailBody = event.email_body;
    }
  });
  
  // Toggle editing mode
  function toggleEdit() {
    isEditing = !isEditing;
    // Reset form when exiting edit mode without saving
    if (!isEditing && event) {
      emailSubject = event.email_subject;
      emailBody = event.email_body;
    }
  }
  
  // Track the previous updatingEmail state to detect changes
  let wasUpdating = $state(false);
  
  // Save email template
  function handleSave() {
    if (!event) return;
    onUpdateEmail(event.id, emailSubject, emailBody);
  }
  
  // Watch for updatingEmail changes to detect when operation completes
  $effect(() => {
    // Detect the transition from updating to not updating (operation completed)
    if (wasUpdating && !updatingEmail) {
      // If event data matches our form data, the update was successful
      // Turn off editing mode after successful update
      if (event && event.email_subject === emailSubject && event.email_body === emailBody) {
        isEditing = false;
      }
    }
    
    // Store current state for next comparison
    wasUpdating = updatingEmail;
  });
</script>

<div class="rounded-lg border border-gray-300 bg-white p-6 mb-4">
  <div class="mb-4 flex justify-between items-center">
    <h2 class="text-xl font-semibold text-gray-900">Email Template</h2>
    {#if !loading && event}
      <div class="flex gap-3">
        {#if isEditing}
        <button
          onclick={handleSave}
          disabled={updatingEmail}
          class="rounded bg-blue-600 px-4 py-2 text-white transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
          aria-label="Save email template"
        >
          {updatingEmail ? 'Saving...' : 'Save'}
        </button>
          <button 
            onclick={toggleEdit}
            class="rounded border border-gray-300 bg-white px-4 py-2 text-gray-700 transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
            disabled={updatingEmail}
            aria-label="Cancel editing"
          >
            Cancel
          </button>
        {:else}
          <button 
            onclick={toggleEdit}
            class="rounded bg-blue-600 px-4 py-2 text-white transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
            disabled={updatingEmail}
            aria-label="Edit email template"
          >
            Edit Email
          </button>
        {/if}
      </div>
    {/if}
  </div>
  
  {#if loading}
    <!-- Loading placeholder for email template content -->
    <div class="space-y-4">
      <div>
        <span class="block mb-1 text-sm font-medium text-gray-700">Subject:</span>
        <div class="h-10 w-full animate-pulse rounded bg-gray-200"></div>
      </div>
      
      <div>
        <span class="block mb-1 text-sm font-medium text-gray-700">Body:</span>
        <div class="h-28 w-full animate-pulse rounded bg-gray-200"></div>
      </div>
    </div>
  {:else if event}
    <div class="space-y-4">
      <div>
        <label for="emailSubject" class="block mb-1 text-sm font-medium text-gray-700">Subject:</label>
        <input
          id="emailSubject"
          type="text"
          bind:value={emailSubject}
          disabled={!isEditing || updatingEmail}
          class="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-blue-500 focus:ring-blue-500 disabled:cursor-default disabled:bg-gray-100"
        />
      </div>
      
      <div>
        <label for="emailBody" class="block mb-1 text-sm font-medium text-gray-700">Body:</label>
        <textarea
          id="emailBody"
          bind:value={emailBody}
          rows="6"
          disabled={!isEditing || updatingEmail}
          class="w-full rounded-lg border border-gray-300 px-3 py-2 focus:border-blue-500 focus:ring-blue-500 disabled:cursor-default disabled:bg-gray-100"
        ></textarea>
        {#if isEditing}
          <div class="mt-2 text-xs text-gray-500">
            Template variables: <span class="font-mono bg-gray-100 px-1 rounded">&#123;name&#125;</span>, 
            <span class="font-mono bg-gray-100 px-1 rounded">&#123;surname&#125;</span>
          </div>
        {/if}
      </div>
      
      <!-- Save button moved to the header -->
    </div>
  {/if}
</div>
