import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { CheckListItemDto } from '../../models/disbursement.model';

export interface ReceiptSignResult { signature: Blob; signedName: string; }

@Component({
  selector: 'app-receipt-sign-dialog',
  standalone: true,
  imports: [CommonModule, FormsModule, DialogsModule, ButtonsModule, InputsModule],
  templateUrl: './receipt-sign-dialog.component.html',
})
export class ReceiptSignDialogComponent implements AfterViewInit {
  @Input() check!: CheckListItemDto;
  @Output() save = new EventEmitter<ReceiptSignResult>();
  @Output() cancel = new EventEmitter<void>();

  @ViewChild('pad', { static: false }) padRef!: ElementRef<HTMLCanvasElement>;

  signedName = '';
  hasInk = false;
  submitting = false;

  private ctx!: CanvasRenderingContext2D;
  private drawing = false;

  ngAfterViewInit(): void {
    const canvas = this.padRef.nativeElement;
    this.signedName = this.check.payeeName || '';
    this.ctx = canvas.getContext('2d')!;
    this.ctx.fillStyle = '#ffffff';
    this.ctx.fillRect(0, 0, canvas.width, canvas.height);
    this.ctx.strokeStyle = '#111827';
    this.ctx.lineWidth = 2;
    this.ctx.lineCap = 'round';
    this.ctx.lineJoin = 'round';
  }

  private point(e: PointerEvent): { x: number; y: number } {
    const rect = this.padRef.nativeElement.getBoundingClientRect();
    return {
      x: (e.clientX - rect.left) * (this.padRef.nativeElement.width / rect.width),
      y: (e.clientY - rect.top) * (this.padRef.nativeElement.height / rect.height),
    };
  }

  onDown(e: PointerEvent): void {
    e.preventDefault();
    this.drawing = true;
    const p = this.point(e);
    this.ctx.beginPath();
    this.ctx.moveTo(p.x, p.y);
    this.padRef.nativeElement.setPointerCapture(e.pointerId);
  }

  onMove(e: PointerEvent): void {
    if (!this.drawing) return;
    const p = this.point(e);
    this.ctx.lineTo(p.x, p.y);
    this.ctx.stroke();
    this.hasInk = true;
  }

  onUp(): void { this.drawing = false; }

  clear(): void {
    const canvas = this.padRef.nativeElement;
    this.ctx.fillStyle = '#ffffff';
    this.ctx.fillRect(0, 0, canvas.width, canvas.height);
    this.hasInk = false;
  }

  confirm(): void {
    if (!this.hasInk || !this.signedName.trim() || this.submitting) return;
    this.submitting = true;
    this.padRef.nativeElement.toBlob(blob => {
      if (!blob) { this.submitting = false; return; }
      this.save.emit({ signature: blob, signedName: this.signedName.trim() });
    }, 'image/png');
  }

  onClose(): void { this.cancel.emit(); }
}
