@extends('layouts.ownerLayout')

@section('title', 'Configuración')

@section('vendor-style')
@vite([
  'resources/assets/vendor/libs/notyf/notyf.scss',
  'resources/assets/vendor/libs/@form-validation/form-validation.scss'
])
@endsection

@section('vendor-script')
@vite([
  'resources/assets/vendor/libs/notyf/notyf.js',
  'resources/assets/vendor/libs/@form-validation/popular.js',
  'resources/assets/vendor/libs/@form-validation/bootstrap5.js',
  'resources/assets/vendor/libs/@form-validation/auto-focus.js'
])
@endsection

@section('page-script')
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const toastData = {
      success: @json(session('status')),
      errors: @json($errors->all())
    };

    const notyf = new Notyf({
      duration: 3500,
      dismissible: true,
      position: { x: 'right', y: 'top' }
    });

    if (toastData.success) {
      notyf.success(toastData.success);
    }

    if (Array.isArray(toastData.errors) && toastData.errors.length) {
      toastData.errors.forEach(msg => notyf.error(msg));
    }

    const generatedTokenField = document.getElementById('generatedApiTokenValue');
    const copyGeneratedTokenButton = document.getElementById('copyGeneratedApiToken');
    if (generatedTokenField && copyGeneratedTokenButton && navigator.clipboard) {
      copyGeneratedTokenButton.addEventListener('click', async () => {
        try {
          await navigator.clipboard.writeText(generatedTokenField.value);
          notyf.success('Token copiado al portapapeles.');
        } catch (error) {
          notyf.error('No se pudo copiar el token.');
        }
      });
    }

    const form = document.getElementById('ownerApiSettingsForm');
    if (form && window.FormValidation) {
      FormValidation.formValidation(form, {
        fields: {
          google_maps_country: {
            validators: {
              regexp: {
                regexp: /^[a-zA-Z]{2}$/,
                message: 'Usa un código de país ISO-2 (ej: co, mx, us).'
              }
            }
          }
        },
        plugins: {
          trigger: new FormValidation.plugins.Trigger(),
          bootstrap5: new FormValidation.plugins.Bootstrap5({
            eleValidClass: '',
            rowSelector: '.form-control-validation'
          }),
          defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
          submitButton: new FormValidation.plugins.SubmitButton(),
          autoFocus: new FormValidation.plugins.AutoFocus()
        }
      });
    }

    const tokenActionType = @json(old('token_action_type'));
    if (tokenActionType === 'create') {
      const createModalEl = document.getElementById('createApiTokenModal');
      if (createModalEl && window.bootstrap) {
        bootstrap.Modal.getOrCreateInstance(createModalEl).show();
      }
    }

    if (tokenActionType === 'reset') {
      const resetModalEl = document.getElementById('resetApiTokenModal');
      if (resetModalEl && window.bootstrap) {
        bootstrap.Modal.getOrCreateInstance(resetModalEl).show();
      }
    }
  });
</script>
@endsection

@section('content')
@if (!$organization)
  <div class="alert alert-warning">
    Tu usuario no tiene organización asignada. Pide al administrador vincular tu cuenta para configurar APIs.
  </div>
