import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Design_lbraryservice } from './Design_lbrary.service';
import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators, ValidationErrors } from '@angular/forms';
import { ExtensionService } from 'src/app/services/fnd/extension.service';
import { DashboardContentModel2 } from 'src/app/models/builder/dashboard';
import { Design_lbrarycardvariable } from './Design_lbrary_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
import { SiteTreeservice } from '../SiteBuilderGrid/SiteTree.service';
import { COMMON_CSS } from '../WireframesUi/common-css';
import { ActivatedRoute } from '@angular/router';
// import { Download_Css } from '../WireframesUi/download-css';
declare var JsBarcode: any;
@Component({
  selector: 'app-Design_lbrary',
  templateUrl: './Design_lbrary.component.html',
  styleUrls: ['./Design_lbrary.component.scss']
})
export class Design_lbraryComponent implements OnInit {

  commonCss: string = COMMON_CSS;

  cardButton = Design_lbrarycardvariable.cardButton;
  cardmodeldata = Design_lbrarycardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Design_lbrarycardvariable.cardButton;
  cardmodal; changeView() {
    this.isCardview = !this.isCardview;
  }
  beforeText(fieldtext: string): string { // Extract the text before the first '<'
    const index = fieldtext.indexOf('<');
    return index !== -1 ? fieldtext.substring(0, index) : fieldtext;
  }
  afterText(fieldtext: string): string { // Extract the text after the last '>'
    const index = fieldtext.lastIndexOf('>');
    return index !== -1 ? fieldtext.substring(index + 1) : '';
  }
  transform(fieldtext: string): string {
    const match = fieldtext.match(/<([^>]*)>/);
    return match ? match[1] : ''; // Extract the text between '<' and '>'
  }
  userrole;
  rowSelected: any = {};
  modaldelete = false;
  modalEdit = false;
  modalAdd = false;
  public entryForm: FormGroup;
  loading = false;
  product;
  modalOpenedforNewLine = false;
  newLine: any;
  additionalFieldsFromBackend: any[] = [];
  formcode = 'Design_lbrary_formCode'
  headerId;
  tableName = 'Design_lbrary'; checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
    private userInfoService: UserInfoService,
    private mainService: Design_lbraryservice,
    private alertService: AlertService,
    private toastr: ToastrService,
    private _fb: FormBuilder,
    private siteTreeService: SiteTreeservice,
    private route: ActivatedRoute,

  ) { }
  // component button 
  ngOnInit(): void {
    this.headerId = this.route.snapshot.params["id"];
    console.log("headerId : = ", this.headerId);
    if (this.cardmodeldata !== '') {
      this.cardmodal = JSON.parse(this.cardmodeldata);
      this.dashboardArray = this.cardmodal.dashboard.slice();
      console.log(this.dashboardArray)
    }
    this.userrole = this.userInfoService.getRoles();
    this.getData();
    this.entryForm = this._fb.group({
      name: [null],

      description: [null],

      active: [false],

      htmljson: [null],

      css: [null],
      templatetype: [null],
      uitype: [null],
      javacode: [null],
      typerender: [null],
      // techstack: [null],
      html: [null],
      hedaer_id: [this.headerId],

    }); // component_button200
    // form code start
    this.extensionService.getJsonObjectsByFormCodeList(this.formcode).subscribe(data => {
      console.log(data);
      const jsonArray = data.map((str) => JSON.parse(str));
      this.additionalFieldsFromBackend = jsonArray;
      this.checkFormCode = this.additionalFieldsFromBackend.some(field => field.formCode === "Design_lbrary_formCode");
      console.log(this.checkFormCode);
      console.log(this.additionalFieldsFromBackend);
      if (this.additionalFieldsFromBackend && this.additionalFieldsFromBackend.length > 0) {
        this.additionalFieldsFromBackend.forEach(field => {
          if (field.formCode === this.formcode) {
            if (!this.entryForm.contains(field.extValue)) {
              // Add the control only if it doesn't exist in the form
              this.entryForm.addControl(field.extValue, this._fb.control(field.fieldValue));
            }
          }
        });
      }
    });
    console.log('form code ', this.entryForm.value);
    // form code end 
  }
  error;
  getData() {
    this.mainService.getAll(this.headerId).subscribe((data) => {
      console.log('get all ', data);
      // this.product = data;
      this.product = Array.isArray(data) ? data : [];

      if (this.product.length == 0) {
        this.error = "No Data Available"
      }
    }, (error) => {
      console.log(error);
      if (error) {
        this.error = "Server Error";
      }
    });
  }
  onEdit(row) {
    this.rowSelected = row;
    this.modalEdit = true;
  }
  onDelete(row) {
    this.rowSelected = row;
    this.modaldelete = true;
  }
  delete(id) {
    this.modaldelete = false;
    console.log("in delete  " + id);
    this.mainService.delete(id).subscribe(
      (data) => {
        console.log(data);
        this.ngOnInit();
        if (data) { this.toastr.success('Deleted successfully'); }
      });
  }
  onUpdate(id) {
    this.modalEdit = false;
    //console.log("in update");
    console.log("id  " + id);
    console.log(this.rowSelected);
    //console.log("out update");
    this.mainService.update(id, this.rowSelected).subscribe(
      (data) => {
        console.log(data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Update Successfully");
        }
        setTimeout(() => {
          this.ngOnInit();
        }, 500);

      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("update Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Updated");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Updated");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  onCreate() {
    this.modalAdd = false;
    this.mainService.create(this.entryForm.value).subscribe(
      (data) => {
        console.log(data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Successfully");
        }
        setTimeout(() => {
          this.ngOnInit();
        }, 500);

      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("Added Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Added");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Added");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  goToAdd(row) {
    this.modalAdd = true; this.submitted = false;

  }
  submitted = false;
  onSubmit() {
    console.log(this.entryForm.value);
    this.submitted = true;
    if (this.entryForm.invalid) {
      return;
    }
    this.onCreate();

  }

  rsModaldescription = false;
  goToReplaceStringdescription(row) {
    this.rowSelected = row; this.rsModaldescription = true;
  }



  rsModalhtmljson = false;
  goToReplaceStringhtmljson(row) {
    this.rowSelected = row; this.rsModalhtmljson = true;
  }

  rsModalcss = false;
  goToReplaceStringcss(row) {
    this.rowSelected = row; this.rsModalcss = true;
  }

  rsModaljavacode = false;
  goToReplaceStringjavacode(row) {
    this.rowSelected = row; this.rsModaljavacode = true;
  }

  // updateaction

  public htmlContent: string = '';
  public modalHtmlPreview: boolean = false;

  // openHtmlPreview(id: number): void {
  //   console.log('preview html start..');
  //   this.siteTreeService.generateHtmlwithcss(id).subscribe((response: any) => {
  //     this.htmlContent = response.msg; // assuming { html: "<div>..</div>" }
  //     console.log('html code ..', this.htmlContent);

  //     this.modalHtmlPreview = true;
  //   }, error => {
  //     this.htmlContent = '<p style="color:red;">Error loading HTML.</p>';
  //     this.modalHtmlPreview = true;
  //   });
  // }
  openHtmlPreview(id: number): void {
    console.log('preview html start..');

    this.siteTreeService.generateHtmlwithcss(id).subscribe((response: any) => {
      const bodyContent = response.msg || '<div>Empty</div>'; // fallback

      // Store raw content for download/copy
      const rawHtmlContent = bodyContent;

      // Full HTML with styles and controls
      const fullHtml = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>HTML Preview</title>
          <style>
        ${COMMON_CSS}
        
        /* Additional styles for controls */
        .preview-controls {
          position: fixed !important;
          top: 10px !important;
          right: 10px !important;
          background-color: rgba(255, 255, 255, 0.9) !important;
          border: 1px solid #ccc !important;
          border-radius: 4px !important;
          padding: 10px;
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2) !important;
          z-index: 1000 !important;
        }
        .preview-controls button {
          margin: 5px !important;
          padding: 8px 12px !important;
          background-color: #0072a3 !important;
          color: white !important;
          border: none !important;
          border-radius: 3px !important; 
          cursor: pointer !important;
          font-size: 14px !important;
        }
        .preview-controls button:hover {
          background-color: #005a80 !important;
        }
        .toast {
          position: fixed !important;
          top: 70px !important;
          right: 10px !important;
          padding: 10px 20px !important;
          background-color: #4CAF50 !important;
          color: white !important;
          border-radius: 4px !important;
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2) !important;
          opacity: 0 !important;
          transition: opacity 0.3s !important;
          z-index: 1001 !important;
        }
        .toast.show {
          opacity: 1 !important;
        }
        .html-source {
          display: none !important;
          margin-top: 20px !important;
          width: 100% !important;
          height: 300px !important;
          font-family: monospace !important;
          resize: vertical !important;
          white-space: pre !important;
          overflow: auto !important;
          background-color: #f5f5f5 !important;
          border: 1px solid #ddd !important;
          padding: 10px !important;
        }
        .show-source {
          display: block !important;
        }
          </style>
        </head>
        <body>
          <div class="preview-controls">
        <button id="download-btn">Download HTML</button>
        <button id="copy-btn">Copy to Clipboard</button>
        <button id="toggle-source-btn">View Source</button>
          </div>
          
          <div id="toast" class="toast">Copied to clipboard!</div>
          
          <div id="content-preview">
        ${bodyContent}
          </div>
          
          <pre id="html-source" class="html-source"></pre>
          
          <script>
        // Format HTML for display in the source view
        function formatHtml(html) {
          return html.replace(/&/g, '&amp;')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;');
        }
        
        // Store the raw HTML content
        const rawHtml = \`${rawHtmlContent.replace(/`/g, '\\`')}\`;
        
        // Download functionality with full HTML and CSS
        document.getElementById('download-btn').addEventListener('click', function() {
          const fullHtmlContent = \`
            <!DOCTYPE html>
            <html lang="en">
            <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Downloaded HTML</title>
          <style>
            ${COMMON_CSS}
          </style>
            </head>
            <body>
          \${rawHtml}
            </body>
            </html>
          \`;
  
          const blob = new Blob([fullHtmlContent], { type: 'text/html' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = 'preview-' + new Date().toISOString().slice(0, 10) + '.html';
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
        });
        
        // Copy to clipboard functionality
        document.getElementById('copy-btn').addEventListener('click', function() {
          navigator.clipboard.writeText(rawHtml).then(function() {
            const toast = document.getElementById('toast');
            toast.textContent = 'Copied to clipboard!';
            toast.classList.add('show');
            setTimeout(function() {
          toast.classList.remove('show');
            }, 2000);
          }).catch(function(err) {
            console.error('Could not copy text: ', err);
            const toast = document.getElementById('toast');
            toast.textContent = 'Failed to copy to clipboard';
            toast.style.backgroundColor = '#f44336';
            toast.classList.add('show');
            setTimeout(function() {
          toast.classList.remove('show');
            }, 2000);
          });
        });
        
        // Toggle source view
        document.getElementById('toggle-source-btn').addEventListener('click', function() {
          const sourceElem = document.getElementById('html-source');
          if (!sourceElem.classList.contains('show-source')) {
            sourceElem.textContent = rawHtml;
            sourceElem.innerHTML = formatHtml(rawHtml);
            sourceElem.classList.add('show-source');
            this.textContent = 'Hide Source';
          } else {
            sourceElem.classList.remove('show-source');
            this.textContent = 'View Source';
          }
        });
          </script>
        </body>
        </html>
      `;

      // Open the HTML in a new window/tab
      const newWindow = window.open('', '_blank');
      if (newWindow) {
        newWindow.document.write(fullHtml);
        newWindow.document.close();
      } else {
        // If popup is blocked, inform the user
        this.toastr.warning('Pop-up blocked. Please allow pop-ups for this site to see the preview.');
      }
    }, error => {
      // Handle error by opening a new window with error message
      const errorHtml = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Error Preview</title>
          <style>${COMMON_CSS}</style>
        </head>
        <body>
          <div style="padding: 20px; text-align: center;">
            <h2 style="color:red;">Error Loading Preview</h2>
            <p>The preview content could not be loaded. Error details:</p>
            <pre style="background-color: #f8f8f8; padding: 10px; border-radius: 5px; text-align: left;">${error ? JSON.stringify(error, null, 2) : 'Unknown error'}</pre>
          </div>
        </body>
        </html>
      `;

      const newWindow = window.open('', '_blank');
      if (newWindow) {
        newWindow.document.write(errorHtml);
        newWindow.document.close();
      } else {
        this.toastr.error('Error loading preview. Pop-up blocked. Please allow pop-ups for this site.');
      }
    });
  }
}





