import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { LocationContentDTO } from '../Models/location.model';

interface ContentItem extends LocationContentDTO {
  fileName?: string;
}

@Component({
  selector: 'app-polygon-content-dialog',
  templateUrl: './polygon-content-dialog.component.html',
  styleUrls: ['./polygon-content-dialog.component.css']
})
export class PolygonContentDialogComponent {
  contents: ContentItem[] = [];

  constructor(
    public dialogRef: MatDialogRef<PolygonContentDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    // Initialize with existing contents or empty array
    const typedData = data as { contents?: LocationContentDTO[] };
    this.contents = typedData.contents && typedData.contents.length > 0
      ? JSON.parse(JSON.stringify(typedData.contents))  // Deep copy
      : [];
  }

  addContent(): void {
    this.contents.push({
      content: {
        type: 'TEXT',
        value: ''
      }
    });
  }

  removeContent(index: number): void {
    this.contents.splice(index, 1);
  }

  onTypeChange(index: number): void {
    // Clear value when type changes
    this.contents[index].content['value'] = '';
    if (this.contents[index].fileName) {
      delete this.contents[index].fileName;
    }
  }

  onFileSelected(event: any, index: number): void {
    const file = event.target.files[0];
    if (file) {
      this.contents[index].fileName = file.name;

      // Convert file to base64 for preview and storage
      const reader = new FileReader();
      reader.onload = (e: any) => {
        this.contents[index].content['value'] = e.target.result;
      };
      reader.readAsDataURL(file);
    }
  }

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

  onSave(): void {
    // Filter out empty contents
    const validContents = this.contents.filter(c => {
      const value = c.content['value'];
      return value && value.toString().trim() !== '';
    });

    // Remove fileName property before returning
    const cleanContents = validContents.map(c => ({
      content: {
        type: c.content['type'],
        value: c.content['value']
      }
    }));

    this.dialogRef.close(cleanContents);
  }
}
