<%# Process Letter Batch Form %>
<div class="container">
  <article>
    <header>
      <h1>Process Letter Batch</h1>
      <p>Review the batch details and configure processing options.</p>
    </header>
    <div class="card mb-4">
      <div class="card-body">
        <% if @batch.letter_return_address&.us? %>
          <div class="grid md:grid-cols-2 gap-4">
            <div>
              <h3 class="text-sm font-medium mb-2">Letter Counts</h3>
              <div class="text-sm mb-2">
                <span class="text-gray-500">US Letters:</span>
                <span id="us_letter_count" class="font-medium">
                  <%= @batch.letters.joins(:address).where(addresses: { country: "US" }).count %>
                </span>
              </div>
              <div class="text-sm mb-2">
                <span class="text-gray-500">International Letters:</span>
                <span id="intl_letter_count" class="font-medium">
                  <%= @batch.letters.joins(:address).where.not(addresses: { country: "US" }).count %>
                </span>
              </div>
              <div class="text-sm mb-2">
                <span class="text-gray-500">Total Letters:</span>
                <span class="font-medium">
                  <%= @batch.letters.count %>
                </span>
              </div>
            </div>
            <div>
              <h3 class="text-sm font-medium mb-2">Projected Costs</h3>
              <div class="text-sm mb-2">
                <span class="text-gray-500">Total Postage Cost:</span>
                <span id="total_postage_cost" class="font-medium">$<%= sprintf('%.2f', @batch.postage_cost) %></span>
              </div>
              <div class="text-sm mb-2">
                <span class="text-gray-500">US Cost Difference:</span>
                <span id="us_cost_difference" class="font-medium text-green-600">
                  $<%= sprintf('%.2f', @batch.postage_cost_difference[:us]) %>
                </span>
              </div>
              <div class="text-sm mb-2">
                <span class="text-gray-500">International Cost Difference:</span>
                <span id="intl_cost_difference" class="font-medium text-red-600">
                  $<%= sprintf('%.2f', @batch.postage_cost_difference[:intl]) %>
                </span>
              </div>
            </div>
          </div>
        <% else %>
          <div class="text-sm mb-2">
            <span class="text-gray-500">Total Letters:</span>
            <span class="font-medium">
              <%= @batch.letters.count %>
            </span>
          </div>
        <% end %>
      </div>
    </div>
    <%= form_with(model: @batch, url: process_letter_batch_path(@batch), method: :post, data: { controller: "postage-form" }) do |f| %>
      <div x-data="{ usPostageType: 'indicia', intlPostageType: 'indicia' }">
        <div class="form-group">
          <%= f.label :letter_mailing_date, "Mailing Date", class: "form-label" %>
          <%= f.date_field :letter_mailing_date, 
            value: @batch.letter_mailing_date || @batch.default_mailing_date,
            min: Date.current,
            class: "form-control",
            required: true %>
        </div>
        <% if @batch.letter_return_address&.us? %>
          <div style="margin-bottom: 1.5rem;">
            <h4 class="text-sm font-medium mb-2">US Mail</h4>
            <div class="space-y-2">
              <div class="form-check">
                <%= f.radio_button :us_postage_type, "stamps", class: "form-check-input", "@change": "usPostageType = 'stamps'" %>
                <%= f.label :us_postage_type_stamps, "Stamps", class: "form-check-label" %>
              </div>
              <div class="form-check">
                <%= f.radio_button :us_postage_type, "indicia", class: "form-check-input", checked: true, "@change": "usPostageType = 'indicia'" %>
                <%= f.label :us_postage_type_indicia, "Indicia (Metered)", class: "form-check-label" %>
              </div>
            </div>
          </div>
          <div style="margin-bottom: 1.5rem;">
            <h4 class="text-sm font-medium mb-2">International Mail</h4>
            <div class="space-y-2">
              <div class="form-check">
                <%= f.radio_button :intl_postage_type, "stamps", class: "form-check-input", "@change": "intlPostageType = 'stamps'" %>
                <%= f.label :intl_postage_type_stamps, "Stamps", class: "form-check-label" %>
              </div>
              <div class="form-check">
                <%= f.radio_button :intl_postage_type, "indicia", class: "form-check-input", checked: true, "@change": "intlPostageType = 'indicia'" %>
                <%= f.label :intl_postage_type_indicia, "Indicia (Metered)", class: "form-check-label" %>
              </div>
            </div>
          </div>
        <% else %>
          <div class="banner banner-info">
            <strong>hey!</strong> jsyk, since you're mailing from outside the US, we can't buy postage or calculate costs.
          </div>
          <%= f.hidden_field :us_postage_type, value: "international_origin" %>
          <%= f.hidden_field :intl_postage_type, value: "international_origin" %>
        <% end %>
        <div class="form-group" style="margin-top: 1.5rem;" x-show="usPostageType === 'indicia' || intlPostageType === 'indicia'" x-cloak>
          <%= f.label :usps_payment_account_id, "USPS Payment Account", class: "form-label" %>
          <%= f.collection_select :usps_payment_account_id,
                                USPS::PaymentAccount.all,
                                :id,
                                :display_name,
                                { selected: USPS::PaymentAccount.first&.id },
                                { class: "form-select" } %>
        </div>
        <div class="form-group" style="margin-top: 1.5rem;" x-show="usPostageType === 'indicia' || intlPostageType === 'indicia'" x-cloak>
          <%= f.label :hcb_payment_account_id, "Pay with HCB Organization", class: "form-label" %>
          <% if current_user.hcb_payment_accounts.any? %>
            <%= f.collection_select :hcb_payment_account_id,
                                  current_user.hcb_payment_accounts,
                                  :id,
                                  :organization_name,
                                  { prompt: "Select an organization" },
                                  { class: "form-select", required: true } %>
          <% else %>
            <p class="text-sm text-gray-600">
              <%= link_to "Connect your HCB account", new_hcb_oauth_connection_path %> to purchase indicia.
            </p>
          <% end %>
        </div>
        <div class="form-group">
          <%= f.label :template_cycle, "Template Cycle", class: "form-label" %>
          <%= f.hidden_field :template_cycle, id: "selected_template", value: params[:template] %>
          <%= render "shared/template_picker", multiple: true %>
        </div>
        <div class="form-group">
          <%= f.label :user_facing_title, "User Facing Title", class: "form-label" %>
          <%= f.text_field :user_facing_title, class: "form-control", value: params[:uft] %>
        </div>
        <div class="form-group">
          <%= f.label :include_qr_code, "Include QR Code", class: "form-label" %>
          <%= f.check_box :include_qr_code, class: "form-checkbox", checked: true %>
        </div>
        <div class="form-group">
          <%= f.label :immediate_print, "⚡ print immediately when done?", class: "form-label" %>
          <%= f.check_box :immediate_print, class: "form-checkbox", checked: false %>
        </div>
      </div>
      <div class="actions">
        <%= f.submit "Process Batch", class: "contrast" %>
        <%= link_to "Cancel", letter_batch_path(@batch), class: "secondary" %>
      </div>
    <% end %>
  </article>
