import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { InputTextModule } from 'primeng/inputtext';
import { PasswordModule } from 'primeng/password';
import { ButtonModule } from 'primeng/button';
import { MessageModule } from 'primeng/message';
import { ToastModule } from 'primeng/toast';
import { MessageService } from 'primeng/api';
import { AuthService } from '../../../core/services/auth.service';
import { LanguageService } from '../../../core/services/language.service';

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [
    CommonModule, ReactiveFormsModule, RouterModule, TranslateModule,
    InputTextModule, PasswordModule, ButtonModule, MessageModule, ToastModule,
  ],
  providers: [MessageService],
  template: `
    <p-toast />
    <div class="register-container star-field">
      <div class="register-card">
        <div class="register-header">
          <div class="logo-area">
            <img src="assets/moon-crescent.svg" alt="Moon" width="48" height="48" />
          </div>
          <h1>{{ 'REGISTER.TITLE' | translate }}</h1>
          <p>{{ 'REGISTER.SUBTITLE' | translate }}</p>
        </div>

        @if (errorMessage) {
          <p-message severity="error" [text]="errorMessage" [style]="{'width':'100%','margin-bottom':'1rem'}" />
        }

        <form [formGroup]="registerForm" (ngSubmit)="onSubmit()" class="register-form">
          <div class="form-field">
            <label for="name">{{ 'REGISTER.NAME' | translate }}</label>
            <input pInputText id="name" formControlName="name" [placeholder]="'REGISTER.NAME_PLACEHOLDER' | translate" />
            @if (registerForm.get('name')?.touched && registerForm.get('name')?.hasError('required')) {
              <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
            }
          </div>

          <div class="form-field">
            <label for="email">{{ 'REGISTER.EMAIL' | translate }}</label>
            <input pInputText id="email" formControlName="email" type="email" [placeholder]="'REGISTER.EMAIL_PLACEHOLDER' | translate" />
            @if (registerForm.get('email')?.touched && registerForm.get('email')?.hasError('required')) {
              <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
            }
            @if (registerForm.get('email')?.touched && registerForm.get('email')?.hasError('email')) {
              <small class="p-error">{{ 'REGISTER.INVALID_EMAIL' | translate }}</small>
            }
          </div>

          <div class="form-field">
            <label for="password">{{ 'REGISTER.PASSWORD' | translate }}</label>
            <p-password id="password" formControlName="password" [toggleMask]="true" [feedback]="true" [style]="{'width':'100%'}" [inputStyle]="{'width':'100%'}" />
            @if (registerForm.get('password')?.touched && registerForm.get('password')?.hasError('required')) {
              <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
            }
            @if (registerForm.get('password')?.touched && registerForm.get('password')?.hasError('minlength')) {
              <small class="p-error">{{ 'REGISTER.PASSWORD_MIN' | translate }}</small>
            }
          </div>

          <div class="form-field">
            <label for="password_confirmation">{{ 'REGISTER.CONFIRM_PASSWORD' | translate }}</label>
            <p-password id="password_confirmation" formControlName="password_confirmation" [toggleMask]="true" [feedback]="false" [style]="{'width':'100%'}" [inputStyle]="{'width':'100%'}" />
            @if (registerForm.get('password_confirmation')?.touched && registerForm.get('password_confirmation')?.hasError('required')) {
              <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
            }
          </div>

          <p-button
            type="submit"
            [label]="'REGISTER.SUBMIT' | translate"
            icon="pi pi-user-plus"
            [loading]="loading"
            [style]="{'width':'100%'}"
          />
        </form>

        <div class="register-footer">
          <span>{{ 'REGISTER.HAVE_ACCOUNT' | translate }}</span>
          <a routerLink="/login">{{ 'REGISTER.LOGIN_LINK' | translate }}</a>
        </div>

        <button class="lang-toggle" (click)="toggleLang()">
          {{ langService.currentLang() === 'ar' ? 'English' : 'العربية' }}
        </button>
      </div>
    </div>
  `,
  styles: [`
    .register-container {
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #040710;
      padding: 2rem;
      position: relative;
    }
    .register-card {
      background: rgba(17, 24, 39, 0.6);
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
      border: 1px solid rgba(255, 255, 255, 0.08);
      border-radius: 16px;
      padding: 2.5rem;
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
      max-width: 480px;
      width: 100%;
      position: relative;
      z-index: 1;
    }
    .register-header {
      text-align: center;
      margin-bottom: 2rem;
      color: #f1f5f9;
    }
    .logo-area {
      margin-bottom: 1rem;
      img {
        filter: drop-shadow(0 0 12px rgba(255, 193, 7, 0.4));
      }
    }
    .register-header h1 {
      color: #f1f5f9;
      font-size: 1.5rem;
      margin: 0 0 0.5rem;
    }
    .register-header p {
      color: #94a3b8;
      font-size: 0.875rem;
      margin: 0;
    }
    .register-form {
      display: flex;
      flex-direction: column;
      gap: 1.25rem;
    }
    .form-field {
      display: flex;
      flex-direction: column;
      gap: 0.5rem;
      label { font-size: 0.875rem; color: #cbd5e1; }
    }
    .form-field input,
    :host ::ng-deep .p-password { width: 100%; }
    :host ::ng-deep .p-inputtext,
    :host ::ng-deep .p-password-input {
      background: rgba(8, 12, 26, 0.6) !important;
      border: 1px solid rgba(255, 255, 255, 0.1) !important;
      color: #f1f5f9 !important;
    }
    :host ::ng-deep .p-inputtext:focus,
    :host ::ng-deep .p-password-input:focus {
      border-color: rgba(255, 193, 7, 0.4) !important;
      box-shadow: 0 0 0 2px rgba(255, 193, 7, 0.15) !important;
    }
    :host ::ng-deep .p-button {
      background: linear-gradient(135deg, #ffc107, #ffab00) !important;
      border: none !important;
      color: #1a1a2e !important;
      font-weight: 600 !important;
      box-shadow: 0 4px 20px rgba(255, 193, 7, 0.3) !important;
      transition: box-shadow 0.2s, transform 0.2s !important;
    }
    :host ::ng-deep .p-button:hover {
      box-shadow: 0 6px 28px rgba(255, 193, 7, 0.45) !important;
      transform: translateY(-1px) !important;
    }
    .register-footer {
      text-align: center;
      margin-top: 1.5rem;
      font-size: 0.875rem;
      color: #94a3b8;
      a {
        color: var(--color-accent, #ffc107);
        text-decoration: none;
        margin-inline-start: 0.25rem;
        &:hover { text-decoration: underline; }
      }
    }
    .lang-toggle {
      display: block;
      margin: 1rem auto 0;
      background: none;
      border: 1px solid rgba(255, 255, 255, 0.15);
      color: #94a3b8;
      padding: 0.375rem 1rem;
      border-radius: 0.5rem;
      cursor: pointer;
      font-size: 0.8rem;
      transition: border-color 0.2s, color 0.2s;
      &:hover { border-color: #ffc107; color: #ffc107; }
    }
    @media (max-width: 768px) {
      .register-container { padding: 1rem; }
      .register-card { padding: 1.5rem; border-radius: 12px; }
    }
    @media (max-width: 480px) {
      .register-card { padding: 1rem; }
    }
  `],
})
export class RegisterComponent {
  private fb = inject(FormBuilder);
  private authService = inject(AuthService);
  private router = inject(Router);
  private messageService = inject(MessageService);
  langService = inject(LanguageService);

  registerForm: FormGroup = this.fb.group({
    name: ['', Validators.required],
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(6)]],
    password_confirmation: ['', Validators.required],
  });

  loading = false;
  errorMessage = '';

  onSubmit(): void {
    if (this.registerForm.valid) {
      if (this.registerForm.value.password !== this.registerForm.value.password_confirmation) {
        this.errorMessage = 'Passwords do not match';
        return;
      }
      this.loading = true;
      this.errorMessage = '';
      this.authService.register(this.registerForm.value).subscribe({
        next: (response) => {
          this.loading = false;
          this.authService.setToken(response.token);
          this.router.navigate(['/dashboard']);
        },
        error: (err) => {
          this.loading = false;
          if (err.status === 422 && err.error?.errors) {
            const errors = err.error.errors;
            this.errorMessage = Object.values(errors).flat().join('. ');
          } else {
            this.errorMessage = err.error?.message || 'Registration failed';
          }
        },
      });
    } else {
      this.registerForm.markAllAsTouched();
    }
  }

  toggleLang(): void {
    this.langService.toggleLang();
  }
}
