import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AngularEditorConfig } from '@josipv/angular-editor-k2';
import { AuthenticationService } from 'src/app/service/authentication.service';
;
import { BlogService } from 'src/app/service/blog.service';
import { ProfessorService } from 'src/app/service/professor.service';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.css'],
})
export class BlogComponent implements OnInit {
  blogs: any[] = [];
  allProfessors: any[] = [];
  selectedBlog: any = null;
  blogForm: FormGroup;
  editing: boolean = false;
  loggedInUser: any;
  currentBlog: any = null; // Holds the blog being edited
  isShowForm = false; // Controls visibility of form vs. table
  content = '';

  constructor(
    private blogService: BlogService,
    private authService: AuthenticationService,
    private professorService: ProfessorService,
    private fb: FormBuilder
  ) {
    // Initialize form with form controls
    this.blogForm = this.fb.group({
      title: ['', Validators.required],
      content: ['', Validators.required],
      professors: [[], Validators.required], // To hold selected professor IDs
      tags: ['', Validators.required], // To hold tags as a comma-separated string
      posted: [true], // Initialize checkbox with default value false
    });
  }

  editorConfig: AngularEditorConfig = {
    editable: true,
    spellcheck: true,
    height: '10',
    minHeight: '0',
    maxHeight: 'auto',
    width: 'auto',
    minWidth: '0',
    translate: 'yes',
    enableToolbar: true,
    showToolbar: true,
    placeholder: 'Enter text here...',
    defaultParagraphSeparator: '',
    defaultFontName: '',
    defaultFontSize: '',
    // headers: [{

    // }],
    fonts: [
      { class: 'arial', name: 'Arial' },
      { class: 'times-new-roman', name: 'Times New Roman' },
      { class: 'calibri', name: 'Calibri' },
      { class: 'comic-sans-ms', name: 'Comic Sans MS' },
    ],
    customClasses: [
      {
        name: 'quote',
        class: 'quote',
      },
      {
        name: 'redText',
        class: 'redText',
      },
      {
        name: 'titleText',
        class: 'titleText',
        tag: 'h1',
      },
    ],
    // uploadUrl: 'v1/image',
    // upload: (file: File) => { ... }
    // uploadWithCredentials: false,
    sanitize: true,
    toolbarPosition: 'top',
    toolbarHiddenButtons: [['bold', 'italic'], ['fontSize']],
  };

 

    ngOnInit(): void {
      this.loggedInUser = this.authService.getUserFromLocalStorage();
      this.professorService
        .getAllProfessors()
        .subscribe((res) => (this.allProfessors = res.content));

      this.loadBlogs();
      // Subscribe to form value changes to update content for preview
      this.blogForm.get('content')?.valueChanges.subscribe((value) => {
        this.content = value;
      });
    }

    showForm() {
      this.isShowForm = true;
      this.resetForm(); // Ensure form is reset when showing
    }
  
    showTable() {
      this.isShowForm = false;
      this.resetForm(); // Ensure form is reset when switching back
    }
  
    loadBlogs() {
      this.blogService.getBlogs().subscribe(data => {
        this.blogs = data;
      });
    }
  
    createBlog() {
      this.showForm(); // Show form to create a new blog
      this.blogForm.reset();
      this.selectedBlog = null;
      this.editing = false;
    }
  
    editBlog(blog: any) {
      
      this.selectedBlog = blog;

      this.blogForm.patchValue({
        title: blog.title,
        content: blog.content,
        posted: blog.posted,
        professors: blog.professors.map((prof: any) => prof.id), // Assuming professors are an array of objects
        tags: blog.tags.join(', ') // Convert tags array back to comma-separated string
      });
      this.editing = true;
      this.isShowForm = true;
      
    }
  
    saveBlog() {
      if (this.blogForm.valid) {
        const blogData = this.blogForm.value;
  
        // Convert tags to array and professors to array of IDs
        blogData.tags = blogData.tags.split(',').map((tag: string) => tag.trim());
        blogData.professors = blogData.professors || [];
  
        blogData.author = this.loggedInUser._id; // Associate logged-in user with the blog
  
        if (this.editing && this.selectedBlog) {
          this.blogService.updateBlog(this.selectedBlog.id, blogData).subscribe(() => {
            this.loadBlogs();
            this.resetForm();
            this.isShowForm = false; // Hide form after update
          });
        } else {
          this.blogService.createBlog(blogData).subscribe(() => {
            this.loadBlogs();
            this.resetForm();
            this.isShowForm = false; // Hide form after creation
          });
        }
      }
    }
  
    deleteBlog(blog: any) {
      if (confirm('Are you sure you want to delete this blog?')) {
        this.blogService.deleteBlog(blog.id).subscribe(() => {
          this.loadBlogs();
        });
      }

    }
  
    resetForm() {
      this.blogForm.reset();
      this.selectedBlog = null;
      this.editing = false;
      this.blogForm.patchValue({
        professors: [],
        tags: ''
      });
    }
  }
  