import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { SequenceService } from 'src/app/services/api/sequence.service';
import { ExcelService } from 'src/app/services/excel.service';
import * as moment from 'moment';
import { HttpErrorResponse } from '@angular/common/http';
import { ThemeService } from 'src/app/services/theme.service';

@Component({
  selector: 'app-sequencegenarator',
  templateUrl: './sequencegenarator.component.html',
  styleUrls: ['./sequencegenarator.component.scss']
})
export class SequencegenaratorComponent implements OnInit {
  loading = false;
  selected: any[] = [];
  workflow_data;
  rowSelected: any = {};
  modaldelete = false;
  error;
  alldata = [];
  modaladd = false;
  modaledit = false;
  submitted = false;
  filterText = '';
  // Changed default view to cards
  viewMode: 'table' | 'cards' = 'cards';

  public entryForm: FormGroup;
  
  constructor(
    private seqservice: SequenceService, 
    private router: Router, 
    private toastr: ToastrService, 
    private _fb: FormBuilder,
    private route: ActivatedRoute, 
    private excel: ExcelService, 
    private themeService: ThemeService
  ) { }

  ngOnInit(): void {
    // Ensure theme variables are applied to the view
    this.themeService.currentTheme$.subscribe(() => {
      // CSS variables are updated globally; no extra handling needed here
    });
    
    this.getall();
    this.entryForm = this._fb.group({
      prefix: [null, Validators.required],
      sequence_size: [null],
      suffix: [null],
      starting_no: [null],
      seperator: [null],
      sequence_name: [null, Validators.required],
      sequence_code: [null],
      demonstration: [null],
      current_no: [null]
    });
  }
  
  // Stats & filtering helpers for UI only
  get totalSequences(): number { 
    return ((this.alldata as unknown as any[]) || []).length; 
  }
  
  get filteredSequences(): any[] {
    const items: any[] = (this.alldata as unknown as any[]) || [];
    const text = (this.filterText || '').toLowerCase();
    if (!text) { return items; }
    
    // Search across all relevant fields
    return items.filter(s => (
      (s?.sequence_name || '').toLowerCase().includes(text) ||
      (s?.prefix || '').toLowerCase().includes(text) ||
      (s?.sequence_code || '').toLowerCase().includes(text) ||
      (s?.suffix || '').toLowerCase().includes(text) ||
      (s?.seperator || '').toLowerCase().includes(text) ||
      (s?.sequence_size?.toString() || '').includes(text) ||
      (s?.starting_no?.toString() || '').includes(text) ||
      (s?.current_no?.toString() || '').includes(text) ||
      (s?.demonstration || '').toLowerCase().includes(text)
    ));
  }
  
  setViewMode(mode: 'table' | 'cards') { 
    this.viewMode = mode; 
  }
  
  getall() {
    this.seqservice.getAll().subscribe((data) => {
      console.log(data);
      this.alldata = data;

      if (this.alldata.length == 0) {
        console.log('zero data ');
        this.error = "No data Available!"
      }
    }, (error) => {
      console.log(error);
      if (error) {
        this.error = "No data Available OR server Error";
      }
    })
  }

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

  onCreate() {
    this.modaladd = false;
    this.seqservice.create(this.entryForm.value).subscribe(
      (data) => {
        console.log(data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Succesfully");
          this.ngOnInit();
        }
      }, (error) => {
        if (error.status >= 200 && error.status <= 299) {
          this.toastr.success("Added Succesfully");
          this.ngOnInit();
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Added");
          this.ngOnInit();
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Server Error");
          this.ngOnInit();
        }
      });
  }

  goToAdd() {
    this.modaladd = true;
    this.submitted = false;
    // Reset form
    this.entryForm.reset();
  }

  onExport() {
    this.excel.exportAsExcelFile(this.alldata, 'sequence_',
      moment().format('YYYYMMDD_HHmmss'))
  }

  goToEdit(row) {
    this.rowSelected = { ...row }; // Create a copy to avoid direct binding issues
    console.log(row)
    this.modaledit = true;
  }
  
  onDelete(row) {
    this.rowSelected = row;
    this.modaldelete = true;
  }

  delete(id) {
    this.modaldelete = false;
    console.log("in delete  " + id);
    this.seqservice.delete(id).subscribe((data) => {
      console.log(data);
      if (data == null || data.status >= 200 && data.status <= 299) {
        this.toastr.success('Deleted successfully');
        this.ngOnInit();
      }
    },
      (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          this.toastr.success('Deleted successfully');
          this.ngOnInit();
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error('Not Deleted Data Getting Some Error');
          this.ngOnInit();
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error('Server Error');
          this.ngOnInit();
        }
      });
  }
  
  onUpdate(id) {
    this.modaledit = false;
    this.seqservice.update(id, this.rowSelected).subscribe((data) => {
      console.log(data);
      if (data || data.status >= 200 && data.status <= 299) {
        this.toastr.success("Update Succesfully");
        this.ngOnInit();
      }
    }, (error: HttpErrorResponse) => {
      console.log(error?.message);
      if (error.status >= 200 && error.status <= 299) {
        this.toastr.success("Update Succesfully");
        this.ngOnInit();
      }
      if (error.status >= 400 && error.status <= 499) {
        this.toastr.error("Not Update");
        this.ngOnInit();
      }
      if (error.status >= 500 && error.status <= 599) {
        this.toastr.error("Server Error");
        this.ngOnInit();
      }
    });
  }
}