import { Component, inject, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { InputTextModule } from 'primeng/inputtext';
import { ButtonModule } from 'primeng/button';
import { SelectModule } from 'primeng/select';
import { ToastModule } from 'primeng/toast';
import { CardModule } from 'primeng/card';
import { ProgressSpinnerModule } from 'primeng/progressspinner';
import { MessageService } from 'primeng/api';
import { environment } from '../../../environments/environment';
import { User } from '../../core/models/auth.model';
import { ApiResponse } from '../../core/models/api.model';

@Component({
  selector: 'app-profile',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TranslateModule,
    InputTextModule,
    ButtonModule,
    SelectModule,
    ToastModule,
    CardModule,
    ProgressSpinnerModule,
  ],
  providers: [MessageService],
  template: `
    <p-toast />

    <div class="profile-container">
      <!-- Header -->
      <div class="profile-header">
        <div class="header-content">
          <div class="header-icon">
            <i class="pi pi-user"></i>
          </div>
          <div>
            <h2>{{ 'PROFILE.TITLE' | translate }}</h2>
            <p>{{ 'PROFILE.SUBTITLE' | translate }}</p>
          </div>
        </div>
      </div>

      <!-- Loading -->
      @if (loading()) {
        <div class="loading-container">
          <p-progressSpinner strokeWidth="3" />
        </div>
      }

      <!-- Error -->
      @if (error() && !loading()) {
        <div class="error-container">
          <i class="pi pi-exclamation-triangle"></i>
          <p>{{ error() }}</p>
          <button pButton [label]="'COMMON.RETRY' | translate" icon="pi pi-refresh" (click)="loadProfile()" class="p-button-outlined"></button>
        </div>
      }

      <!-- Profile Content -->
      @if (user() && !loading()) {
        <div class="profile-grid">
          <!-- Left Column: Info Card -->
          <div class="profile-info-card">
            <div class="avatar-section">
              <div class="avatar">
                <span>{{ getInitials() }}</span>
              </div>
              <h3>{{ user()!.name }}</h3>
              <p class="email-text">{{ user()!.email }}</p>
              @if (user()!.is_active) {
                <span class="status-badge active">{{ 'COMMON.ACTIVE' | translate }}</span>
              } @else {
                <span class="status-badge inactive">{{ 'COMMON.INACTIVE' | translate }}</span>
              }
            </div>

            <div class="info-divider"></div>

            <div class="info-details">
              <div class="info-row">
                <span class="info-label"><i class="pi pi-building"></i> {{ 'PROFILE.COMPANY' | translate }}</span>
                <span class="info-value">{{ user()!.company?.name || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="info-label"><i class="pi pi-map-marker"></i> {{ 'PROFILE.BRANCH' | translate }}</span>
                <span class="info-value">{{ user()!.branch?.name || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="info-label"><i class="pi pi-shield"></i> {{ 'PROFILE.ROLES' | translate }}</span>
                <span class="info-value">{{ user()!.roles?.length ? user()!.roles.join(', ') : '-' }}</span>
              </div>
              <div class="info-row">
                <span class="info-label"><i class="pi pi-calendar"></i> {{ 'PROFILE.MEMBER_SINCE' | translate }}</span>
                <span class="info-value">{{ user()!.created_at | date:'mediumDate' }}</span>
              </div>
            </div>
          </div>

          <!-- Right Column: Edit Form -->
          <div class="profile-edit-card">
            <div class="card-header">
              <h3>
                <i class="pi pi-pencil"></i>
                @if (editMode()) {
                  {{ 'COMMON.EDIT' | translate }}
                } @else {
                  {{ 'PROFILE.TITLE' | translate }}
                }
              </h3>
              @if (!editMode() && !readOnly()) {
                <button pButton icon="pi pi-pencil" [label]="'COMMON.EDIT' | translate"
                  class="p-button-outlined p-button-sm" (click)="toggleEdit()"></button>
              }
            </div>

            <form [formGroup]="profileForm">
              <div class="form-grid">
                <!-- Name Arabic -->
                <div class="form-field">
                  <label for="name_ar">{{ 'PROFILE.NAME_AR' | translate }}</label>
                  <input pInputText id="name_ar" formControlName="name_ar"
                    [readonly]="!editMode()" [class.readonly-field]="!editMode()" />
                </div>

                <!-- Name English -->
                <div class="form-field">
                  <label for="name_en">{{ 'PROFILE.NAME_EN' | translate }}</label>
                  <input pInputText id="name_en" formControlName="name_en"
                    [readonly]="!editMode()" [class.readonly-field]="!editMode()" />
                </div>

                <!-- Email -->
                <div class="form-field">
                  <label for="email">{{ 'PROFILE.EMAIL' | translate }}</label>
                  <input pInputText id="email" formControlName="email" type="email"
                    [readonly]="!editMode()" [class.readonly-field]="!editMode()" />
                </div>

                <!-- Phone -->
                <div class="form-field">
                  <label for="phone">{{ 'PROFILE.PHONE' | translate }}</label>
                  <input pInputText id="phone" formControlName="phone"
                    [readonly]="!editMode()" [class.readonly-field]="!editMode()" />
                </div>

                <!-- Locale -->
                <div class="form-field">
                  <label for="locale">{{ 'PROFILE.LOCALE' | translate }}</label>
                  @if (editMode()) {
                    <p-select id="locale" formControlName="locale"
                      [options]="localeOptions" optionLabel="label" optionValue="value"
                      [placeholder]="'COMMON.SELECT' | translate" />
                  } @else {
                    <input pInputText [value]="getLocaleLabel()" readonly class="readonly-field" />
                  }
                </div>
              </div>

              <!-- Action Buttons -->
              @if (editMode()) {
                <div class="form-actions">
                  <button pButton type="button" [label]="'COMMON.CANCEL' | translate"
                    icon="pi pi-times" class="p-button-outlined p-button-secondary"
                    (click)="cancelEdit()"></button>
                  <button pButton type="button" [label]="'PROFILE.SAVE' | translate"
                    icon="pi pi-check" [loading]="saving()"
                    (click)="saveProfile()" [disabled]="profileForm.invalid || profileForm.pristine"></button>
                </div>
              }
            </form>
          </div>
        </div>
      }
    </div>
  `,
  styles: [`
    :host {
      display: block;
    }

    .profile-container {
      max-width: 1100px;
      margin: 0 auto;
      padding: 1.5rem;
    }

    .profile-header {
      margin-bottom: 2rem;
    }

    .header-content {
      display: flex;
      align-items: center;
      gap: 1rem;
    }

    .header-icon {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      background: linear-gradient(135deg, #1a237e, #283593);
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ffc107;
      font-size: 1.5rem;
    }

    .header-content h2 {
      margin: 0;
      font-size: 1.5rem;
      color: #1a237e;
    }

    .header-content p {
      margin: 0.25rem 0 0;
      color: #666;
      font-size: 0.9rem;
    }

    .loading-container {
      display: flex;
      justify-content: center;
      padding: 4rem;
    }

    .error-container {
      text-align: center;
      padding: 3rem;
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    }

    .error-container i {
      font-size: 2.5rem;
      color: #f44336;
      margin-bottom: 1rem;
    }

    .error-container p {
      color: #666;
      margin-bottom: 1rem;
    }

    .profile-grid {
      display: grid;
      grid-template-columns: 340px 1fr;
      gap: 1.5rem;
      align-items: start;
    }

    /* Left info card */
    .profile-info-card {
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
      overflow: hidden;
    }

    .avatar-section {
      padding: 2rem 1.5rem;
      text-align: center;
      background: linear-gradient(135deg, #1a237e 0%, #283593 100%);
      color: #fff;
    }

    .avatar {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: rgba(255, 193, 7, 0.2);
      border: 3px solid #ffc107;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto 1rem;
      font-size: 1.8rem;
      font-weight: 700;
      color: #ffc107;
    }

    .avatar-section h3 {
      margin: 0 0 0.25rem;
      font-size: 1.2rem;
    }

    .email-text {
      margin: 0 0 0.75rem;
      opacity: 0.8;
      font-size: 0.85rem;
    }

    .status-badge {
      display: inline-block;
      padding: 0.25rem 0.75rem;
      border-radius: 20px;
      font-size: 0.75rem;
      font-weight: 600;
    }

    .status-badge.active {
      background: rgba(76, 175, 80, 0.2);
      color: #81c784;
    }

    .status-badge.inactive {
      background: rgba(244, 67, 54, 0.2);
      color: #ef9a9a;
    }

    .info-divider {
      height: 1px;
      background: #e0e0e0;
    }

    .info-details {
      padding: 1.25rem 1.5rem;
    }

    .info-row {
      display: flex;
      flex-direction: column;
      gap: 0.25rem;
      padding: 0.75rem 0;
    }

    .info-row + .info-row {
      border-top: 1px solid #f0f0f0;
    }

    .info-label {
      font-size: 0.8rem;
      color: #888;
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }

    .info-label i {
      font-size: 0.85rem;
      color: #1a237e;
    }

    .info-value {
      font-size: 0.95rem;
      color: #333;
      font-weight: 500;
      padding-inline-start: 1.35rem;
    }

    /* Right edit card */
    .profile-edit-card {
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
      padding: 1.5rem 2rem;
    }

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 1.5rem;
      padding-bottom: 1rem;
      border-bottom: 2px solid #f0f0f0;
    }

    .card-header h3 {
      margin: 0;
      font-size: 1.1rem;
      color: #1a237e;
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }

    .card-header h3 i {
      color: #ffc107;
    }

    .form-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 1.25rem;
    }

    .form-field {
      display: flex;
      flex-direction: column;
      gap: 0.5rem;
    }

    .form-field label {
      font-size: 0.85rem;
      font-weight: 600;
      color: #555;
    }

    .form-field input,
    .form-field :host ::ng-deep .p-select {
      width: 100%;
    }

    .readonly-field {
      background: #f9f9f9 !important;
      color: #555 !important;
      cursor: default;
    }

    .form-actions {
      display: flex;
      justify-content: flex-end;
      gap: 0.75rem;
      margin-top: 2rem;
      padding-top: 1.25rem;
      border-top: 1px solid #f0f0f0;
    }

    /* Responsive */
    @media (max-width: 768px) {
      .profile-grid {
        grid-template-columns: 1fr;
      }

      .form-grid {
        grid-template-columns: 1fr;
      }

      .profile-container {
        padding: 1rem;
      }
    }

    /* PrimeNG overrides */
    :host ::ng-deep {
      .p-button {
        &:not(.p-button-outlined) {
          background: #1a237e;
          border-color: #1a237e;
          &:hover {
            background: #283593;
            border-color: #283593;
          }
        }
      }

      .p-inputtext:enabled:focus {
        border-color: #1a237e;
        box-shadow: 0 0 0 0.2rem rgba(26, 35, 126, 0.15);
      }

      .p-select:not(.p-disabled).p-focus {
        border-color: #1a237e;
        box-shadow: 0 0 0 0.2rem rgba(26, 35, 126, 0.15);
      }
    }
  `],
})
export class ProfileComponent implements OnInit {
  private fb = inject(FormBuilder);
  private http = inject(HttpClient);
  private messageService = inject(MessageService);
  private translate = inject(TranslateService);

