import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { DepartmentService } from '../services/department.service';
import { NotificationService } from '../../../core/services/notification.service';

@Component({
  selector: 'app-department-form',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    ReactiveFormsModule,
    MatCardModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatDialogModule,
    PageHeaderComponent,
  ],
  template: `
    <div class="page-container">
      <app-page-header
        [title]="isEditMode() ? 'Edit Department' : 'Create Department'"
        [subtitle]="isEditMode() ? 'Update department details' : 'Add a new government department'"
      >
        <button mat-button routerLink="/departments">
          <mat-icon>arrow_back</mat-icon>
          Back
        </button>
      </app-page-header>

      <mat-card class="form-card">
        <mat-card-content>
          @if (loading()) {
            <div class="loading-container">
              <mat-spinner diameter="48"></mat-spinner>
            </div>
          } @else {
            <form [formGroup]="form" (ngSubmit)="onSubmit()">
              <div class="form-grid">
                <mat-form-field appearance="outline">
                  <mat-label>Department Code</mat-label>
                  <input
                    matInput
                    formControlName="code"
                    placeholder="e.g., FIRE_DEPT"
                    [readonly]="isEditMode()"
                  />
                  @if (form.controls.code.hasError('required')) {
                    <mat-error>Code is required</mat-error>
                  }
                  @if (form.controls.code.hasError('pattern')) {
                    <mat-error>Use uppercase letters, numbers, and underscores only</mat-error>
                  }
                  <mat-hint>Unique identifier for the department</mat-hint>
                </mat-form-field>

                <mat-form-field appearance="outline">
                  <mat-label>Department Name</mat-label>
                  <input matInput formControlName="name" placeholder="Full department name" />
                  @if (form.controls.name.hasError('required')) {
                    <mat-error>Name is required</mat-error>
                  }
                </mat-form-field>

                <mat-form-field appearance="outline" class="full-width">
                  <mat-label>Description</mat-label>
                  <textarea
                    matInput
                    formControlName="description"
                    rows="3"
                    placeholder="Brief description of the department"
                  ></textarea>
                </mat-form-field>

                <mat-form-field appearance="outline">
                  <mat-label>Contact Email</mat-label>
                  <input
                    matInput
                    formControlName="contactEmail"
                    type="email"
                    placeholder="department@goa.gov.in"
                  />
                  @if (form.controls.contactEmail.hasError('email')) {
                    <mat-error>Enter a valid email address</mat-error>
                  }
                </mat-form-field>

                <mat-form-field appearance="outline">
                  <mat-label>Contact Phone</mat-label>
                  <input
                    matInput
                    formControlName="contactPhone"
                    type="tel"
                    placeholder="+91-XXX-XXXXXXX"
                  />
                </mat-form-field>

                <mat-form-field appearance="outline" class="full-width">
                  <mat-label>Webhook URL</mat-label>
                  <input
                    matInput
                    formControlName="webhookUrl"
                    placeholder="https://example.com/webhook"
                  />
                  @if (form.controls.webhookUrl.hasError('pattern')) {
                    <mat-error>Enter a valid URL</mat-error>
                  }
                  <mat-hint>URL to receive event notifications</mat-hint>
                </mat-form-field>
              </div>

              <div class="form-actions">
                <button mat-button type="button" routerLink="/departments">Cancel</button>
                <button
                  mat-raised-button
                  color="primary"
                  type="submit"
                  [disabled]="form.invalid || submitting()"
                >
                  @if (submitting()) {
                    <mat-spinner diameter="20"></mat-spinner>
                  } @else {
                    {{ isEditMode() ? 'Update' : 'Create' }}
                  }
                </button>
              </div>
            </form>
          }
        </mat-card-content>
      </mat-card>
    </div>
  `,
  styles: [
    `
      .form-card {
        max-width: 800px;
      }

      .loading-container {
        display: flex;
        justify-content: center;
        padding: 48px;
      }

      .form-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
      }

      .full-width {
        grid-column: 1 / -1;
      }

      .form-actions {
        display: flex;
        gap: 12px;
        justify-content: flex-end;
        margin-top: 24px;
        padding-top: 16px;
        border-top: 1px solid #eee;
      }
    `,
  ],
})
export class DepartmentFormComponent implements OnInit {
  private readonly fb = inject(FormBuilder);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly departmentService = inject(DepartmentService);
  private readonly notification = inject(NotificationService);
  private readonly dialog = inject(MatDialog);

  readonly loading = signal(false);
  readonly submitting = signal(false);
  readonly isEditMode = signal(false);
  private departmentId: string | null = null;

  readonly form = this.fb.nonNullable.group({
    code: ['', [Validators.required, Validators.pattern(/^[A-Z0-9_]+$/)]],
    name: ['', [Validators.required]],
    description: [''],
    contactEmail: ['', [Validators.email]],
    contactPhone: [''],
    webhookUrl: ['', [Validators.pattern(/^https?:\/\/.+/)]],
  });

  ngOnInit(): void {
    this.departmentId = this.route.snapshot.paramMap.get('id');
    if (this.departmentId) {
      this.isEditMode.set(true);
      this.loadDepartment();
    }
  }

  private loadDepartment(): void {
    if (!this.departmentId) return;

    this.loading.set(true);
    this.departmentService.getDepartment(this.departmentId).subscribe({
      next: (dept) => {
        this.form.patchValue({
          code: dept.code,
          name: dept.name,
          description: dept.description || '',
          contactEmail: dept.contactEmail || '',
          contactPhone: dept.contactPhone || '',
          webhookUrl: dept.webhookUrl || '',
        });
        this.loading.set(false);
      },
      error: () => {
        this.notification.error('Failed to load department');
        this.router.navigate(['/departments']);
      },
    });
  }

  onSubmit(): void {
    if (this.form.invalid) return;

    this.submitting.set(true);
    const values = this.form.getRawValue();

    if (this.isEditMode() && this.departmentId) {
      this.departmentService.updateDepartment(this.departmentId, values).subscribe({
        next: () => {
          this.notification.success('Department updated successfully');
          this.router.navigate(['/departments', this.departmentId]);
        },
        error: () => {
          this.submitting.set(false);
        },
      });
    } else {
      this.departmentService.createDepartment(values).subscribe({
        next: (result) => {
          this.notification.success('Department created successfully');
          // Show credentials dialog
          alert(
            `Department created!\n\nAPI Key: ${result.apiKey}\nAPI Secret: ${result.apiSecret}\n\nPlease save these credentials securely.`
          );
          this.router.navigate(['/departments', result.department.id]);
        },
        error: () => {
          this.submitting.set(false);
        },
      });
    }
  }
}
