import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } 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 { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatDialogModule, MatDialog } from '@angular/material/dialog';
import { ApiService } from '../../../core/services/api.service';

@Component({
  selector: 'app-department-onboarding',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatCardModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatSnackBarModule,
    MatDialogModule,
  ],
  template: `
    <mat-card class="onboarding-card">
      <mat-card-header>
        <mat-card-title>
          <mat-icon class="title-icon">add_business</mat-icon>
          Onboard New Department
        </mat-card-title>
      </mat-card-header>

      <mat-card-content>
        <form [formGroup]="onboardingForm" (ngSubmit)="onSubmit()">
          <div class="form-grid">
            <mat-form-field appearance="outline" class="full-width">
              <mat-label>Department Code</mat-label>
              <input
                matInput
                formControlName="code"
                placeholder="e.g., POLICE_DEPT"
                [style.text-transform]="'uppercase'"
              />
              <mat-icon matPrefix>badge</mat-icon>
              <mat-hint>Uppercase letters and underscores only</mat-hint>
              <mat-error *ngIf="onboardingForm.get('code')?.hasError('required')">
                Department code is required
              </mat-error>
              <mat-error *ngIf="onboardingForm.get('code')?.hasError('pattern')">
                Use only uppercase letters and underscores
              </mat-error>
            </mat-form-field>

            <mat-form-field appearance="outline" class="full-width">
              <mat-label>Department Name</mat-label>
              <input matInput formControlName="name" placeholder="e.g., Police Department" />
              <mat-icon matPrefix>business</mat-icon>
              <mat-error *ngIf="onboardingForm.get('name')?.hasError('required')">
                Department name is required
              </mat-error>
            </mat-form-field>

            <mat-form-field appearance="outline" class="full-width">
              <mat-label>Contact Email</mat-label>
              <input matInput type="email" formControlName="contactEmail" placeholder="police@goa.gov.in" />
              <mat-icon matPrefix>email</mat-icon>
              <mat-error *ngIf="onboardingForm.get('contactEmail')?.hasError('required')">
                Contact email is required
              </mat-error>
              <mat-error *ngIf="onboardingForm.get('contactEmail')?.hasError('email')">
                Please enter a valid email
              </mat-error>
            </mat-form-field>

            <mat-form-field appearance="outline" class="full-width">
              <mat-label>Contact Phone</mat-label>
              <input matInput formControlName="contactPhone" placeholder="+91-832-6666666" />
              <mat-icon matPrefix>phone</mat-icon>
            </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-icon matPrefix>description</mat-icon>
            </mat-form-field>
          </div>

          <div class="info-box">
            <mat-icon>info</mat-icon>
            <div>
              <strong>Auto-generated on submission:</strong>
              <ul>
                <li>Blockchain wallet with encrypted private key</li>
                <li>API key pair for department authentication</li>
                <li>Webhook secret for secure callbacks</li>
              </ul>
            </div>
          </div>

          <div class="form-actions">
            <button mat-raised-button color="primary" type="submit" [disabled]="onboardingForm.invalid || loading">
              <mat-spinner *ngIf="loading" diameter="20" class="button-spinner"></mat-spinner>
              <mat-icon *ngIf="!loading">add_circle</mat-icon>
              <span *ngIf="!loading">Onboard Department</span>
            </button>
            <button mat-button type="button" (click)="onboardingForm.reset()" [disabled]="loading">
              <mat-icon>clear</mat-icon>
              Reset Form
            </button>
          </div>
        </form>
      </mat-card-content>
    </mat-card>
  `,
  styles: [
    `
      .onboarding-card {
        margin-bottom: 24px;
      }

      mat-card-header {
        margin-bottom: 16px;
      }

      mat-card-title {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 1.25rem;
      }

      .title-icon {
        color: #1976d2;
        font-size: 32px;
        width: 32px;
        height: 32px;
      }

      .form-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 16px;
      }

      @media (min-width: 768px) {
        .form-grid {
          grid-template-columns: 1fr 1fr;
        }

        .full-width {
          grid-column: span 2;
        }
      }

      .info-box {
        display: flex;
        gap: 12px;
        padding: 16px;
        background-color: #e3f2fd;
        border-radius: 8px;
        margin: 16px 0;

        mat-icon {
          color: #1976d2;
          font-size: 24px;
          width: 24px;
          height: 24px;
        }

        strong {
          color: #1565c0;
        }

        ul {
          margin: 8px 0 0;
          padding-left: 20px;
        }

        li {
          margin: 4px 0;
          font-size: 0.875rem;
        }
      }

      .form-actions {
        display: flex;
        gap: 12px;
        margin-top: 16px;

        button {
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }

      .button-spinner {
        display: inline-block;
      }
    `,
  ],
})
export class DepartmentOnboardingComponent {
  onboardingForm: FormGroup;
  loading = false;

  constructor(private fb: FormBuilder, private api: ApiService, private snackBar: MatSnackBar, private dialog: MatDialog) {
    this.onboardingForm = this.fb.group({
      code: ['', [Validators.required, Validators.pattern(/^[A-Z_]+$/)]],
      name: ['', Validators.required],
      contactEmail: ['', [Validators.required, Validators.email]],
      contactPhone: [''],
      description: [''],
    });
  }

  async onSubmit() {
    if (this.onboardingForm.invalid) {
      return;
    }

    this.loading = true;
    try {
      const formData = {
        ...this.onboardingForm.value,
        code: this.onboardingForm.value.code.toUpperCase(),
      };

      const response = await this.api.post<any>('/admin/departments', formData).toPromise();

      // Show success with credentials
      this.showCredentialsDialog(response);

      this.onboardingForm.reset();
      this.snackBar.open('Department onboarded successfully!', 'Close', {
        duration: 5000,
        panelClass: ['success-snackbar'],
      });
    } catch (error: any) {
      this.snackBar.open(error?.error?.message || 'Failed to onboard department', 'Close', {
        duration: 5000,
        panelClass: ['error-snackbar'],
      });
    } finally {
      this.loading = false;
    }
  }

  showCredentialsDialog(response: any) {
    const message = `
Department: ${response.department.name}
Wallet Address: ${response.department.walletAddress}

⚠️ SAVE THESE CREDENTIALS - They will not be shown again:

API Key: ${response.apiKey}
API Secret: ${response.apiSecret}
    `.trim();

    alert(message);
  }
}
