import { formatJalali, formatWithCurrency, jalaliDiff } from '@/utils';
import { CommonModule } from '@angular/common';
import { Component, EventEmitter, Input, Output, TemplateRef } from '@angular/core';
import { Tag } from 'primeng/tag';
import { UikitCopyComponent } from '@/uikit';
import { IColumn } from './page-data-list.component';

@Component({
  selector: 'app-page-data-value',
  standalone: true,
  imports: [CommonModule, Tag, UikitCopyComponent],
  template: `
    @if (column.type === 'thumbnail') {
      <div class="w-20 h-20 rounded-2xl overflow-hidden bg-surface-100 cursor-pointer" (click)="thumbnailClick.emit(item)">
        @if (readFieldValue(item, column.field)) {
          <img [src]="readFieldValue(item, column.field)" class="w-full h-full object-cover" />
        }
      </div>
    } @else if (column.variant === 'tag') {
      <p-tag [value]="getCell(item, column)" [severity]="column.tagOptions?.severity || 'contrast'"></p-tag>
    } @else if (getTemplate(column)) {
      <ng-container [ngTemplateOutlet]="getTemplate(column)" [ngTemplateOutletContext]="{ $implicit: item }"></ng-container>
    } @else if (column.canCopy) {
      <uikit-copy [text]="getCell(item, column)"></uikit-copy>
    } @else {
      <span [class]="getPreviewClasses(item, column)">{{ getCell(item, column) }}</span>
    }
  `,
})
export class PageDataValueComponent {
  @Input({ required: true }) item!: Record<string, any>;
  @Input({ required: true }) column!: IColumn;
  @Output() thumbnailClick = new EventEmitter<any>();

  readFieldValue(item: Record<string, any>, field: IColumn['field']) {
    return item?.[String(field)];
  }

  getPreviewClasses(item: Record<string, any>, column: IColumn): string {
    if (!item || !column || column.customDataModel) return '';
    const data = item[String(column.field)];
    if (column.type === 'date' && column.dateOption?.expiredMode && jalaliDiff(new Date(), data) > 0) {
      return 'text-error';
    }
    return '';
  }

  getCell(item: Record<string, any>, column: IColumn): any {
    if (!item || !column) return '';
    let { field, type } = column;

    if (column.customDataModel) {
      return this.renderCustom(column, item);
    }

    let data = item[String(field)];
    if (column.type === 'nested') {
      const path = column.nestedOption?.path;
      if (!path) return '-';
      data = path.split('.').reduce((obj: any, key: string) => (obj && obj[key] !== undefined ? obj[key] : null), item);
      type = column.nestedOption?.type || 'simple';
    }

    switch (type) {
      case 'id':
        return data ? `${data.slice(0, 5)}...${data.slice(data.length - 5)}` : '-';
      case 'date':
        return data ? formatJalali(data) : '-';
      case 'boolean':
        return data ? 'بله' : 'خیر';
      case 'price':
        return formatWithCurrency(data, false, 'ریال');
      case 'number':
        return data || 0;
    }

    if (data === undefined || data === null) return '-';
    if (typeof data === 'object') return data.title || '-';
    return data || '-';
  }

  getTemplate(col: IColumn): TemplateRef<any> | null {
    const v = col.customDataModel;
    return v instanceof TemplateRef ? (v as TemplateRef<any>) : null;
  }

  renderCustom(column: IColumn, item: any): any {
    const v = column.customDataModel;
    if (!v) return null;
    if (typeof v === 'function') {
      try {
        return (v as (item: any) => any)(item);
      } catch {
        return '-';
      }
    }
    if (typeof v === 'string') return v;
    return null;
  }
}
