<p-toast />

<div class="ai-settings-page">
  <app-page-header title="AI_SETTINGS.TITLE" subtitle="AI_SETTINGS.SUBTITLE" (refresh)="loadAll()">
  </app-page-header>

  @if (loading()) {
    <div class="loading-state">
      <p-progressSpinner strokeWidth="3" />
      <p>{{ 'COMMON.LOADING' | translate }}</p>
    </div>
  } @else {
    <p-tabs [value]="activeTab()" (valueChange)="activeTab.set(+($event ?? 0))">
      <p-tablist>
        <p-tab [value]="0">
          <i class="pi pi-cog tab-icon"></i>
          {{ 'AI_SETTINGS.TAB_SETTINGS' | translate }}
        </p-tab>
        <p-tab [value]="1">
          <i class="pi pi-user tab-icon"></i>
          {{ 'AI_SETTINGS.TAB_PREFERENCES' | translate }}
        </p-tab>
        <p-tab [value]="2">
          <i class="pi pi-chart-bar tab-icon"></i>
          {{ 'AI_SETTINGS.TAB_USAGE' | translate }}
        </p-tab>
        <p-tab [value]="3">
          <i class="pi pi-chart-line tab-icon"></i>
          {{ 'AI_SETTINGS.TAB_MY_USAGE' | translate }}
        </p-tab>
      </p-tablist>

      <p-tabpanels>
        <!-- ===== Settings Tab ===== -->
        <p-tabpanel [value]="0">
          @if (settings(); as s) {
            <div class="settings-section">
              <!-- Provider Settings -->
              <div class="section-card">
                <div class="section-header">
                  <i class="pi pi-cloud"></i>
                  <h3>{{ 'AI_SETTINGS.PROVIDER_SETTINGS' | translate }}</h3>
                </div>
                <div class="section-body">
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.DEFAULT_PROVIDER' | translate }}</label>
                    <p-select
                      [options]="providerOptions"
                      [(ngModel)]="editSettings.default_provider"
                      optionLabel="label"
                      optionValue="value"
                      [style]="{ width: '100%' }"
                    />
                  </div>

                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.ENABLED' | translate }}</label>
                    <p-toggleSwitch [(ngModel)]="editSettings.is_enabled" />
                  </div>
                </div>
              </div>

              <!-- DeepSeek Config -->
              <div class="section-card">
                <div class="section-header">
                  <i class="pi pi-bolt"></i>
                  <h3>DeepSeek</h3>
                  @if (s.deepseek_api_key) {
                    <p-tag severity="success" value="Configured" />
                  } @else {
                    <p-tag severity="warn" value="Not Configured" />
                  }
                </div>
                <div class="section-body">
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.API_KEY' | translate }}</label>
                    <input
                      pInputText
                      type="password"
                      [(ngModel)]="editSettings.deepseek_api_key"
                      [placeholder]="s.deepseek_api_key ? '••••••••' : 'AI_SETTINGS.ENTER_KEY' | translate"
                      style="width: 100%"
                    />
                  </div>
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.MODEL' | translate }}</label>
                    <input
                      pInputText
                      [(ngModel)]="editSettings.deepseek_model"
                      style="width: 100%"
                    />
                  </div>
                </div>
              </div>

              <!-- OpenAI Config -->
              <div class="section-card">
                <div class="section-header">
                  <i class="pi pi-sparkles"></i>
                  <h3>OpenAI</h3>
                  @if (s.openai_api_key) {
                    <p-tag severity="success" value="Configured" />
                  } @else {
                    <p-tag severity="warn" value="Not Configured" />
                  }
                </div>
                <div class="section-body">
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.API_KEY' | translate }}</label>
                    <input
                      pInputText
                      type="password"
                      [(ngModel)]="editSettings.openai_api_key"
                      [placeholder]="s.openai_api_key ? '••••••••' : 'AI_SETTINGS.ENTER_KEY' | translate"
                      style="width: 100%"
                    />
                  </div>
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.MODEL' | translate }}</label>
                    <input
                      pInputText
                      [(ngModel)]="editSettings.openai_model"
                      style="width: 100%"
                    />
                  </div>
                </div>
              </div>

              <!-- Limits & Cache -->
              <div class="section-card">
                <div class="section-header">
                  <i class="pi pi-sliders-h"></i>
                  <h3>{{ 'AI_SETTINGS.LIMITS_CACHE' | translate }}</h3>
                </div>
                <div class="section-body">
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.MAX_TOKENS' | translate }}</label>
                    <p-inputNumber
                      [(ngModel)]="editSettings.max_tokens_per_request"
                      [min]="100"
                      [max]="8000"
                      [step]="256"
                      [showButtons]="true"
                      [style]="{ width: '100%' }"
                    />
                  </div>
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.MONTHLY_TOKEN_LIMIT' | translate }}</label>
                    <p-inputNumber
                      [(ngModel)]="editSettings.monthly_token_limit"
                      [min]="0"
                      [step]="10000"
                      [showButtons]="true"
                      [style]="{ width: '100%' }"
                      [placeholder]="'AI_SETTINGS.UNLIMITED' | translate"
                    />
                  </div>
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.USD_TO_EGP' | translate }}</label>
                    <p-inputNumber
                      [(ngModel)]="editSettings.usd_to_egp_rate"
                      [minFractionDigits]="2"
                      [maxFractionDigits]="4"
                      [min]="0"
                      [showButtons]="true"
                      [style]="{ width: '100%' }"
                    />
                  </div>
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.CACHE_ENABLED' | translate }}</label>
                    <p-toggleSwitch [(ngModel)]="editSettings.cache_enabled" />
                  </div>
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.CACHE_TTL' | translate }}</label>
                    <p-inputNumber
                      [(ngModel)]="editSettings.cache_ttl_hours"
                      [min]="1"
                      [max]="720"
                      [step]="24"
                      [showButtons]="true"
                      suffix=" hrs"
                      [style]="{ width: '100%' }"
                    />
                  </div>
                </div>
              </div>

              <!-- Save Button -->
              <div class="save-bar">
                <p-button
                  [label]="'COMMON.SAVE' | translate"
                  icon="pi pi-check"
                  (onClick)="saveSettings()"
                  [loading]="saving()"
                />
              </div>
            </div>
          } @else {
            <div class="empty-state">
              <i class="pi pi-lock"></i>
              <p>{{ 'AI_SETTINGS.NO_PERMISSION_SETTINGS' | translate }}</p>
            </div>
          }
        </p-tabpanel>

        <!-- ===== Preferences Tab ===== -->
        <p-tabpanel [value]="1">
          @if (preferences(); as p) {
            <div class="settings-section">
              <div class="section-card">
                <div class="section-header">
                  <i class="pi pi-user-edit"></i>
                  <h3>{{ 'AI_SETTINGS.MY_PREFERENCES' | translate }}</h3>
                </div>
                <div class="section-body">
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.PREFERRED_PROVIDER' | translate }}</label>
                    <p-select
                      [options]="prefProviderOptions"
                      [(ngModel)]="editPrefs.preferred_provider"
                      optionLabel="label"
                      optionValue="value"
                      [style]="{ width: '100%' }"
                    />
                  </div>
                  <div class="form-row">
                    <label>{{ 'AI_SETTINGS.AI_ENABLED' | translate }}</label>
                    <p-toggleSwitch [(ngModel)]="editPrefs.is_enabled" />
                  </div>
                </div>
              </div>

              <div class="save-bar">
                <p-button
                  [label]="'COMMON.SAVE' | translate"
                  icon="pi pi-check"
                  (onClick)="savePreferences()"
                  [loading]="saving()"
                />
              </div>
            </div>
          }
        </p-tabpanel>

        <!-- ===== Usage Tab (Admin) ===== -->
        <p-tabpanel [value]="2">
          <!-- Date Filters -->
          <div class="filter-bar">
            <div class="filter-group">
              <label>{{ 'AI_SETTINGS.FROM' | translate }}</label>
              <p-datePicker
                [(ngModel)]="usageFrom"
                dateFormat="yy-mm-dd"
                [showIcon]="true"
                [style]="{ width: '180px' }"
              />
            </div>
            <div class="filter-group">
              <label>{{ 'AI_SETTINGS.TO' | translate }}</label>
              <p-datePicker
                [(ngModel)]="usageTo"
                dateFormat="yy-mm-dd"
                [showIcon]="true"
                [style]="{ width: '180px' }"
              />
            </div>
            <p-button
              icon="pi pi-filter"
              [label]="'AI_SETTINGS.FILTER' | translate"
              (onClick)="filterUsage()"
              severity="secondary"
            />
          </div>

          @if (usageLoading()) {
            <div class="loading-state compact">
              <p-progressSpinner strokeWidth="3" />
            </div>
          } @else if (usage(); as u) {
            <!-- Summary Cards -->
            <div class="stats-grid">
              <div class="stat-card">
                <div class="stat-icon requests"><i class="pi pi-send"></i></div>
                <div class="stat-info">
                  <span class="stat-value">{{ u.totals.total_requests | number }}</span>
                  <span class="stat-label">{{ 'AI_SETTINGS.TOTAL_REQUESTS' | translate }}</span>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon tokens"><i class="pi pi-code"></i></div>
                <div class="stat-info">
                  <span class="stat-value">{{ u.totals.total_tokens | number }}</span>
                  <span class="stat-label">{{ 'AI_SETTINGS.TOTAL_TOKENS' | translate }}</span>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon cost-usd"><i class="pi pi-dollar"></i></div>
                <div class="stat-info">
                  <span class="stat-value">${{ u.totals.total_cost_usd | number:'1.4-4' }}</span>
                  <span class="stat-label">{{ 'AI_SETTINGS.COST_USD' | translate }}</span>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon cost-egp"><i class="pi pi-money-bill"></i></div>
                <div class="stat-info">
                  <span class="stat-value">{{ u.totals.total_cost_egp | number:'1.2-2' }} EGP</span>
                  <span class="stat-label">{{ 'AI_SETTINGS.COST_EGP' | translate }}</span>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon cached"><i class="pi pi-bolt"></i></div>
                <div class="stat-info">
                  <span class="stat-value">{{ u.totals.cached_requests | number }}</span>
                  <span class="stat-label">{{ 'AI_SETTINGS.CACHED_REQUESTS' | translate }}</span>
                </div>
              </div>
            </div>

            <!-- By Provider -->
            @if (u.by_provider.length > 0) {
              <div class="section-card">
                <div class="section-header">
                  <i class="pi pi-cloud"></i>
                  <h3>{{ 'AI_SETTINGS.BY_PROVIDER' | translate }}</h3>
                </div>
                <p-table [value]="u.by_provider" [rows]="10" styleClass="p-datatable-sm">
                  <ng-template #header>
                    <tr>
                      <th>{{ 'AI_SETTINGS.PROVIDER' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.REQUESTS' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.TOKENS' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.COST_USD' | translate }}</th>
                    </tr>
                  </ng-template>
                  <ng-template #body let-row>
                    <tr>
                      <td>
                        <p-tag [value]="row.provider" [severity]="row.provider === 'deepseek' ? 'info' : 'success'" />
                      </td>
                      <td>{{ row.total_requests | number }}</td>
                      <td>{{ row.total_tokens | number }}</td>
                      <td>${{ row.total_cost_usd | number:'1.4-4' }}</td>
                    </tr>
                  </ng-template>
                </p-table>
              </div>
            }

            <!-- By User -->
            @if (u.by_user.length > 0) {
              <div class="section-card">
                <div class="section-header">
                  <i class="pi pi-users"></i>
                  <h3>{{ 'AI_SETTINGS.BY_USER' | translate }}</h3>
                </div>
                <p-table [value]="u.by_user" [rows]="10" styleClass="p-datatable-sm">
                  <ng-template #header>
                    <tr>
                      <th>{{ 'AI_SETTINGS.USER' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.REQUESTS' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.TOKENS' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.COST_USD' | translate }}</th>
                    </tr>
                  </ng-template>
                  <ng-template #body let-row>
                    <tr>
                      <td>{{ row.user_name }}</td>
                      <td>{{ row.total_requests | number }}</td>
                      <td>{{ row.total_tokens | number }}</td>
                      <td>${{ row.total_cost_usd | number:'1.4-4' }}</td>
                    </tr>
                  </ng-template>
                </p-table>
              </div>
            }

            @if (u.by_provider.length === 0 && u.by_user.length === 0) {
              <div class="empty-state">
                <i class="pi pi-chart-bar"></i>
                <p>{{ 'AI_SETTINGS.NO_USAGE_DATA' | translate }}</p>
              </div>
            }
          }
        </p-tabpanel>

        <!-- ===== My Usage Tab ===== -->
        <p-tabpanel [value]="3">
          @if (myUsage(); as mu) {
            <!-- My Stats -->
            <div class="stats-grid">
              <div class="stat-card">
                <div class="stat-icon requests"><i class="pi pi-send"></i></div>
                <div class="stat-info">
                  <span class="stat-value">{{ mu.totals.total_requests | number }}</span>
                  <span class="stat-label">{{ 'AI_SETTINGS.MY_REQUESTS' | translate }}</span>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon tokens"><i class="pi pi-code"></i></div>
                <div class="stat-info">
                  <span class="stat-value">{{ mu.totals.total_tokens | number }}</span>
                  <span class="stat-label">{{ 'AI_SETTINGS.MY_TOKENS' | translate }}</span>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon cost-usd"><i class="pi pi-dollar"></i></div>
                <div class="stat-info">
                  <span class="stat-value">${{ mu.totals.total_cost_usd | number:'1.4-4' }}</span>
                  <span class="stat-label">{{ 'AI_SETTINGS.COST_USD' | translate }}</span>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon cached"><i class="pi pi-bolt"></i></div>
                <div class="stat-info">
                  <span class="stat-value">{{ mu.totals.cached_requests | number }}</span>
                  <span class="stat-label">{{ 'AI_SETTINGS.CACHED_REQUESTS' | translate }}</span>
                </div>
              </div>
            </div>

            <!-- Recent Activity -->
            @if (mu.recent.length > 0) {
              <div class="section-card">
                <div class="section-header">
                  <i class="pi pi-history"></i>
                  <h3>{{ 'AI_SETTINGS.RECENT_ACTIVITY' | translate }}</h3>
                </div>
                <p-table [value]="mu.recent" [rows]="10" [paginator]="mu.recent.length > 10" styleClass="p-datatable-sm">
                  <ng-template #header>
                    <tr>
                      <th>{{ 'AI_SETTINGS.DATE' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.PROVIDER' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.TOKENS' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.COST_USD' | translate }}</th>
                      <th>{{ 'AI_SETTINGS.CACHED' | translate }}</th>
                    </tr>
                  </ng-template>
                  <ng-template #body let-row>
                    <tr>
                      <td>{{ row.created_at | date:'short' }}</td>
                      <td>
                        <p-tag [value]="row.provider" [severity]="row.provider === 'deepseek' ? 'info' : 'success'" />
                      </td>
                      <td>{{ row.tokens_used | number }}</td>
                      <td>${{ row.cost_usd | number:'1.6-6' }}</td>
                      <td>
                        @if (row.cached) {
                          <p-tag severity="info" value="Cached" />
                        }
                      </td>
                    </tr>
                  </ng-template>
                </p-table>
              </div>
            } @else {
              <div class="empty-state">
                <i class="pi pi-chart-line"></i>
                <p>{{ 'AI_SETTINGS.NO_USAGE_DATA' | translate }}</p>
              </div>
            }
          }
        </p-tabpanel>
      </p-tabpanels>
    </p-tabs>
  }
</div>