@else
  @php
    $maskApiKey = function (?string $value): string {
      $value = trim((string) $value);
      if ($value === '') {
        return 'sin configurar';
      }
      $len = mb_strlen($value, 'UTF-8');
      if ($len <= 8) {
        return str_repeat('*', $len);
      }
      return mb_substr($value, 0, 4, 'UTF-8') . '...' . mb_substr($value, -4, null, 'UTF-8');
    };

    $googleKeyMasked = $maskApiKey($organization->google_maps_api_key ?? null);
    $geminiKeyMasked = $maskApiKey($organization->gemini_api_key ?? null);
    $googleConfigured = !empty($organization->google_maps_api_key);
    $geminiConfigured = !empty($organization->gemini_api_key);
    $activeApiTokens = $apiTokens->whereNull('revoked_at')->values();
  @endphp

  @if(session('api_token_plaintext'))
    <div class="alert alert-warning alert-dismissible fade show mb-6" role="alert">
      <div class="d-flex flex-column gap-3">
        <div>
          <h6 class="alert-heading mb-1">Token generado una sola vez</h6>
          <p class="mb-0 text-body-secondary">
            Guarda este token en n8n, Chatwoot o en tu agente de IA. Después de salir de esta pantalla ya no se vuelve a mostrar.
          </p>
        </div>
        <div class="input-group">
          <input
            type="text"
            class="form-control"
            id="generatedApiTokenValue"
            readonly
            value="{{ session('api_token_plaintext') }}">
          <button class="btn btn-outline-primary" type="button" id="copyGeneratedApiToken">Copiar</button>
        </div>
        <div class="small text-body-secondary">
          Nombre: <strong>{{ session('api_token_name') }}</strong>
          @if(session('api_token_action') === 'reset')
            | Acción: <strong>Restablecido</strong>
          @else
            | Acción: <strong>Creado</strong>
          @endif
        </div>
      </div>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  @endif

  <div class="card mb-6">
    <div class="card-header border-bottom d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3">
      <div>
        <h5 class="card-title mb-1">Token personal para integraciones</h5>
        <p class="mb-0 text-body-secondary">
          Cada token pertenece a tu usuario y respeta tus permisos y grupos mariachi. Úsalo con `Authorization: Bearer TU_TOKEN`.
        </p>
      </div>
      <div class="d-flex flex-wrap gap-2">
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createApiTokenModal">
          Generar token
        </button>
        <button type="button" class="btn btn-label-warning" data-bs-toggle="modal" data-bs-target="#resetApiTokenModal">
          Restablecer token
        </button>
      </div>
    </div>

    <div class="card-body">
      <div class="row g-4 mb-5">
        <div class="col-md-4">
          <div class="border rounded p-4 h-100">
            <div class="text-body-secondary small mb-1">Tokens activos</div>
            <div class="fs-3 fw-semibold">{{ $activeApiTokens->count() }}</div>
          </div>
        </div>
        <div class="col-md-4">
          <div class="border rounded p-4 h-100">
            <div class="text-body-secondary small mb-1">Tu usuario</div>
            <div class="fw-semibold">{{ $organization->name }}</div>
            <div class="small text-body-secondary">{{ auth()->user()->email }}</div>
          </div>
        </div>
        <div class="col-md-4">
          <div class="border rounded p-4 h-100">
            <div class="text-body-secondary small mb-1">Uso recomendado</div>
            <div class="fw-semibold">n8n, Chatwoot, IA</div>
            <div class="small text-body-secondary">Un token por integración o uno único restablecible.</div>
          </div>
        </div>
      </div>

      <div class="table-responsive">
        <table class="table table-borderless align-middle mb-0">
          <thead class="border-bottom">
            <tr>
              <th>Nombre</th>
              <th>Prefijo</th>
              <th>Estado</th>
              <th>Último uso</th>
              <th>Creado</th>
              <th class="text-end">Acción</th>
            </tr>
          </thead>
          <tbody>
            @forelse($apiTokens as $token)
              <tr class="border-bottom">
                <td>
                  <div class="fw-medium">{{ $token->name }}</div>
                  <div class="small text-body-secondary">ID {{ $token->id }}</div>
                </td>
                <td><code>{{ $token->token_prefix }}</code></td>
                <td>
                  @if($token->revoked_at)
                    <span class="badge bg-label-secondary">Revocado</span>
                  @else
                    <span class="badge bg-label-success">Activo</span>
                  @endif
                </td>
                <td class="small text-body-secondary">
                  {{ $token->last_used_at ? $token->last_used_at->format('d/m/Y H:i') : 'Sin uso' }}
                </td>
                <td class="small text-body-secondary">{{ optional($token->created_at)->format('d/m/Y H:i') }}</td>
                <td class="text-end">
                  @if(!$token->revoked_at)
                    <form method="POST" action="{{ route('owner.settings.api-tokens.revoke', $token) }}" class="d-inline">
                      @csrf
                      <button
                        type="submit"
                        class="btn btn-sm btn-label-danger"
                        onclick="return confirm('Vas a revocar este token. La integración que lo use dejará de funcionar.');">
                        Revocar
                      </button>
                    </form>
                  @else
                    <span class="small text-body-secondary">Sin acciones</span>
                  @endif
                </td>
              </tr>
            @empty
              <tr>
                <td colspan="6" class="text-center py-5 text-body-secondary">
                  Aún no has generado tokens API para tu usuario.
                </td>
              </tr>
            @endforelse
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="card mb-6">
    <div class="card-header border-bottom">
      <h5 class="card-title mb-1">Integraciones</h5>
      <p class="mb-0 text-body-secondary">Configura Google Maps para autocompletar direcciones y Gemini para autocompletado por IA.</p>
    </div>

    <div class="card-body">
      <form id="ownerApiSettingsForm" method="POST" action="{{ route('owner.settings.update') }}">
        @csrf

        <div class="row g-5">
          <div class="col-12 col-lg-6">
            <div class="border rounded p-4 h-100">
              <h6 class="mb-3">Google Maps API</h6>

              <div class="mb-4 form-control-validation">
                <label class="form-label" for="google_maps_api_key">API Key</label>
                <input
                  type="password"
                  class="form-control"
                  id="google_maps_api_key"
                  name="google_maps_api_key"
                  placeholder="AIza..."
                  autocomplete="off">
                <small class="text-body-secondary">
                  Estado:
                  @if($googleConfigured)
                    <span class="badge bg-label-success">Configurada</span>
                  @else
                    <span class="badge bg-label-warning">Sin configurar</span>
                  @endif
                  | Huella: <code>{{ $googleKeyMasked }}</code>.
                  Si dejas vacío, no se reemplaza.
                </small>
              </div>

              <div class="mb-0 form-control-validation">
                <label class="form-label" for="google_maps_country">País para autocompletar</label>
                <input
                  type="text"
                  class="form-control"
                  id="google_maps_country"
                  name="google_maps_country"
                  maxlength="2"
                  value="{{ old('google_maps_country', $organization->google_maps_country ?? 'co') }}"
                  placeholder="co">
                <small class="text-body-secondary">Código ISO-2. Ejemplos: co, mx, us.</small>
              </div>
            </div>
          </div>

          <div class="col-12 col-lg-6">
            <div class="border rounded p-4 h-100">
              <h6 class="mb-3">Gemini API</h6>

              <div class="mb-4 form-control-validation">
                <label class="form-label" for="gemini_api_key">API Key</label>
                <input
                  type="password"
                  class="form-control"
                  id="gemini_api_key"
                  name="gemini_api_key"
                  placeholder="AIza..."
                  autocomplete="off">
                <small class="text-body-secondary">
                  Estado:
                  @if($geminiConfigured)
                    <span class="badge bg-label-success">Configurada</span>
                  @else
                    <span class="badge bg-label-warning">Sin configurar</span>
                  @endif
                  | Huella: <code>{{ $geminiKeyMasked }}</code>.
                  Si dejas vacío, no se reemplaza.
                </small>
              </div>

              <div class="form-check form-control-validation">
                <input class="form-check-input" type="checkbox" value="1" id="replace_keys" name="replace_keys">
                <label class="form-check-label" for="replace_keys">
                  Reemplazar claves actuales (si no marcas, solo se actualizan campos con valor).
                </label>
              </div>
            </div>
          </div>
        </div>

        <div class="mt-5 d-flex gap-2">
          <button type="submit" class="btn btn-primary">Guardar configuración</button>
          <a href="{{ route('owner.dashboard') }}" class="btn btn-label-secondary">Cancelar</a>
        </div>
      </form>
    </div>
  </div>

  <div class="modal fade" id="createApiTokenModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header border-bottom">
          <h5 class="modal-title">Generar token API</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form method="POST" action="{{ route('owner.settings.api-tokens.store') }}">
          @csrf
          <input type="hidden" name="token_action_type" value="create">
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label" for="create_token_name">Nombre del token</label>
              <input
                type="text"
                class="form-control"
                id="create_token_name"
                name="name"
                maxlength="120"
                value="{{ old('token_action_type') === 'create' ? old('name', 'n8n chatwoot') : 'n8n chatwoot' }}"
                placeholder="n8n chatwoot">
              <small class="text-body-secondary">Usa un nombre que identifique la integración o el agente que lo consume.</small>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
            <button type="submit" class="btn btn-primary">Generar token</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <div class="modal fade" id="resetApiTokenModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header border-bottom">
          <h5 class="modal-title">Restablecer token API</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form method="POST" action="{{ route('owner.settings.api-tokens.reset') }}">
          @csrf
          <input type="hidden" name="token_action_type" value="reset">
          <div class="modal-body">
            <div class="alert alert-warning mb-4">
              Esta acción revoca todos tus tokens activos y genera uno nuevo. Las integraciones actuales dejarán de funcionar hasta actualizar el secreto.
            </div>
            <div class="mb-0">
              <label class="form-label" for="reset_token_name">Nombre del nuevo token</label>
              <input
                type="text"
                class="form-control"
                id="reset_token_name"
                name="name"
                maxlength="120"
                value="{{ old('token_action_type') === 'reset' ? old('name', 'token principal') : 'token principal' }}"
                placeholder="token principal">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">Cancelar</button>
            <button type="submit" class="btn btn-warning">Restablecer token</button>
          </div>
        </form>
      </div>
    </div>
  </div>
@endif
@endsection
