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',
  standalone: true,
  imports: [CommonModule, FormsModule],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => UploadInputComponent),
      multi: true,
    },
    UploadService,
  ],
  template: `
  <div class="flex flex-col items-start gap-2 p-4 border border-gray-300 rounded-xl bg-gray-50 w-fit">

    <!-- Hidden File Input -->
    <input
      type="file"
      #file
      (change)="onFileChange(file.files)"
      accept="image/*"
      class="hidden"
    />

    <!-- Upload Placeholder -->
    @if (!value) {
      <button
        type="button"
        class="px-4 py-2 text-sm text-blue-600 border border-blue-400 rounded-md hover:bg-blue-50 flex items-center gap-2 transition"
        (click)="file.click()"
      >
        <i class="bi bi-upload"></i>
        Upload Image
      </button>
    }

    <!-- Uploaded Preview -->
    @if (value) {
      <div class="flex flex-col items-center gap-2">
        <img
          [src]="value"
          [style.width.rem]="size"
          alt="Uploaded Image"
          class="rounded-lg shadow-md cursor-pointer hover:opacity-90 transition"
          (click)="file.click()"
        />

        <div class="flex items-center gap-4 text-xs text-blue-600">
          <a (click)="view = !view" class="flex items-center gap-1 cursor-pointer hover:text-blue-800">
            <i class="bi bi-eye"></i> View
          </a>
          <a (click)="removeImage()" class="flex items-center gap-1 cursor-pointer text-red-500 hover:text-red-700">
            <i class="bi bi-trash"></i> Remove
          </a>
        </div>
      </div>
    }

    <!-- Modal View -->
    @if (view && value) {
      <div
        class="fixed inset-0 bg-black bg-opacity-80 flex flex-col items-center justify-center gap-4 z-50"
        (click)="closeModal($event)"
      >
        <img
          [src]="value"
          alt="Preview"
          class="max-w-[50%] rounded-xl shadow-lg"
        />
        <input
          type="text"
          class="px-3 py-2 text-sm bg-gray-900 text-white rounded-md w-[60%] outline-none"
          [(ngModel)]="value"
        />
        <button
          type="button"
          class="mt-2 px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700"
          (click)="view = false"
        >
          Close
        </button>
      </div>
    }
  </div>
  `,
})
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() {
    const control = this.formGroup?.get(this.formControlName);
    if (control) {
      this.value = control.value || '';
      this.subscription = control.valueChanges.subscribe((val: string) => {
        this.value = val || '';
        this.cdr.detectChanges();
      });
    }
  }

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

  onFileChange(files: FileList | null) {
    this.uploadService.onUpload(
      files,
      {},
      '',
      (url: string) => {
        this.formGroup.get(this.formControlName)?.setValue(url);
        this.onChange(url);
      }
    );
  }

  removeImage() {
    this.value = '';
    this.formGroup.get(this.formControlName)?.setValue('');
    this.onChange('');
  }

  closeModal($event: MouseEvent) {
    if ($event.target === $event.currentTarget) this.view = false;
  }

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

  writeValue(value: string): void {
    this.value = value;
    this.parentItem[this.imageKey] = value;
    this.cdr.detectChanges();
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}
