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 { AuthService } from '../auth.service';
import { LanguageService } from '../language.service';
import { TranslationService } from '../translation.service';


declare var tinymce: any;

@Component({
  selector: 'app-writestory',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, EditorModule, HeaderComponent, RouterModule],
  templateUrl: './writestory.component.html',
  styleUrl: './writestory.component.css'
})
export class WritestoryComponent implements OnInit {
  storyForm: FormGroup;
  editorConfig: any;
  storyId: number | null = null;
  isReadOnly: boolean = false;
  message: string = '';
  editStoryId: number | null = null; 
  episodeId: number | null = null;
  selectedLanguage: string = 'en';

  videoFile: File | null = null;
videoUploadProgress: number | null = null;
uploadedVideoUrl: string = '';
videoUploading: boolean = false; 

  constructor(
    private contentService: AllapiService,
    private fb: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private cd: ChangeDetectorRef,
    private authService: AuthService,
    public translationService: TranslationService,
    private languageService: LanguageService 
  ) {
    this.storyForm = this.fb.group({
      story_title: ['', Validators.required],
      story_content: ['', Validators.required],
      video_link: [''],
      audio_link: ['']
    });

    this.setEditorConfig(false);
  }

  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;
  }

  // Get the editStoryId from route params
  this.route.paramMap.subscribe(params => {
      const idAndTitle = params.get('idAndTitle');
      if (idAndTitle) {
        this.editStoryId = parseInt(idAndTitle.split('-')[0], 10);
        this.storyId = this.editStoryId; // ✅ fix added
        console.log('Edit Story ID:', this.editStoryId);
        this.loadStory();
      }
    });

  // Get episodeId from query params
  this.route.queryParams.subscribe(params => {
    this.episodeId = params['episodeId'] ? parseInt(params['episodeId'], 10) : null;
    console.log('Episode ID:', this.episodeId);
    
    // If no episodeId in query params, try to get it from the loaded story
    if (!this.episodeId && this.editStoryId) {
      this.contentService.getStoryById(this.editStoryId).subscribe({
        next: (story) => {
          if (story.episode_id) {
            this.episodeId = story.episode_id;
          }
        }
      });
    }
  });
}

  loadStory() {
  if (!this.editStoryId) return;

  this.contentService.getStoryById(this.editStoryId).subscribe({
    next: (response: any) => {
      console.log('Story loaded:', response);
      if (response.status === 'success' && response.data) {
        let storyHtml = response.data.content || '';
        let storyTitle = response.data.story_title || '';
        let videoLink = response.data.video_link || '';
        let audioLink = response.data.audio || '';

        storyHtml = this.cleanWordHTML(storyHtml);

        this.storyForm.patchValue({
          story_title: storyTitle,
          story_content: storyHtml,
          video_link: videoLink,
          audio_link: audioLink
        });

        this.cd.detectChanges();
        setTimeout(() => {
          if (tinymce.activeEditor) {
            tinymce.activeEditor.setContent(storyHtml);
          }
        }, 100);

        this.setEditorConfig(this.isReadOnly);
        this.cd.detectChanges();
      }
    },
    error: (err) => console.error('Error loading story:', err)
  });
}

  cleanWordHTML(html: string): string {
    if (!html) return '';
    return html
      .replace(/<!--[\s\S]*?-->/g, '') 
      .replace(/<(\w+)[^>]*>\s*<\/\1>/g, '') 
      .replace(/<(\w+)[^>]*class="[^"]*"[^>]*>/g, '<$1>') 
      .replace(/<(\w+)[^>]*style="[^"]*"[^>]*>/g, '<$1>') 
      .replace(/<span[^>]*>/g, '') 
      .replace(/<\/span>/g, '')
      .replace(/<font[^>]*>/g, '') 
      .replace(/<\/font>/g, '') 
      .replace(/<o:p>|<\/o:p>/g, '') 
      .replace(/<(\w+)[^>]*>(&nbsp;|\s)*<\/\1>/g, '') 
      .replace(/&nbsp;/g, ' ') 
      .replace(/\s+/g, ' ') 
      .trim();
  }
  setEditorConfig(isReadOnly: boolean) {
    this.editorConfig = {
      height: 500,
      menubar: false,
      plugins: ['lists', 'link', 'image', 'code', 'paste'],
      toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | removeformat | code',
      readonly: isReadOnly,
      directionality: 'ltr',

      // Paste handling
      paste_as_text: false, // Set to true if you want plain text only
      paste_block_drop: true,
      paste_data_images: false,
      paste_webkit_styles: 'none',
      paste_remove_styles: true,
      paste_remove_styles_if_webkit: true,
      paste_strip_class_attributes: 'all',

      // Content filtering (only one valid_elements definition)
      valid_elements: 'p,h1,h2,h3,h4,h5,h6,strong,em,b,i,u,a[href|target=_blank],ul,ol,li,img[src|alt|width|height],br,hr,blockquote,pre,code',

      // Extended elements (if needed, merge with valid_elements)
      // extended_valid_elements: '', // Comment out or merge with valid_elements

      // Forbidden elements
      invalid_elements: 'script,iframe,object,embed,style,link,form,input,textarea,button,table,tr,td',

      // Content CSS
      content_css: false,

      // Automatic cleanup
      cleanup: true,
      verify_html: true
    };
  }


  updateContent() {
    setTimeout(() => {
      if (tinymce.activeEditor) {
        const content = tinymce.activeEditor.getContent() || '';
        this.storyForm.controls['story_content'].setValue(content);
        this.storyForm.updateValueAndValidity();
        this.cd.detectChanges();
      }
    }, 0);
  }
  // publishStory() {
  //   this.updateContent(); // Sync TinyMCE content with form

  //   setTimeout(() => {
  //     const formValues = this.storyForm.getRawValue();
  //     const storyTitle = (formValues.story_title || '').trim();
  //     const storyContent = (formValues.story_content || '').trim();
  //     const videoLink = (formValues.video_link || '').trim();
  //     const audioLink = (formValues.audio_link || '').trim();

  //     if (!this.storyId) {
  //       alert('⚠ Cannot publish. Story ID is missing.');
  //       return;
  //     }

  //     if (!storyTitle || !storyContent || storyTitle.length > 255 || this.stripHtml(storyContent).trim().length < 3) {
  //       alert('⚠ Please complete the title and content before publishing.');
  //       return;
  //     }

  //     const formData = new FormData();
  //     formData.append('story_id', String(this.storyId));
  //     formData.append('story_title', storyTitle);
  //     formData.append('story_content', storyContent);
  //     formData.append('video_link', videoLink);
  //     formData.append('audio_link', audioLink);

  //     this.contentService.publishStory(formData).subscribe({
  //       next: (response: any) => {
  //         if (response.status === 'success') {
  //           const message = '✅ Story published successfully!';
  //           this.message = message;
  //           window.scrollTo({ top: 0, behavior: 'smooth' });
  //           setTimeout(() => {
  //             this.message = '';
  //             this.router.navigate(['/episode', `${this.storyId}-` + this.slugify(formValues.story_title)]);
  //           }, 3000);
  //         } else {
  //           alert('⚠ Failed to publish: ' + (response.message || 'Unknown error'));
  //         }
  //       },
  //       error: (err) => {
  //         console.error('Publish error:', err);
  //         alert('⚠ Server error occurred during publish.');
  //       }
  //     });
  //   }, 10);
  // }

