import { Component, ChangeDetectorRef, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router, RouterModule } from '@angular/router'; 
import { AllapiService } from '../allapi.service';
import { HeaderComponent } from '../header/header.component';
import { EditorModule } from '@tinymce/tinymce-angular';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { AuthService } from '../auth.service';
import { LanguageService } from '../language.service';
import { TranslationService } from '../translation.service';
declare var tinymce: any;
@Component({
  selector: 'app-new',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, EditorModule, HeaderComponent, RouterModule], 
  templateUrl: './new.component.html',
  styleUrl: './new.component.css'
})
export class NewComponent {
  categories: any[] = [];
storyForm: FormGroup;
  editorConfig: any;
  storyId: number | null = null;
  isReadOnly: boolean = false; // **Status 1 ke liye read-only mode**
tagsList: string[] = [];
selectedFile: File | null = null;
imagePreview: string | ArrayBuffer | null = null;
selectedLanguage: string = 'en';
showCreateCoverPopup = false;
message:string = '';
  constructor(
 
    private fb: FormBuilder, 
    private router: Router,
    private route: ActivatedRoute,  
    private http: HttpClient,
    private authService: AuthService,
    public translationService: TranslationService,
          private languageService: LanguageService 
  ) {
    
this.storyForm = this.fb.group({
      story_title: ['', Validators.required],
      story_description: ['', Validators.required],
      tagsInput: [''],
      tags: [''],
      copyright: ['1', Validators.required],
      audiences:['All Audiences',  Validators.required],
      language:['English', Validators.required],
      category:['', Validators.required]
    });
  }
ngOnInit(): void {
  this.selectedLanguage = this.languageService.getCurrentLanguage();
    
    // ✅ Language changes subscribe karein
    this.languageService.currentLanguage$.subscribe(lang => {
      this.selectedLanguage = lang;
    });
  const userId = this.authService.getCurrentUserId();
  if (!userId) {
    this.router.navigate(['login']);
    return;
  }

  this.getCategories();

  // ✅ Route params se id lena
  this.route.paramMap.subscribe(params => {
    const idParam = params.get('id');
    if (idParam) {
      this.storyId = +idParam;
      console.log('Editing Story ID:', this.storyId); // 🧪 Debug
      this.fetchStoryDetails(this.storyId);
    }
  });
}
t(key: string): string {
    return this.translationService.translate(key);
  }
fetchStoryDetails(id: number) {
  const userId = this.authService.getCurrentUserId();
  if (!userId) {
    this.router.navigate(['login']);
    return;
  }

  const headers = new HttpHeaders({
    'Content-Type': 'application/json'
  });

  this.http.get<any>('https://infoways.in/funtelapi/save_story.php?id=' + id, {
    headers: headers,
    withCredentials: true
  }).subscribe({
    next: (res) => {
      if (res.status === 'success') {
        const story = res.story;
        
        // Check if the current user owns this story
        if (story.user_id != userId) {
          this.router.navigate(['/404']); // Or show an access denied message
          return;
        }

        this.storyForm.patchValue({
          story_title: story.story_title,
          story_description: story.description,
          tags: story.tags,
          copyright: story.copyright,
          audiences: story.audiences,
          language: story.language,
          category: story.category
        });

        window.scrollTo({ top: 0, behavior: 'smooth' });

        // populate tag list
        if (story.tags) {
          this.tagsList = story.tags.split(',');
        }

        // preview image
        if (story.story_image) {
          this.imagePreview = 'https://infoways.in/funtelapi/' + story.story_image;
        }
      }
    },
    error: (err) => {
      console.error('Error fetching story:', err);
      this.router.navigate(['/404']); // Redirect if story doesn't exist
    }
  });
}
  onTagsKeyUp(event: any) {
    if (event.key === ',' || event.key === 'Enter') {
      event.preventDefault();
      this.addTag();
    }
  }

  onFileSelected(event: any) {
  const file = event.target.files[0];
  this.handleFile(file);
}
openCreateCoverPopup() {
    this.showCreateCoverPopup = true;
  }

  // Close Create Cover Popup
  closeCreateCoverPopup() {
    this.showCreateCoverPopup = false;
  }
  getCoverPrompt(): string {
    const storyTitle = this.storyForm.get('story_title')?.value || 'Your Story Title';
    const category = this.storyForm.get('category')?.value || 'Horror';
    
    return `Vertical 9:16 ultra-realistic ${category.toLowerCase()} poster of "${storyTitle}" in bold cracked white Hindi typography with "${category} Story" in red below. {Describe characters which you want in the poster.} Go to https://sora.chatgpt.com and generate poster.`;
  }

