import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { DynamicformService } from '../services/dynamicform.service';
import { Rn_Forms_Setup } from 'src/app/models/fnd/Rn_Forms_Setup';
import { Rn_Forms_Component_Setup } from 'src/app/models/fnd/Rn_Forms_Component_Setup';

import { ToastrService } from 'ngx-toastr';

@Component({
    selector: 'app-dynamic-form-viewer',
    templateUrl: './dynamic-form-viewer.component.html',
    styleUrls: ['./dynamic-form-viewer.component.scss']
})
export class DynamicFormViewerComponent implements OnInit {
    formId: number;
    formSetup: Rn_Forms_Setup;
    dynamicForm: FormGroup;
    loading = false;
    error = '';

    viewMode: 'list' | 'add' | 'edit' = 'list';
    gridColumns: any[] = [];
    gridData: any[] = [];

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private dynamicFormService: DynamicformService,
        private fb: FormBuilder,
        private toastr: ToastrService
    ) { }

    ngOnInit(): void {
        // Check Query Params first
        this.route.queryParams.subscribe(params => {
            const id = params['form_id'];
            if (id) {
                this.formId = Number(id);
                this.loadFormSetup(this.formId);
                return;
            }
        });

        // Check Route Params if Query Params didn't trigger
        this.route.params.subscribe(params => {
            const id = params['form_id'];
            if (id && !this.formId) {
                this.formId = Number(id);
                this.loadFormSetup(this.formId);
            } else if (!id && !this.formId) {
                this.error = "Form ID is missing.";
            }
        });
    }

    loadFormSetup(id: number) {
        this.loading = true;
        this.dynamicFormService.getById(id).subscribe(
            (data: Rn_Forms_Setup) => {
                this.formSetup = data;
                if (this.formSetup && this.formSetup.components) {
                    this.buildForm(this.formSetup.components);
                    this.setupGridColumns(this.formSetup.components);
                    this.loadData();
                } else {
                    this.error = "Form configuration is empty or invalid.";
                }
                this.loading = false;
            },
            (err) => {
                console.error(err);
                this.error = "Failed to load form setup from server.";
                this.loading = false;
            }
        );
    }

    setupGridColumns(components: Rn_Forms_Component_Setup[]) {
        this.gridColumns = [];
        // Always add ID column at the start (hidden or visible)
        // this.gridColumns.push({ field: 'id', header: 'ID', type: 'number' });

        let loopCount = 0;
        components.forEach((comp) => {
            loopCount++;
            const type = comp.type ? comp.type.toLowerCase() : '';

            // Exclude heavy text fields from grid
            if (!this.isTextArea(type)) {
                // Ensure we use the exact same control name as in the form group
                // The buildForm logic uses:
                let controlName = `comp${loopCount}`;
                if (type === 'textarea' || type === 'longtext' || type === 'long text') {
                    controlName = `comp_l${25 + loopCount}`;
                }

                this.gridColumns.push({
                    field: controlName, // Use the actual key bound to the data
                    header: comp.label,
                    type: type
                });
            }
        });
    }

    getStorageKey(): string {
        return `dynamic_form_data_${this.formId}`;
    }

    loadData() {
        // Use real API
        this.dynamicFormService.getTransactionsByFormId(this.formId).subscribe(
            (data: any[]) => {
                this.gridData = data || [];
            },
            (err) => {
                console.error(err);
                this.toastr.error('Failed to load data');
            }
        );
    }

    // saveData() {
    //     localStorage.setItem(this.getStorageKey(), JSON.stringify(this.gridData));
    // } // REMOVED

    buildForm(components: Rn_Forms_Component_Setup[]) {
        const group: any = {};
        let loopCount = 0;

        components.forEach((comp) => {
            loopCount++;
            const i = loopCount;

            let controlName = `comp${i}`;
            const type = comp.type ? comp.type.toLowerCase() : '';

            // Match the logic in Java backend for field naming
            if (type === 'textarea' || type === 'longtext' || type === 'long text') {
                controlName = `comp_l${25 + i}`;
            }

            const validators = [];
            if (comp.mandatory === 'true' || comp.mandatory === 'True' || comp.mandatory === '1') {
                validators.push(Validators.required);
            }

            const isDisabled = (comp.readonly === 'true' || comp.readonly === 'True' || comp.readonly === '1');

            let defaultValue = '';
            if ((type === 'textarea' || type === 'longtext' || type === 'long text') && comp.drop_values) {
                defaultValue = comp.drop_values;
            }

            group[controlName] = new FormControl({ value: defaultValue, disabled: isDisabled }, validators);

            // Save the key so html can use it
            (comp as any).generatedControlName = controlName;
        });

        // Add hidden ID control
        group['id'] = new FormControl(null);
        // Add hidden form_id control logic or just handle in submit
        // group['form_id'] = new FormControl(this.formId); 

        this.dynamicForm = new FormGroup(group);
    }

    goToAdd() {
        this.dynamicForm.reset();
        this.viewMode = 'add';
    }

    goToEdit(row: any) {
        this.viewMode = 'edit';
        this.dynamicForm.patchValue(row);
    }

    onDelete(row: any) {
        if (confirm('Are you sure you want to delete this record?')) {
            this.dynamicFormService.deleteTransaction(row.id).subscribe(
                (res) => {
                    this.toastr.success('Record deleted');
                    this.loadData(); // Refresh grid
                },
                (err) => {
                    console.error(err);
                    this.toastr.error('Failed to delete record');
                }
            );
        }
    }

    cancel() {
        this.viewMode = 'list';
        this.dynamicForm.reset();
    }

    onSubmit() {
        if (this.dynamicForm.valid) {
            const formValue = this.dynamicForm.value;

            // Ensure form_id is attached
            formValue.form_id = this.formId;

            if (this.viewMode === 'add') {
                this.dynamicFormService.createTransaction(formValue).subscribe(
                    (res) => {
                        this.toastr.success('Record Added');
                        this.viewMode = 'list';
                        this.loadData();
                    },
                    (err) => {
                        console.error(err);
                        this.toastr.error('Failed to add record');
                    }
                );
            } else {
                // Update existing
                const id = formValue.id; // ID should be in the form value if we patched it
                this.dynamicFormService.updateTransaction(id, this.formId, formValue).subscribe(
                    (res) => {
                        this.toastr.success('Record Updated');
                        this.viewMode = 'list';
                        this.loadData();
                    },
                    (err) => {
                        console.error(err);
                        this.toastr.error('Failed to update record');
                    }
                );
            }
        } else {
            Object.keys(this.dynamicForm.controls).forEach(field => {
                const control = this.dynamicForm.get(field);
                control.markAsTouched({ onlySelf: true });
            });
        }
    }

    // Type checkers
    isTextField(type: string): boolean {
        if (!type) return false;
        const t = type.toLowerCase();
        return t.includes('text') && !t.includes('area') && !t.includes('long') && !t.includes('date');
    }

    isTextArea(type: string): boolean {
        if (!type) return false;
        const t = type.toLowerCase();
        return t.includes('area') || t.includes('long');
    }

    isCheckbox(type: string): boolean {
        if (!type) return false;
        return type.toLowerCase().includes('checkbox');
    }

    isAutocomplete(type: string): boolean {
        if (!type) return false;
        return type.toLowerCase().includes('auto');
    }

    isDropdown(type: string): boolean {
        if (!type) return false;
        return type.toLowerCase().includes('drop') || type.toLowerCase().includes('select');
    }

    isDate(type: string): boolean {
        if (!type) return false;
        return type.toLowerCase().includes('date');
    }

    isToggle(type: string): boolean {
        if (!type) return false;
        return type.toLowerCase().includes('toggle');
    }

    getDropdownOptions(values: string): string[] {
        if (!values) return [];
        return values.split(',').map(v => v.trim());
    }
}