publishStory() {
  this.updateContent();

  if (!this.episodeId) {
    alert('Cannot publish - missing episode reference');
    return;
  }

  const formValues = this.storyForm.getRawValue();
  const formData = new FormData();
  
  formData.append('story_id', String(this.editStoryId));
  formData.append('episode_id', String(this.episodeId));
  formData.append('story_title', formValues.story_title.trim());
  formData.append('story_content', formValues.story_content.trim());
  formData.append('video_link', formValues.video_link?.trim() || '');
  formData.append('audio_link', formValues.audio_link?.trim() || '');

  this.contentService.publishStory(formData).subscribe({
    next: (response: any) => {
      if (response.status === 'success') {
        // Fix: Properly construct the URL without double encoding
        const slug = this.slugify(formValues.story_title);
        const urlSegment = `${this.episodeId}-${slug}`;
        
        console.log('Redirecting to:', urlSegment); // Debug log
        
        this.router.navigate(['/episode', urlSegment], {
          skipLocationChange: false // Ensure proper navigation
        });
      }
    },
    error: (err) => {
      console.error('Publish error:', err);
      alert('Publish failed. Please check console for details.');
    }
  });
}

private doPublish() {
  const formValues = this.storyForm.getRawValue();
  const formData = new FormData();
  
  formData.append('story_id', String(this.editStoryId));
  formData.append('episode_id', String(this.episodeId));
  formData.append('story_title', formValues.story_title.trim());
  formData.append('story_content', formValues.story_content.trim());
  formData.append('video_link', formValues.video_link?.trim() || '');
  formData.append('audio_link', formValues.audio_link?.trim() || '');

  this.contentService.publishStory(formData).subscribe({
    next: (response: any) => {
      if (response.status === 'success') {
        const redirectUrl = `/${this.episodeId}-${this.slugify(formValues.story_title)}`;
        console.log('Publish successful, redirecting to:', redirectUrl);
        this.router.navigate(['/episode', redirectUrl]);
      } else {
        alert('Publish failed: ' + (response.message || 'Unknown error'));
      }
    },
    error: (err) => {
      console.error('Publish error:', err);
      alert('Publish failed. Please check console for details.');
    }
  });
}

