import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LocalHistoryService } from '../../services/local-history.service';
import { RemoteInferenceService } from '../../core/services/remote-inference.service';
import { SurveillanceService } from '../../services/surveillance.service';

const GRADE_COLORS: Record<string, string> = {
  'Empty_Bunch': '#6C757D', 'Underripe': '#F9A825', 'Abnormal': '#DC3545',
  'Ripe': '#00A651', 'Unripe': '#9E9D24', 'Overripe': '#5D4037',
};

export interface BatchSessionGroup {
  batch_id: string;
  label: string;         // e.g. "Batch Session · April 20"
  count: number;
  timestamp: string;
  records: any[];
  expanded: boolean;
}

@Component({
  selector: 'app-history',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './history.component.html',
  styleUrls: ['./history.component.scss']
})
export class HistoryComponent implements OnInit {
  localHistoryRecords: any[] = [];
  remoteHistoryRecords: any[] = [];
  /** Remote records grouped by batch_id for the Industrial Cloud tab */
  batchGroups: BatchSessionGroup[] = [];

  viewMode: 'local' | 'remote' = 'local';
  loading = true;
  expandedId: string | null = null;

  constructor(
    private localHistory: LocalHistoryService,
    private remoteInference: RemoteInferenceService,
    public surveillance: SurveillanceService,
  ) {}

  ngOnInit(): void {
    this.loadLocalHistory();
  }

  loadLocalHistory(): void {
    this.loading = true;
    this.localHistoryRecords = this.localHistory.getRecords();
    this.loading = false;
  }

  loadRemoteHistory(): void {
    this.loading = true;
    this.remoteInference.getHistory().subscribe({
      next: (data) => {
        this.remoteHistoryRecords = data.map(record => ({
          ...record,
          timestamp: new Date(record.created_at).toLocaleString(),
          engine: 'API AI',
          isNormalized: false,
          imageData: `http://localhost:3000/palm-oil/archive/${record.archive_id}`
        }));
        this.batchGroups = this.groupByBatch(this.remoteHistoryRecords);
        this.loading = false;
      },
      error: (err) => {
        console.error('Failed to load remote history:', err);
        this.loading = false;
      }
    });
  }

  /** Group remote records by batch_id. Records without a batch_id each form a singleton group. */
  private groupByBatch(records: any[]): BatchSessionGroup[] {
    const map = new Map<string, any[]>();
    records.forEach(r => {
      const key = r.batch_id || `__solo__${r.archive_id}`;
      if (!map.has(key)) map.set(key, []);
      map.get(key)!.push(r);
    });

    return Array.from(map.entries()).map(([key, recs]) => {
      const first = recs[0];
      const isSolo = key.startsWith('__solo__');
      const date = new Date(first.created_at).toLocaleDateString('en-US', {
        month: 'long', day: 'numeric', year: 'numeric'
      });
      return {
        batch_id: key,
        label: isSolo ? `Single Scan · ${date}` : `Batch Session · ${date} · ${recs.length} images`,
        count: recs.length,
        timestamp: first.timestamp,
        records: recs,
        expanded: false,
      };
    });
  }

  switchTab(mode: 'local' | 'remote'): void {
    if (mode === 'remote' && this.surveillance.nestStatus() === 'OFFLINE') return;
    this.viewMode = mode;
    this.expandedId = null;
    if (mode === 'local') {
      this.loadLocalHistory();
    } else {
      this.loadRemoteHistory();
    }
  }

  toggleBatchGroup(group: BatchSessionGroup): void {
    group.expanded = !group.expanded;
  }

  // ── Delete actions ────────────────────────────────────────────────────────

  deleteLocalRecord(record: any, event: Event): void {
    event.stopPropagation();
    this.localHistory.deleteRecord(record.timestamp, record.filename);
    this.loadLocalHistory();
  }

  clearLocalHistory(event: Event): void {
    event.stopPropagation();
    if (!confirm('Clear all Browser Cache records? This cannot be undone.')) return;
    this.localHistory.clearAll();
    this.loadLocalHistory();
  }

  deleteRemoteRecord(record: any, event: Event): void {
    event.stopPropagation();
    if (!record.archive_id) return;
    this.remoteInference.deleteRecord(record.archive_id).subscribe(() => {
      this.loadRemoteHistory();
    });
  }

  clearRemoteHistory(event: Event): void {
    event.stopPropagation();
    if (!confirm('Delete ALL industrial cloud records from the server? This also removes archived images from disk.')) return;
    this.remoteInference.clearAll().subscribe(() => {
      this.loadRemoteHistory();
    });
  }

  get currentHistory(): any[] {
    return this.viewMode === 'local' ? this.localHistoryRecords : this.remoteHistoryRecords;
  }

  parseJSON(jsonStr: string): any {
    try {
      return typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr;
    } catch {
      return {};
    }
  }

  getSummaryBadge(summary: any): string[] {
    const data = typeof summary === 'string' ? this.parseJSON(summary) : summary;
    return Object.entries(data)
      .filter(([_, count]) => (count as number) > 0)
      .map(([key, count]) => `${key}: ${count}`);
  }

  toggleExpand(timestamp: string, filename: string, archiveId?: string): void {
    const id = archiveId || `${timestamp}-${filename}`;
    this.expandedId = this.expandedId === id ? null : id;
  }

  isExpanded(timestamp: string, filename: string, archiveId?: string): boolean {
    const id = archiveId || `${timestamp}-${filename}`;
    return this.expandedId === id;
  }

  getBoxStyles(box: number[], record: any): any {
    const dims = record.industrial_summary ? { width: 640, height: 640 } : (record.original_dimensions || record.dimensions);
    if (!dims) return {};
    return {
      'left': (box[0] / dims.width * 100) + '%',
      'top': (box[1] / dims.height * 100) + '%',
      'width': ((box[2] - box[0]) / dims.width * 100) + '%',
      'height': ((box[3] - box[1]) / dims.height * 100) + '%',
      'border-color': record.is_health_alert ? '#DC3545' : '#00A651',
    };
  }

  /** CSS border color for a detection box by ripeness class */
  getDetectionColor(det: any): string {
    return GRADE_COLORS[det.class] ?? '#00A651';
  }

  /** Aggregate industrial_summary for a batch group into display badges */
  getGroupSummary(group: BatchSessionGroup): string[] {
    const totals: Record<string, number> = {};
    group.records.forEach(r => {
      const summary = typeof r.industrial_summary === 'string'
        ? this.parseJSON(r.industrial_summary) : r.industrial_summary;
      if (!summary) return;
      Object.entries(summary).forEach(([cls, n]) => {
        totals[cls] = (totals[cls] ?? 0) + (n as number);
      });
    });
    return Object.entries(totals)
      .filter(([, n]) => n > 0)
      .map(([cls, n]) => `${cls}: ${n}`);
  }
}
