import { Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { ApprovalService } from '../services/approval.service';
import { NotificationService } from '../../../core/services/notification.service';
import { ApprovalResponseDto, RejectionReason, DocumentType } from '../../../api/models';

export interface ApprovalActionDialogData {
  approval: ApprovalResponseDto;
  action: 'approve' | 'reject' | 'changes';
}

@Component({
  selector: 'app-approval-action',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatProgressSpinnerModule,
  ],
  template: `
    <h2 mat-dialog-title>{{ dialogTitle }}</h2>
    <mat-dialog-content>
      <form [formGroup]="form" class="action-form">
        <mat-form-field appearance="outline">
          <mat-label>Remarks</mat-label>
          <textarea
            matInput
            formControlName="remarks"
            rows="4"
            [placeholder]="remarksPlaceholder"
          ></textarea>
          @if (form.controls.remarks.hasError('required')) {
            <mat-error>Remarks are required</mat-error>
          }
          @if (form.controls.remarks.hasError('minlength')) {
            <mat-error>Remarks must be at least 10 characters</mat-error>
          }
        </mat-form-field>

        @if (data.action === 'reject') {
          <mat-form-field appearance="outline">
            <mat-label>Rejection Reason</mat-label>
            <mat-select formControlName="rejectionReason">
              @for (reason of rejectionReasons; track reason.value) {
                <mat-option [value]="reason.value">{{ reason.label }}</mat-option>
              }
            </mat-select>
            @if (form.controls.rejectionReason.hasError('required')) {
              <mat-error>Please select a rejection reason</mat-error>
            }
          </mat-form-field>
        }

        @if (data.action === 'changes') {
          <mat-form-field appearance="outline">
            <mat-label>Required Documents</mat-label>
            <mat-select formControlName="requiredDocuments" multiple>
              @for (docType of documentTypes; track docType.value) {
                <mat-option [value]="docType.value">{{ docType.label }}</mat-option>
              }
            </mat-select>
            <mat-hint>Select documents the applicant needs to provide</mat-hint>
          </mat-form-field>
        }
      </form>
    </mat-dialog-content>
    <mat-dialog-actions align="end">
      <button mat-button (click)="onCancel()" [disabled]="submitting()">Cancel</button>
      <button
        mat-raised-button
        [color]="actionColor"
        (click)="onSubmit()"
        [disabled]="form.invalid || submitting()"
      >
        @if (submitting()) {
          <mat-spinner diameter="20"></mat-spinner>
        } @else {
          {{ actionLabel }}
        }
      </button>
    </mat-dialog-actions>
  `,
  styles: [
    `
      .action-form {
        display: flex;
        flex-direction: column;
        gap: 16px;
        min-width: 400px;
      }
    `,
  ],
})
export class ApprovalActionComponent {
  private readonly fb = inject(FormBuilder);
  private readonly approvalService = inject(ApprovalService);
  private readonly notification = inject(NotificationService);
  private readonly dialogRef = inject(MatDialogRef<ApprovalActionComponent>);
  readonly data: ApprovalActionDialogData = inject(MAT_DIALOG_DATA);

  readonly submitting = signal(false);

  readonly rejectionReasons: { value: RejectionReason; label: string }[] = [
    { value: 'DOCUMENTATION_INCOMPLETE', label: 'Documentation Incomplete' },
    { value: 'INCOMPLETE_DOCUMENTS', label: 'Incomplete Documents' },
    { value: 'ELIGIBILITY_CRITERIA_NOT_MET', label: 'Eligibility Criteria Not Met' },
    { value: 'INCOMPLETE_INFORMATION', label: 'Incomplete Information' },
    { value: 'POLICY_VIOLATION', label: 'Policy Violation' },
    { value: 'FRAUD_SUSPECTED', label: 'Fraud Suspected' },
    { value: 'OTHER', label: 'Other' },
  ];

  readonly documentTypes: { value: DocumentType; label: string }[] = [
    { value: 'FIRE_SAFETY_CERTIFICATE', label: 'Fire Safety Certificate' },
    { value: 'BUILDING_PLAN', label: 'Building Plan' },
    { value: 'PROPERTY_OWNERSHIP', label: 'Property Ownership' },
    { value: 'INSPECTION_REPORT', label: 'Inspection Report' },
    { value: 'POLLUTION_CERTIFICATE', label: 'Pollution Certificate' },
    { value: 'ELECTRICAL_SAFETY_CERTIFICATE', label: 'Electrical Safety' },
    { value: 'IDENTITY_PROOF', label: 'Identity Proof' },
    { value: 'ADDRESS_PROOF', label: 'Address Proof' },
  ];

  readonly form = this.fb.nonNullable.group({
    remarks: ['', [Validators.required, Validators.minLength(10)]],
    rejectionReason: ['' as RejectionReason],
    requiredDocuments: [[] as string[]],
  });

  get dialogTitle(): string {
    switch (this.data.action) {
      case 'approve':
        return 'Approve Request';
      case 'reject':
        return 'Reject Request';
      case 'changes':
        return 'Request Changes';
    }
  }

  get actionLabel(): string {
    switch (this.data.action) {
      case 'approve':
        return 'Approve';
      case 'reject':
        return 'Reject';
      case 'changes':
        return 'Request Changes';
    }
  }

  get actionColor(): 'primary' | 'warn' {
    return this.data.action === 'reject' ? 'warn' : 'primary';
  }

  get remarksPlaceholder(): string {
    switch (this.data.action) {
      case 'approve':
        return 'Enter your approval remarks...';
      case 'reject':
        return 'Explain why this request is being rejected...';
      case 'changes':
        return 'Explain what changes are required...';
    }
  }

  constructor() {
    if (this.data.action === 'reject') {
      this.form.controls.rejectionReason.addValidators(Validators.required);
    }
  }

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

    this.submitting.set(true);
    const { remarks, rejectionReason, requiredDocuments } = this.form.getRawValue();
    const requestId = this.data.approval.requestId;

    let action$;
    switch (this.data.action) {
      case 'approve':
        action$ = this.approvalService.approve(requestId, { remarks });
        break;
      case 'reject':
        action$ = this.approvalService.reject(requestId, { remarks, rejectionReason });
        break;
      case 'changes':
        action$ = this.approvalService.requestChanges(requestId, { remarks, requiredDocuments });
        break;
    }

    action$.subscribe({
      next: () => {
        this.notification.success(
          this.data.action === 'approve'
            ? 'Request approved successfully'
            : this.data.action === 'reject'
            ? 'Request rejected'
            : 'Changes requested'
        );
        this.dialogRef.close(true);
      },
      error: () => {
        this.submitting.set(false);
      },
    });
  }

  onCancel(): void {
    this.dialogRef.close();
  }
}