checkUrlMode(): { isUpdate: boolean, isAdd: boolean } {
  const currentRoute = this.router.url;
  
  const isUpdate = currentRoute.includes('/story-write/') && /\/story-write\/\d+-/.test(currentRoute);
  const isAdd = currentRoute.includes('/creat/');
  
  return { isUpdate, isAdd };
}

  onSubmit() {
    console.log("updatestory");
    this.updateContent();
const { isUpdate, isAdd } = this.checkUrlMode();
    setTimeout(() => {
      const formValues = this.storyForm.getRawValue();
      const storyTitle = (formValues.story_title || '').trim();
      const storyContent = (formValues.story_content || '').trim();
      const videoLink = (formValues.video_link || '').trim();
      const audioLink = (formValues.audio_link || '').trim();

      // 1. Client-side validations
      if (!storyTitle) {
        alert('⚠ Please enter a story title');
        this.storyForm.controls['story_title'].markAsTouched();
        return;
      }

      if (storyTitle.length > 255) {
        alert('⚠ Title is too long (max 255 characters)');
        return;
      }

      if (!storyContent) {
        alert('⚠ Please enter story content');
        this.storyForm.controls['story_content'].markAsTouched();
        return;
      }

      const textOnlyContent = this.stripHtml(storyContent).trim();
      if (textOnlyContent.length < 10) {
        alert('⚠ Story content must contain at least 10 characters (excluding HTML)');
        return;
      }

      // 2. FormData creation

      const formData = new FormData();
      formData.append('story_id', String(this.storyId));
      formData.append('story_title', storyTitle);
      formData.append('story_content', storyContent);
      formData.append('video_link', videoLink);
      formData.append('audio_link', audioLink);


      if (this.storyId) {
        formData.append('story_id', String(this.storyId));
      }

      const userId = this.authService.getCurrentUserId();
      if (userId) {
        formData.append('user_id', userId.toString());
      }

    
      console.log('Sending FormData:', {
        story_id: formData.get('story_id'),
        story_title: formData.get('story_title'),
        story_content: formData.get('story_content'),
        video_link: formData.get('video_link'),
        audio: formData.get('audio_link'),
      });


      // 3. API call
      const apiCall = isUpdate 
    ? this.contentService.updateStory(formData)
    : this.contentService.addStory(formData);

      apiCall.subscribe({
        next: (response) => {
          console.log('Server response:', response);
          if (response.status === 'success') {
            const message = '✅ Save Story successfully!';
            this.message = message;
            window.scrollTo({ top: 0, behavior: 'smooth' });
            setTimeout(() => {
              this.message = '';
            }, 3000);
          } else {
            alert(`⚠ Server error: ${response.message || 'Unknown error'}`);
          }
        },
        error: (err) => {
          console.error('API error:', err);
          alert('⚠ Failed to save story. Please check console for details.');
        }
      });
    }, 10); // Wait for content update to reflect
  }


  // Helper function to strip HTML tags for length validation
  private stripHtml(html: string): string {
    const tmp = document.createElement('div');
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || '';
  }
  goBack() {
    window.history.back();
  }
  slugify(text: string): string {
    return text
      .toLowerCase()
      .trim()
      .replace(/[\s\W-]+/g, '-')
      .replace(/^-+|-+$/g, '');
  }
  onVideoSelected(event: Event) {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0] ?? null;
  if (!file) return;

  // Validate size/type (optional)
  const maxMB = 200;
  if (file.size > maxMB * 1024 * 1024) {
    alert('Video too large. Max ' + maxMB + 'MB.');
    return;
  }

  this.videoFile = file;
  this.videoUploadProgress = 0;
  this.videoUploading = true;

  this.uploadVideoFile();
}

uploadVideoFile() {
  if (!this.videoFile) return;

  const fd = new FormData();
  fd.append('video', this.videoFile, this.videoFile.name);

  this.videoUploading = true;
  this.videoUploadProgress = 0;

  this.contentService.uploadVideo(fd).subscribe({
    next: (event: any) => {
      if (event.type === 1 && event.total) {
        this.videoUploadProgress = Math.round(100 * event.loaded / event.total);
      } else if (event.type === 4) {
        this.videoUploading = false;
        if (event.body?.status === 'success') {
          this.uploadedVideoUrl = event.body.url;
          this.videoUploadProgress = 100;
          this.storyForm.patchValue({ video_link: event.body.url });
        } else {
          alert('Upload failed: ' + (event.body?.message || 'Unknown'));
          this.videoUploadProgress = null;
        }
      }
    },
    error: (err) => {
      this.videoUploading = false;
      this.videoUploadProgress = null;
      console.error('Upload error', err);
      alert('Video upload failed.');
    }
  });
}
}
