{% extends "base.html" %}
{% block title %}Google Drive Authorization Processing{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
  <div class="bg-white shadow-md rounded-lg p-6">
    <div class="text-center mb-6">
      <svg xmlns="http://www.w3.org/2000/svg" class="mx-auto h-12 w-12 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
      </svg>
      <h2 class="text-2xl font-bold mt-4">Processing Authorization</h2>
      <p class="text-gray-600 mt-2">Please wait while we complete the Google Drive authorization process...</p>
    </div>

    <div class="flex justify-center my-6">
      <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500" role="status" aria-label="Loading"></div>
    </div>

    <div id="processing-message" class="text-center text-gray-700" aria-live="polite">
      <p>Exchanging authorization code for refresh token...</p>
    </div>

    <div id="error-container" class="hidden mt-6" role="alert" aria-live="assertive">
      <div class="bg-red-50 border-l-4 border-red-400 p-4">
        <div class="flex">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3">
            <h3 class="text-sm font-medium text-red-800">Error details:</h3>
            <div class="mt-2 text-sm text-red-700" id="error-message">
              <!-- Error message will be inserted here -->
            </div>
          </div>
        </div>
      </div>
      <div class="mt-4">
        <a id="return-to-setup-link" href="/google-drive-setup" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
          Return to Setup
        </a>
      </div>
    </div>

    <div id="folder-selection-container" class="hidden mt-6" aria-live="polite">
      <div class="rounded-md bg-blue-50 p-4 mb-6">
        <div class="flex">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-blue-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
              <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3">
            <p class="text-sm font-medium text-blue-800">
              Authentication successful! Please select or enter the Google Drive folder where you want to save files.
            </p>
          </div>
        </div>
      </div>

      <div class="space-y-4 mb-6">
        <div>
          <label for="folder-id-input" class="block text-sm font-medium text-gray-700">Google Drive Folder ID</label>
          <div class="mt-1 flex rounded-md shadow-sm">
            <input type="text" id="folder-id-input" class="focus:ring-indigo-500 focus:border-indigo-500 flex-1 block w-full rounded-md sm:text-sm border-gray-300" placeholder="Enter Google Drive folder ID">
            <button id="folder-select-picker-btn" type="button" class="ml-3 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
              <svg class="h-4 w-4 mr-1 text-white-100" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                <path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1H8a3 3 0 00-3 3v1.5a1.5 1.5 0 01-3 0V6z" clip-rule="evenodd" />
              </svg>
              Select Folder
            </button>
          </div>
          <p class="mt-2 text-sm text-gray-500">
            You can paste a folder ID directly or use the selector to pick a folder. Root folder is "root".
          </p>
        </div>

        <div>
          <button id="save-folder-btn" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
            Save Settings
          </button>
        </div>
      </div>
    </div>

    <div id="success-container" class="hidden mt-6" aria-live="polite">
      <div class="rounded-md bg-green-50 p-4">
        <div class="flex">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-green-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3">
            <p class="text-sm font-medium text-green-800">
              Google Drive authorization successful! Your refresh token has been saved.
            </p>
          </div>
        </div>
      </div>

      <div class="mt-6 p-4 bg-gray-100 rounded-md">
        <h3 class="font-medium text-lg mb-2">Configuration for Worker Nodes</h3>
        <p class="text-sm text-gray-600 mb-3">
          Copy these environment variables to configure all worker nodes:
        </p>

        <div class="relative">
          <pre id="env-vars" class="bg-gray-800 text-green-400 text-sm p-3 rounded overflow-x-auto"><code></code></pre>

          <button id="copy-env-vars" class="absolute top-2 right-2 bg-gray-700 hover:bg-gray-600 text-white text-xs py-1 px-2 rounded">
            Copy
          </button>
        </div>

        <p class="text-xs text-gray-500 mt-2">
          Add these variables to your .env file or environment configuration.
        </p>
      </div>

      <div class="mt-4 text-center">
        <a href="/status" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
          Go to Status Page
        </a>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
  const code = "{{ code }}";

  // Get credentials from session storage
  const clientId = sessionStorage.getItem('google_drive_client_id');
  const clientSecret = sessionStorage.getItem('google_drive_client_secret');
  const folderId = sessionStorage.getItem('google_drive_folder_id');
  const integrationId = sessionStorage.getItem('oauth_integration_id');

  // In user mode, point the "Return to Setup" link back to the wizard with integration_id
  if (integrationId) {
    const returnLink = document.getElementById('return-to-setup-link');
    if (returnLink) {
      returnLink.href = `/google-drive-setup?integration_id=${encodeURIComponent(integrationId)}`;
    }
  }

  const redirectUri = window.location.origin + "/google-drive-callback";

  let accessToken = null;
  let refreshToken = null;

  // Define folderIdInput at the top level so it's accessible throughout the script
  const folderIdInput = document.getElementById('folder-id-input');
  const folderSelectBtn = document.getElementById('folder-select-picker-btn');
  const saveFolderBtn = document.getElementById('save-folder-btn');

  // Automatically exchange the code for a refresh token
  if (code) {
    if (!clientId || !clientSecret) {
      showError("Missing Client ID or Client Secret. Please go back to the setup page and try again.");
      return;
    }

    exchangeCode(code, clientId, clientSecret, redirectUri, folderId);
  } else {
    showError("No authorization code was found in the URL");
  }

  function exchangeCode(code, clientId, clientSecret, redirectUri, folderId) {
    const formData = new FormData();
    formData.append('client_id', clientId);
    formData.append('client_secret', clientSecret);
    formData.append('redirect_uri', redirectUri);
    formData.append('code', code);
    if (folderId) {
      formData.append('folder_id', folderId);
    }

    document.getElementById('processing-message').innerHTML =
      '<p>Exchanging authorization code for refresh token...</p>';

    fetch('/api/google-drive/exchange-token', {
      method: 'POST',
      body: formData
    })
    .then(response => {
      if (!response.ok) {
        return response.json().then(err => {
          throw new Error(err.detail || 'Failed to exchange token');
        });
      }
      return response.json();
    })
    .then(data => {
      if (data.refresh_token) {
        // Store tokens
        refreshToken = data.refresh_token;
        accessToken = data.access_token;

        // Per-user flow: save to the user's integration record
        if (integrationId) {
          const creds = {
            client_id: clientId,
            client_secret: clientSecret,
            refresh_token: data.refresh_token,
          };

          // Only send credentials — the integration's config (folder_id, etc.)
          // is already set and must not be overwritten here.
          const body = { credentials: creds };

          document.getElementById('processing-message').innerHTML =
            '<p>Saving credentials to your integration...</p>';

          return fetch(`/api/integrations/${integrationId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
          }).then(response => {
            if (!response.ok) {
              return response.json().then(err => {
                throw new Error('Failed to save credentials: ' + (err.detail || 'Unknown error'));
              });
            }
            return response.json();
          }).then(() => {
            // Clean up
            sessionStorage.removeItem('google_drive_client_id');
            sessionStorage.removeItem('google_drive_client_secret');
            sessionStorage.removeItem('google_drive_folder_id');
            sessionStorage.removeItem('google_drive_use_oauth');
            sessionStorage.removeItem('oauth_integration_id');

            // Show brief success then redirect to integrations
            document.getElementById('processing-message').innerHTML =
              '<p class="text-green-600 font-semibold">✓ Google Drive authorized successfully!</p>' +
              '<p class="text-sm text-gray-500 mt-2">Redirecting to Integrations...</p>';
            document.querySelector('.animate-spin').parentNode.classList.add('hidden');
            setTimeout(() => { window.location.href = '/integrations'; }, 2000);
          });
        }

        // Global flow: update settings in memory first
        const updateFormData = new FormData();
        updateFormData.append('refresh_token', data.refresh_token);

        // Use the client ID and client secret from session storage
        updateFormData.append('client_id', clientId);
        updateFormData.append('client_secret', clientSecret);
        if (folderId) {
          updateFormData.append('folder_id', folderId);
        }
        updateFormData.append('use_oauth', 'true');

        document.getElementById('processing-message').innerHTML =
          '<p>Updating system settings with new token...</p>';

        return fetch('/api/google-drive/update-settings', {
          method: 'POST',
          body: updateFormData
        }).then(response => {
          if (!response.ok) {
            return response.json().then(err => {
              throw new Error('Token received but failed to update settings: ' + (err.detail || 'Unknown error'));
            });
          }
          return response.json();
        }).then(() => {
          // If we have a folder ID, save settings directly
          if (folderId) {
            return saveSettings(data.refresh_token, clientId, clientSecret, folderId);
          } else {
            // Show folder selection UI
            document.getElementById('processing-message').classList.add('hidden');
            document.getElementById('folder-selection-container').classList.remove('hidden');

            // Initialize Google Picker for folder selection
            loadGooglePicker(accessToken, clientId);

            return null;  // Return null to avoid further .then() processing
          }
        });
      } else {
        throw new Error('No refresh token was received from the server');
      }
    })
    .then(result => {
      // Only proceed if we saved settings directly
      if (result) {
        showSuccess(result.refresh_token, result.client_id, result.client_secret, result.folderId);
      }
    })
    .catch(error => {
      showError(error.message);
    });
  }

  function showError(message) {
    document.getElementById('processing-message').classList.add('hidden');
    document.getElementById('folder-selection-container').classList.add('hidden');
    document.getElementById('error-container').classList.remove('hidden');
    document.getElementById('error-message').innerText = message;

    // Hide the spinner when showing error
    document.querySelector('.animate-spin').parentNode.classList.add('hidden');
  }

  function saveSettings(refreshToken, clientId, clientSecret, folderId) {
    const saveFormData = new FormData();
    saveFormData.append('refresh_token', refreshToken);
    saveFormData.append('client_id', clientId);
    saveFormData.append('client_secret', clientSecret);
    if (folderId) {
      saveFormData.append('folder_id', folderId);
    }
    saveFormData.append('use_oauth', 'true');

    document.getElementById('processing-message').innerHTML =
      '<p>Saving settings to configuration...</p>';

    return fetch('/api/google-drive/save-settings', {
      method: 'POST',
      body: saveFormData
    }).then(response => {
      if (!response.ok) {
        return response.json().then(err => {
          // Check if the error is about .env file not found
          if (err.detail && err.detail.includes('.env file not found')) {
            // Continue despite .env file issue
            return {
              status: 'warning',
              message: 'Settings saved in memory only. The .env file could not be updated.',
              in_memory_only: true
            };
          }
          throw new Error('Failed to save settings to file: ' + (err.detail || 'Unknown error'));
        });
      }
      return response.json();
    }).then((result) => {
      // Return the values for showing success screen
      return {
        refresh_token: refreshToken,
        client_id: clientId,
        client_secret: clientSecret,
        folderId: folderId,
        in_memory_only: result.in_memory_only || false
      };
    });
  }

  function showSuccess(refreshToken, clientId, clientSecret, folderId, inMemoryOnly) {
    document.getElementById('processing-message').classList.add('hidden');
    document.getElementById('folder-selection-container').classList.add('hidden');
    document.getElementById('success-container').classList.remove('hidden');

    // Hide the spinner when showing success
    document.querySelector('.animate-spin').parentNode.classList.add('hidden');

    // Update the environment variables pre block with the new token
    const envVarsCode = document.querySelector('#env-vars code');
    if (envVarsCode) {
      envVarsCode.textContent = `GOOGLE_DRIVE_USE_OAUTH=true
GOOGLE_DRIVE_CLIENT_ID=${clientId}
GOOGLE_DRIVE_CLIENT_SECRET=${clientSecret}
GOOGLE_DRIVE_REFRESH_TOKEN=${refreshToken}
GOOGLE_DRIVE_FOLDER_ID=${folderId || 'YOUR_FOLDER_ID'}`;
    }

    // If settings were only saved in memory, add a warning
    if (inMemoryOnly) {
      const successContainer = document.getElementById('success-container');
      const warningDiv = document.createElement('div');
      warningDiv.className = 'rounded-md bg-yellow-50 p-4 mt-4';
      warningDiv.innerHTML = `
        <div class="flex">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-yellow-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3">
            <p class="text-sm font-medium text-yellow-800">
              Note: Settings were saved in memory only. The .env file could not be updated.
              Make sure to add these environment variables to your configuration files manually.
            </p>
          </div>
        </div>
      `;

      // Insert warning after the success message but before the environment vars section
      const envVarsSection = document.querySelector('#success-container .mt-6');
      successContainer.insertBefore(warningDiv, envVarsSection);
    }

    // Add copy functionality
    const copyEnvVarsBtn = document.getElementById('copy-env-vars');
    if (copyEnvVarsBtn) {
      copyEnvVarsBtn.addEventListener('click', function() {
        const envVarsText = document.getElementById('env-vars').textContent;
        navigator.clipboard.writeText(envVarsText)
          .then(() => {
            const originalText = copyEnvVarsBtn.textContent;
            copyEnvVarsBtn.textContent = 'Copied!';
            copyEnvVarsBtn.classList.add('bg-green-700');
            setTimeout(() => {
              copyEnvVarsBtn.textContent = originalText;
              copyEnvVarsBtn.classList.remove('bg-green-700');
            }, 2000);
          })
          .catch(err => {
            console.error('Failed to copy: ', err);
            alert('Failed to copy text to clipboard');
          });
      });
    }

    // Clear session storage
    sessionStorage.removeItem('google_drive_client_id');
    sessionStorage.removeItem('google_drive_client_secret');
    sessionStorage.removeItem('google_drive_folder_id');

    // In 10 seconds, redirect to status page
    setTimeout(() => {
      window.location.href = '/status';
    }, 10000);
  }

  // Handle folder selection UI
  if (saveFolderBtn) {
    saveFolderBtn.addEventListener('click', function() {
      if (!folderIdInput) {
        alert('Error: Folder input element not found');
        return;
      }

      const folderId = folderIdInput.value.trim() || 'root';
      saveFolderBtn.disabled = true;
      saveFolderBtn.innerHTML = '<span class="animate-spin inline-block mr-2">⟳</span> Saving...';

      saveSettings(refreshToken, clientId, clientSecret, folderId)
        .then(result => {
          showSuccess(result.refresh_token, result.client_id, result.client_secret, result.folderId);
        })
        .catch(error => {
          alert('Failed to save settings: ' + error.message);
          saveFolderBtn.disabled = false;
          saveFolderBtn.textContent = 'Save Settings';
        });
    });
  }

  // Function to load and initialize the Google Picker
  function loadGooglePicker(accessToken, clientId) {
    // Load the Google API Loader script
    const script = document.createElement('script');
    script.src = 'https://apis.google.com/js/api.js';
    script.onload = function() {
      gapi.load('picker', function() {
        initGooglePicker(accessToken, clientId);
      });
    };
    document.body.appendChild(script);
  }

  // Initialize and setup the Google Picker
  function initGooglePicker(accessToken, clientId) {
    if (!accessToken || !clientId || !folderSelectBtn) {
      return;
    }

    // Setup the click handler for the folder select button
    folderSelectBtn.addEventListener('click', function() {
      // Create the folder picker view
      const folderView = new google.picker.DocsView(google.picker.ViewId.FOLDERS)
        .setIncludeFolders(true)
        .setSelectFolderEnabled(true)
        .setMode(google.picker.DocsViewMode.LIST); // Use LIST mode to work with the drive.file scope

      // Create and render the picker
      const picker = new google.picker.PickerBuilder()
        .addView(folderView)
        .setOAuthToken(accessToken)
        .setOrigin(window.location.protocol + '//' + window.location.host)
        .setTitle('Select a folder for DocuElevate')
        .setCallback(pickerCallback)
        .build();

      picker.setVisible(true);
    });
  }

  // Callback function for picker
  function pickerCallback(data) {
    if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
      const folder = data[google.picker.Response.DOCUMENTS][0];
      const folderId = folder[google.picker.Document.ID];
      const folderName = folder[google.picker.Document.NAME];

      // Update the folder ID input
      if (folderIdInput) {
        folderIdInput.value = folderId;

        // Add visual confirmation instead of alert
        const confirmationMsg = document.createElement('div');
        confirmationMsg.className = 'mt-2 text-sm text-green-600';
        confirmationMsg.innerHTML = `<svg class="inline-block h-4 w-4 mr-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
          <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
        </svg> Selected folder: "${folderName}"`;

        // Remove previous confirmation if it exists
        const existingConfirmation = folderIdInput.parentNode.querySelector('.text-green-600');
        if (existingConfirmation) {
          existingConfirmation.remove();
        }

        // Insert the confirmation message after the input field
        folderIdInput.parentNode.appendChild(confirmationMsg);
      }
    }
  }
});
</script>
{% endblock %}