  private apiUrl = environment.apiUrl;

  user = signal<User | null>(null);
  loading = signal(false);
  saving = signal(false);
  error = signal<string | null>(null);
  editMode = signal(false);
  readOnly = signal(false);

  profileForm!: FormGroup;

  localeOptions = [
    { label: 'العربية', value: 'ar' },
    { label: 'English', value: 'en' },
  ];

  ngOnInit(): void {
    this.initForm();
    this.loadProfile();
  }

  private initForm(): void {
    this.profileForm = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      phone: [''],
      locale: ['ar'],
    });
  }

  loadProfile(): void {
    this.loading.set(true);
    this.error.set(null);

    this.http.get<ApiResponse<User>>(`${this.apiUrl}/auth/me`).subscribe({
      next: (res) => {
        this.user.set(res.data);
        this.patchForm(res.data);
        this.loading.set(false);
      },
      error: (err) => {
        this.error.set(err.error?.message || 'Failed to load profile');
        this.loading.set(false);
      },
    });
  }

  private patchForm(user: User): void {
    this.profileForm.patchValue({
      name_ar: user.name_ar || '',
      name_en: user.name_en || '',
      email: user.email || '',
      phone: user.phone || '',
      locale: user.locale || 'ar',
    });
    this.profileForm.markAsPristine();
  }

  toggleEdit(): void {
    this.editMode.set(true);
  }

  cancelEdit(): void {
    this.editMode.set(false);
    if (this.user()) {
      this.patchForm(this.user()!);
    }
  }

  saveProfile(): void {
    if (this.profileForm.invalid) return;

    this.saving.set(true);
    const payload = this.profileForm.value;

    // Try PUT /api/auth/me first
    this.http.put<ApiResponse<User>>(`${this.apiUrl}/auth/me`, payload).subscribe({
      next: (res) => {
        this.handleSaveSuccess(res);
      },
      error: () => {
        // Fallback: try PUT /api/auth/profile
        this.http.put<ApiResponse<User>>(`${this.apiUrl}/auth/profile`, payload).subscribe({
          next: (res) => {
            this.handleSaveSuccess(res);
          },
          error: () => {
            // Both endpoints failed - switch to read-only
            this.saving.set(false);
            this.readOnly.set(true);
            this.editMode.set(false);
            this.messageService.add({
              severity: 'warn',
              summary: this.translate.instant('COMMON.ERROR'),
              detail: this.translate.instant('PROFILE.SAVE_ERROR'),
              life: 5000,
            });
          },
        });
      },
    });
  }

  private handleSaveSuccess(res: ApiResponse<User>): void {
    this.saving.set(false);
    this.editMode.set(false);
    if (res.data) {
      this.user.set(res.data);
      this.patchForm(res.data);
    }
    this.messageService.add({
      severity: 'success',
      summary: this.translate.instant('COMMON.SUCCESS'),
      detail: this.translate.instant('PROFILE.SAVE_SUCCESS'),
      life: 3000,
    });
  }

  getInitials(): string {
    const u = this.user();
    if (!u) return '?';
    const name = u.name_en || u.name || '';
    const parts = name.split(' ').filter(Boolean);
    if (parts.length >= 2) {
      return (parts[0][0] + parts[1][0]).toUpperCase();
    }
    return name.substring(0, 2).toUpperCase();
  }

  getLocaleLabel(): string {
    const val = this.profileForm.get('locale')?.value;
    const opt = this.localeOptions.find(o => o.value === val);
    return opt?.label || val || '-';
  }
}
