import { Injectable, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, switchMap, map, of, forkJoin } from 'rxjs';
import { FeedbackReport, FeedbackType } from '../models/feedback.model';
import { environment } from '../../../../environments/environment';

@Injectable({ providedIn: 'root' })
export class FeedbackSubmitService {
  private http = inject(HttpClient);
  private readonly API = environment.apiUrl;

  submitting = signal(false);

  submitToSupport(report: FeedbackReport): Observable<any> {
    this.submitting.set(true);

    return this.http
      .post<any>(`${this.API}/support/feedbacks`, {
        title: this.buildTitle(report),
        description: this.buildDescription(report),
        type: this.mapType(report.type),
        source: 'web',
        urgency: this.mapUrgency(report.priority),
        affected_module: report.module,
        expected_behavior: report.expected_result || report.to_be || null,
        steps_to_reproduce: report.steps_to_reproduce || null,
      })
      .pipe(
        switchMap((response) => {
          const feedbackId = response.data?.id;
          if (!feedbackId) return of(response);

          const followUps: Observable<any>[] = [];

          // Upload screenshots as attachments
          for (let i = 0; i < report.screenshots.length; i++) {
            const ss = report.screenshots[i];
            const imageData = ss.annotated_url || ss.data_url;
            if (imageData) {
              const file = this.dataUrlToFile(imageData, `screenshot-${i + 1}.png`);
              const formData = new FormData();
              formData.append('file', file);
              followUps.push(
                this.http.post<any>(
                  `${this.API}/support/feedbacks/${feedbackId}/attachments`,
                  formData,
                ),
              );
            }
          }

          if (followUps.length > 0) {
            return forkJoin(followUps).pipe(map(() => response));
          }

          return of(response);
        }),
        map((response) => {
          this.submitting.set(false);
          return response;
        }),
      );
  }

  private dataUrlToFile(dataUrl: string, filename: string): File {
    const [header, base64] = dataUrl.split(',');
    const mime = header.match(/:(.*?);/)?.[1] || 'image/png';
    const binary = atob(base64);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      bytes[i] = binary.charCodeAt(i);
    }
    return new File([bytes], filename, { type: mime });
  }

  private buildTitle(report: FeedbackReport): string {
    const typeLabel = this.getTypeLabel(report.type);
    const desc = report.description.substring(0, 80);
    return `[${typeLabel}] ${report.module} > ${report.screen_name}: ${desc}`;
  }

  private buildDescription(report: FeedbackReport): string {
    const parts: string[] = [];

    parts.push(`📍 الموقع: ${report.page_url}`);
    parts.push(`📦 الموديول: ${report.module} > ${report.screen_name}`);
    parts.push(`👤 المستخدم: ${report.user_name || 'N/A'}`);
    parts.push(`📅 التاريخ: ${report.created_at}`);
    parts.push('');

    parts.push(`📝 الوصف:\n${report.description}`);
    parts.push('');

    if (report.type === 'bug') {
      if (report.steps_to_reproduce) {
        parts.push(`🔄 خطوات إعادة الإنتاج:\n${report.steps_to_reproduce}`);
      }
      if (report.expected_result) {
        parts.push(`✅ النتيجة المتوقعة:\n${report.expected_result}`);
      }
      if (report.actual_result) {
        parts.push(`❌ النتيجة الفعلية:\n${report.actual_result}`);
      }
    }

    if (report.type === 'change_request') {
      if (report.change_type) parts.push(`🔧 نوع التغيير: ${report.change_type}`);
      if (report.as_is) parts.push(`📋 الوضع الحالي:\n${report.as_is}`);
      if (report.to_be) parts.push(`🎯 المطلوب:\n${report.to_be}`);
      if (report.why) parts.push(`❓ السبب:\n${report.why}`);
    }

    if (report.target_elements?.length > 0) {
      parts.push('');
      parts.push(`🎯 العناصر المستهدفة (${report.target_elements.length}):`);
      for (const el of report.target_elements) {
        parts.push(
          `  - <${el.tag}>${el.id ? '#' + el.id : ''} "${el.text?.substring(0, 50)}" → ${el.css_path}`,
        );
      }
    }

    if (report.screenshots?.length > 0) {
      parts.push('');
      parts.push(`📸 لقطات الشاشة: ${report.screenshots.length} (مرفقة)`);
    }

    // AI Report inline
    if (report.ai_report) {
      parts.push('');
      parts.push(`🤖 تقرير الذكاء الاصطناعي (${report.ai_provider || 'auto'}):`);
      parts.push(report.ai_report);
    }

    return parts.join('\n');
  }

  private mapType(type: FeedbackType): string {
    switch (type) {
      case 'bug':
        return 'bug';
      case 'change_request':
      case 'improvement':
        return 'suggestion';
      case 'feature_request':
        return 'suggestion';
    }
  }

  private mapUrgency(priority?: string): string {
    switch (priority) {
      case 'high':
        return 'high';
      case 'medium':
        return 'normal';
      case 'low':
        return 'low';
      default:
        return 'normal';
    }
  }

  private getTypeLabel(type: FeedbackType): string {
    switch (type) {
      case 'bug':
        return 'Bug';
      case 'change_request':
        return 'Change Request';
      case 'improvement':
        return 'Improvement';
      case 'feature_request':
        return 'Feature Request';
    }
  }
}
