import { Component, forwardRef, Input, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core';
import { UploadService } from './UploadService';
import { CommonModule } from '@angular/common';
import {
  ControlValueAccessor,
  FormGroup,
  FormsModule,
  NG_VALUE_ACCESSOR,
} from '@angular/forms';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-upload-input',
  template:`
  <div class="upload-input">
  <input
    type="file"
    #file
    (change)="onFileChange(file.files)"
    accept="image/*"
    style="display: none"
  />

  <input
    type="text"
    *ngIf="!value"
    (click)="file.click()"
    class="pointer"
    placeholder="Click here to upload"
    readonly
  />
  <img
    *ngIf="value"
    [src]="value"
    [style.width.rem]="size"
    alt="Uploaded Image"
    class="uploaded-image pointer"
    title="Click to upload"
    (click)="file.click()"
  />
  <div class="image-actions" style="width: 100%; display: flex">
    <a (click)="view = !view"><i class="bi bi-eye"></i> View</a>
  </div>
  <div (click)="closeModal($event)" *ngIf="view && value" class="image-view">
    <img
    [src]="value"
    [style.width.%]="40"
    id="image-view"
    alt="Uploaded Image"
    class="uploaded-image pointer"
    title="Click to upload"
    (click)="file.click()"
  />
  <input type="text" class="form-control" [(ngModel)]="value">
  </div>
</div>

  `,
  styles: [
`
img {
  margin-top: 1rem;
  border-radius: 6px;
}

.image-actions {
  margin-bottom: 0.5rem;
  a {
    font-size: 0.7rem;
    padding: 3px 4px;
    color: rgb(60, 99, 255);
  }
}

.image-view {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 1000;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  gap: 2rem;
  input {
    max-width: 800px;
    font-size: 0.7rem;
    font-weight: 500;
    padding: 1rem;
    background: #383838;
    color: white;
  }
}

.upload-input{
  background: rgba(0, 0, 0, 0.119);
  width: fit-content;
  padding: 10px;
  margin: 10px 0;
  border-radius: 10px;
  border: 1px solid #4c4c4c;
}
`

  ],
  imports: [CommonModule, FormsModule],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => UploadInputComponent),
      multi: true,
    },
    UploadService,
  ],
})
export class UploadInputComponent implements ControlValueAccessor, OnInit, OnDestroy {
  @Input({ required: true }) formGroup!: FormGroup;
  @Input({ required: true }) formControlName!: string;
  @Input() imageKey = '';
  @Input() size = '10';
  @Input() parentItem: any = {};
  value = '';
  view = false;
  private subscription?: Subscription;

  constructor(
    private uploadService: UploadService,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit() {
    // Listen to form control value changes
    if (this.formGroup && this.formControlName) {
      const control = this.formGroup.get(this.formControlName);
      if (control) {
        // Initialize with current value
        this.value = control.value || '';

        // Subscribe to value changes
        this.subscription = control.valueChanges.subscribe((newValue: string) => {
          this.value = newValue || '';
          this.cdr.detectChanges();
        });
      }
    }
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }

  onFileChange(files: FileList | null) {
    this.uploadService.onUpload(
      files,
      {}, // Empty object since we don't need parentItem anymore
      '', // Empty imageKey since we're using reactive forms
      (url: string) => {
        if (this.formGroup && this.formControlName) {
          // Update the form control value (this will trigger valueChanges subscription)
          this.formGroup.get(this.formControlName)?.setValue(url);

          // Call onChange if it exists (for ControlValueAccessor)
          if (this.onChange) {
            this.onChange(url);
          }
        }
      }
    );
  }
  closeModal($event: MouseEvent) {
    if ($event.target === document.querySelector('.image-view'))
      this.view = false;
  }

  // Required for ControlValueAccessor
  onChange = (_: any) => {};
  onTouched = () => {};

  writeValue(value: string): void {
    this.value = value;
    this.parentItem[this.imageKey] = value;
    // Trigger change detection when value is written
    this.cdr.detectChanges();
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}
