import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterModule } from '@angular/router';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatCardModule } from '@angular/material/card';
import { MatStepperModule } from '@angular/material/stepper';
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 { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { RequestService } from '../services/request.service';
import { AuthService } from '../../../core/services/auth.service';
import { NotificationService } from '../../../core/services/notification.service';
import { ApiService } from '../../../core/services/api.service';
import { RequestType, WorkflowResponseDto } from '../../../api/models';
import {
  INPUT_LIMITS,
  noScriptValidator,
  noNullBytesValidator,
  notOnlyWhitespaceValidator,
  phoneValidator,
  normalizeWhitespace,
} from '../../../shared/utils/form-validators';
import { createSubmitDebounce } from '../../../shared/utils/form-utils';

@Component({
  selector: 'app-request-create',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    ReactiveFormsModule,
    MatCardModule,
    MatStepperModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    PageHeaderComponent,
  ],
  templateUrl: './request-create.component.html',
  styles: [
    `
      .form-card {
        max-width: 900px;
        margin: 0 auto;
        border-radius: 20px !important;
        overflow: hidden;
      }

      .form-header {
        background: linear-gradient(135deg, var(--dbim-blue-dark) 0%, var(--dbim-blue-mid) 100%);
        padding: 32px;
        color: white;
        text-align: center;

        .header-icon {
          width: 64px;
          height: 64px;
          margin: 0 auto 16px;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 16px;
          display: flex;
          align-items: center;
          justify-content: center;

          mat-icon {
            font-size: 32px;
            width: 32px;
            height: 32px;
          }
        }

        h2 {
          margin: 0 0 8px;
          font-size: 24px;
          font-weight: 600;
        }

        p {
          margin: 0;
          opacity: 0.9;
          font-size: 14px;
        }
      }

      .form-content {
        padding: 32px;
      }

      .form-row {
        display: flex;
        gap: 16px;
        margin-bottom: 16px;

        mat-form-field {
          flex: 1;
        }
      }

      .form-actions {
        display: flex;
        gap: 12px;
        justify-content: space-between;
        align-items: center;
        margin-top: 32px;
        padding-top: 24px;
        border-top: 1px solid var(--dbim-linen);

        .actions-left {
          display: flex;
          gap: 12px;
        }

        .actions-right {
          display: flex;
          gap: 12px;
        }
      }

      .step-content {
        padding: 32px 0;
        min-height: 300px;
      }

      .step-header {
        margin-bottom: 24px;

        h3 {
          font-size: 18px;
          font-weight: 600;
          color: var(--dbim-brown);
          margin: 0 0 8px;
        }

        p {
          font-size: 14px;
          color: var(--dbim-grey-2);
          margin: 0;
        }
      }

      .metadata-fields {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
      }

      /* Workflow selection cards */
      .workflow-selection {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 16px;
        margin-top: 16px;
      }

      .workflow-option {
        padding: 20px;
        border: 2px solid var(--dbim-linen);
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          border-color: var(--dbim-blue-light);
          background: var(--dbim-blue-subtle);
        }

        &.selected {
          border-color: var(--dbim-blue-mid);
          background: var(--dbim-blue-subtle);
          box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1);
        }

        .workflow-name {
          font-weight: 600;
          color: var(--dbim-brown);
          margin-bottom: 4px;
        }

        .workflow-desc {
          font-size: 13px;
          color: var(--dbim-grey-2);
        }
      }

      /* Request type cards */
      .type-selection {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 12px;
        margin-bottom: 24px;
      }

      .type-option {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px 16px;
        border: 2px solid var(--dbim-linen);
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.2s ease;
        text-align: center;

        &:hover {
          border-color: var(--dbim-blue-light);
          background: rgba(37, 99, 235, 0.02);
        }

        &.selected {
          border-color: var(--dbim-blue-mid);
          background: var(--dbim-blue-subtle);
        }

        .type-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          background: var(--dbim-linen);
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 12px;

          mat-icon {
            font-size: 24px;
            width: 24px;
            height: 24px;
            color: var(--dbim-grey-3);
          }
        }

        &.selected .type-icon {
          background: linear-gradient(135deg, var(--dbim-blue-dark) 0%, var(--dbim-blue-mid) 100%);

          mat-icon {
            color: white;
          }
        }

        .type-label {
          font-size: 13px;
          font-weight: 500;
          color: var(--dbim-brown);
        }
      }

      /* Progress indicator */
      .step-progress {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        margin-bottom: 32px;

        .progress-step {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          font-weight: 600;
          background: var(--dbim-linen);
          color: var(--dbim-grey-2);

          &.active {
            background: var(--dbim-blue-mid);
            color: white;
          }

          &.completed {
            background: var(--dbim-success);
            color: white;
          }
        }

        .progress-line {
          width: 60px;
          height: 3px;
          background: var(--dbim-linen);
          border-radius: 2px;

          &.active {
            background: linear-gradient(90deg, var(--dbim-success) 0%, var(--dbim-blue-mid) 100%);
          }
        }
      }

      /* Form field hints */
      .field-group {
        margin-bottom: 8px;

        .field-label {
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 13px;
          font-weight: 500;
          color: var(--dbim-grey-3);
          margin-bottom: 8px;

          mat-icon {
            font-size: 16px;
            width: 16px;
            height: 16px;
          }
        }
      }

      /* Submit button animation */
      .submit-btn {
        min-width: 160px;
        height: 48px;
        font-size: 15px;

        mat-spinner {
          margin-right: 8px;
        }
      }
    `,
  ],
})
export class RequestCreateComponent implements OnInit {
  private readonly fb = inject(FormBuilder);
  private readonly router = inject(Router);
  private readonly requestService = inject(RequestService);
  private readonly authService = inject(AuthService);
  private readonly notification = inject(NotificationService);
  private readonly api = inject(ApiService);