</div>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const usPostageRadios = document.querySelectorAll('input[name="batch[us_postage_type]"]');
    const intlPostageRadios = document.querySelectorAll('input[name="batch[intl_postage_type]"]');

    function getSelectedPostageType(radios) {
      for (const radio of radios) {
        if (radio.checked) return radio.value;
      }
      return null;
    }

    function updatePostageCosts() {
      const usPostageType = getSelectedPostageType(usPostageRadios);
      const intlPostageType = getSelectedPostageType(intlPostageRadios);

      fetch(`<%= update_costs_letter_batch_path(@batch) %>`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
        },
        body: JSON.stringify({
          us_postage_type: usPostageType,
          intl_postage_type: intlPostageType
        })
      })
      .then(response => response.json())
      .then(data => {
        document.getElementById('total_postage_cost').textContent = `$${data.total_cost.toFixed(2)}`;
        document.getElementById('us_cost_difference').textContent = `$${data.cost_difference.us.toFixed(2)}`;
        document.getElementById('intl_cost_difference').textContent = `$${data.cost_difference.intl.toFixed(2)}`;

        document.getElementById('us_letter_count').textContent = data.us_count;
        document.getElementById('intl_letter_count').textContent = data.intl_count;

        const usDiffElement = document.getElementById('us_cost_difference');
        const intlDiffElement = document.getElementById('intl_cost_difference');

        if (data.cost_difference.us < 0) {
          usDiffElement.classList.remove('text-red-600');
          usDiffElement.classList.add('text-green-600');
        } else {
          usDiffElement.classList.remove('text-green-600');
          usDiffElement.classList.add('text-red-600');
        }

        if (data.cost_difference.intl < 0) {
          intlDiffElement.classList.remove('text-red-600');
          intlDiffElement.classList.add('text-green-600');
        } else {
          intlDiffElement.classList.remove('text-green-600');
          intlDiffElement.classList.add('text-red-600');
        }
      });
    }

    usPostageRadios.forEach(radio => radio.addEventListener('change', updatePostageCosts));
    intlPostageRadios.forEach(radio => radio.addEventListener('change', updatePostageCosts));
    updatePostageCosts();
  });
</script>
<style>
  [x-cloak] {
    display: none !important;
  }

  .container {
    max-width: 800px;
    margin: 0 auto;
    padding: 1rem;
  }

  .grid {
    display: grid;
    gap: 1rem;
    margin-bottom: 1rem;
  }

  .form-group {
    margin-bottom: 1rem;
  }

  .form-label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: bold;
  }

  .form-control {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid var(--muted-border-color);
    border-radius: var(--border-radius);
  }

  .form-select {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid var(--muted-border-color);
    border-radius: var(--border-radius);
  }

  .form-checkbox {
    margin-right: 0.5rem;
  }

  .actions {
    margin-top: 1rem;
    display: flex;
    justify-content: flex-end;
    gap: 0.5rem;
  }
</style> 