  // Copy Prompt to Clipboard
  copyPromptToClipboard() {
    const prompt = this.getCoverPrompt();
    navigator.clipboard.writeText(prompt).then(() => {
      // Show success message
      alert('Prompt copied to clipboard!');
    }).catch(err => {
      console.error('Failed to copy: ', err);
    });
  }
getCategories() {
  const headers = new HttpHeaders({
   
    'Content-Type': 'application/json'
  });

  this.http.get<any>('https://infoways.in/funtelapi/category.php', { headers, withCredentials: true }).subscribe({
    next: (res) => {
      if (res.status === 'success' && Array.isArray(res.data)) {
        this.categories = res.data;
        console.log('csddsadsa', this.categories)
      } else {
        this.categories = [];
      }
    },
    error: (err) => {
      console.error('Failed to load categories:', err);
      this.categories = [];
    }
  });
}
onFileDropped(event: DragEvent) {
  event.preventDefault();
  const file = event.dataTransfer?.files[0];
  if (file) {
  this.handleFile(file);
}
}

handleFile(file: File) {
  if (file && file.size <= 1024 * 1024) { // 1MB limit
    this.selectedFile = file;

    const reader = new FileReader();
    reader.onload = () => {
      this.imagePreview = reader.result;
    };
    reader.readAsDataURL(file);
  } else {
    alert('File size must be 1MB or less.');
  }
}

onDragOver(event: DragEvent) {
  event.preventDefault();
}
addTag() {
    const tagsInput = this.storyForm.get('tagsInput')?.value.trim();
    if (tagsInput) {
      // Split by comma and trim each tag
      const newTags = tagsInput.split(',')
        .map((tag:any) => tag.trim())
        .filter((tag:any) => tag.length > 0);
      
      // Add to tags list (avoid duplicates)
      newTags.forEach((tag:any) => {
        if (!this.tagsList.includes(tag)) {
          this.tagsList.push(tag);
        }
      });
      
      // Update the form control with comma-separated tags
      this.storyForm.get('tags')?.setValue(this.tagsList.join(','));
      this.storyForm.get('tagsInput')?.setValue('');
    }
  }
   removeTag(index: number) {
    this.tagsList.splice(index, 1);
    this.storyForm.get('tags')?.setValue(this.tagsList.join(','));
  }
  onSubmit() {
    if (this.storyForm.invalid) {
    this.storyForm.markAllAsTouched();
    this.message = 'Please fill all required fields.';
    window.scrollTo({ top: 0, behavior: 'smooth' });
    return;
  }
  if (this.storyForm.valid) {
    const formData = new FormData();

    formData.append('story_title', this.storyForm.get('story_title')?.value);
    formData.append('story_description', this.storyForm.get('story_description')?.value);
    formData.append('tags', this.storyForm.get('tags')?.value);
    formData.append('copyright', this.storyForm.get('copyright')?.value);
    formData.append('audiences', this.storyForm.get('audiences')?.value);
    formData.append('language', this.storyForm.get('language')?.value);
    formData.append('category', this.storyForm.get('category')?.value);

    if (this.selectedFile) {
      formData.append('cover_image', this.selectedFile);
    }

    const userId = this.authService.getCurrentUserId();
    if (!userId) {
      alert('You must be logged in to save a story.');
      this.router.navigate(['login']);
      return;
    }

    formData.append('user_id', userId.toString());
    if (this.storyId) {
      formData.append('story_id', this.storyId.toString());
    }

    this.logFormData(formData);

    // ✅ REMOVE `headers`, DO NOT set 'Content-Type'!
    this.http.post<any>(
      'https://infoways.in/funtelapi/save_story.php',
      formData,
      {
        withCredentials: true,
        observe: 'response'
      }
    ).subscribe({
      next: (response) => {
        const res = response.body;
        if (res?.status === 'success') {
          this.message = this.storyId ? 'Story updated successfully' : 'Story created successfully';
          window.scrollTo({ top: 0, behavior: 'smooth' });
          setTimeout(() => { this.message = ''; }, 3000);

          if (!this.storyId && res.story_id) {
            this.router.navigate(['/creat', res.story_id]);
          }
        } else {
          this.message = res?.message || 'Operation completed but with unexpected status';
        }
      },
      error: (err) => {
        console.error('Full error:', err);
        this.message = err?.error?.message || err?.error?.error || err?.message || 'Network/server error occurred';
      }
    });
  }
}
logFormData(formData: FormData) {
  console.log('FormData contents:');
  const formDataEntries = (formData as any).entries(); // Type assertion
  for (const pair of formDataEntries) {
    console.log(pair[0] + ': ', pair[1]);
  }
}

validateFormBeforeSubmit() {
  console.log('Form validity:', this.storyForm.valid);
  console.log('Form values:', this.storyForm.value);
  console.log('User ID:', this.authService.getCurrentUserId());
  console.log('Story ID:', this.storyId);
  console.log('Selected file:', this.selectedFile ? this.selectedFile.name : 'None');
}



  writenew() {
    this.onSubmit();
  }
}