  /** Debounce handler to prevent double-click submissions */
  private readonly submitDebounce = createSubmitDebounce(500);

  readonly loading = signal(false);
  readonly submitting = signal(false);
  readonly workflows = signal<WorkflowResponseDto[]>([]);

  /** Input limits exposed for template binding */
  readonly limits = INPUT_LIMITS;

  readonly requestTypes: { value: RequestType; label: string }[] = [
    { value: 'NEW_LICENSE', label: 'New License' },
    { value: 'RENEWAL', label: 'License Renewal' },
    { value: 'AMENDMENT', label: 'License Amendment' },
    { value: 'MODIFICATION', label: 'License Modification' },
    { value: 'CANCELLATION', label: 'License Cancellation' },
  ];

  readonly basicForm = this.fb.nonNullable.group({
    requestType: ['NEW_LICENSE' as RequestType, [Validators.required]],
    workflowId: ['', [Validators.required]],
  });

  readonly metadataForm = this.fb.nonNullable.group({
    businessName: ['', [
      Validators.required,
      Validators.minLength(INPUT_LIMITS.NAME_MIN),
      Validators.maxLength(INPUT_LIMITS.NAME_MAX),
      noScriptValidator(),
      noNullBytesValidator(),
      notOnlyWhitespaceValidator(),
    ]],
    businessAddress: ['', [
      Validators.required,
      Validators.maxLength(INPUT_LIMITS.ADDRESS_MAX),
      noScriptValidator(),
      noNullBytesValidator(),
      notOnlyWhitespaceValidator(),
    ]],
    ownerName: ['', [
      Validators.required,
      Validators.minLength(INPUT_LIMITS.NAME_MIN),
      Validators.maxLength(INPUT_LIMITS.NAME_MAX),
      noScriptValidator(),
      noNullBytesValidator(),
      notOnlyWhitespaceValidator(),
    ]],
    ownerPhone: ['', [
      Validators.required,
      Validators.maxLength(INPUT_LIMITS.PHONE_MAX),
      phoneValidator(),
    ]],
    ownerEmail: ['', [
      Validators.email,
      Validators.maxLength(INPUT_LIMITS.EMAIL_MAX),
    ]],
    description: ['', [
      Validators.maxLength(INPUT_LIMITS.DESCRIPTION_MAX),
      noScriptValidator(),
      noNullBytesValidator(),
    ]],
  });

  ngOnInit(): void {
    this.loadWorkflows();
  }

  private loadWorkflows(): void {
    this.loading.set(true);
    this.api.get<{ data: WorkflowResponseDto[] }>('/workflows', { isActive: true }).subscribe({
      next: (response) => {
        const data = Array.isArray(response) ? response : response.data || [];
        this.workflows.set(data);
        this.loading.set(false);
      },
      error: () => {
        this.loading.set(false);
      },
    });
  }

  getTypeIcon(type: string): string {
    switch (type) {
      case 'NEW_LICENSE':
        return 'add_circle';
      case 'RENEWAL':
        return 'autorenew';
      case 'AMENDMENT':
        return 'edit_note';
      case 'MODIFICATION':
        return 'tune';
      case 'CANCELLATION':
        return 'cancel';
      default:
        return 'description';
    }
  }

  onSubmit(): void {
    // Debounce to prevent double-click submissions
    this.submitDebounce(() => this.performSubmit());
  }

  private performSubmit(): void {
    // Prevent submission if already in progress
    if (this.submitting()) {
      return;
    }

    if (this.basicForm.invalid || this.metadataForm.invalid) {
      this.basicForm.markAllAsTouched();
      this.metadataForm.markAllAsTouched();
      return;
    }

    const user = this.authService.getCurrentUser();
    if (!user) {
      this.notification.error('Please login to create a request');
      return;
    }

    this.submitting.set(true);
    const basic = this.basicForm.getRawValue();
    const rawMetadata = this.metadataForm.getRawValue();

    // Normalize whitespace in text fields
    const metadata = {
      businessName: normalizeWhitespace(rawMetadata.businessName),
      businessAddress: normalizeWhitespace(rawMetadata.businessAddress),
      ownerName: normalizeWhitespace(rawMetadata.ownerName),
      ownerPhone: rawMetadata.ownerPhone.trim(),
      ownerEmail: rawMetadata.ownerEmail.trim().toLowerCase(),
      description: normalizeWhitespace(rawMetadata.description),
    };

    this.requestService
      .createRequest({
        applicantName: metadata.ownerName,
        applicantPhone: metadata.ownerPhone,
        businessName: metadata.businessName,
        requestType: basic.requestType,
        workflowId: basic.workflowId,
        metadata: {
          businessAddress: metadata.businessAddress,
          ownerEmail: metadata.ownerEmail,
          description: metadata.description,
        },
      })
      .subscribe({
        next: (result) => {
          this.notification.success('Request created successfully');
          this.router.navigate(['/requests', result.id]);
        },
        error: (err) => {
          this.submitting.set(false);
          // Allow user to retry after error
          this.notification.error(err?.error?.message || 'Failed to create request. Please try again.');
        },
      });
  }
}
