import { Component, inject, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Store } from '@ngrx/store';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { InputTextModule } from 'primeng/inputtext';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { SelectModule } from 'primeng/select';
import { MultiSelectModule } from 'primeng/multiselect';
import { ToggleSwitchModule } from 'primeng/toggleswitch';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { PasswordModule } from 'primeng/password';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent, DataTableComponent, FormDialogComponent, TableColumn } from '../../shared';
import {
  UsersActions,
  selectAllUsers,
  selectUsersLoading,
  selectUsersSaving,
  selectUsersError,
  BranchesActions,
  selectAllBranches,
} from '../../core/store';
import { UserListItem } from '../../core/models/user.model';

@Component({
  selector: 'app-users',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TranslateModule,
    TableModule,
    ButtonModule,
    InputTextModule,
    TagModule,
    ToastModule,
    SelectModule,
    MultiSelectModule,
    ToggleSwitchModule,
    ConfirmDialogModule,
    PasswordModule,
    PageHeaderComponent,
    DataTableComponent,
    FormDialogComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './users.component.html',
  styleUrl: './users.component.scss',
})
export class UsersComponent implements OnInit {
  readonly columns: TableColumn[] = [
    { field: 'name_ar', header: 'USERS.NAME', sortable: true },
    { field: 'email', header: 'USERS.EMAIL', sortable: true },
    { field: 'role', header: 'USERS.ROLE' },
    { field: 'branches', header: 'USERS.BRANCHES' },
    { field: 'locale', header: 'USERS.LOCALE' },
    { field: 'status', header: 'COMMON.STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  private fb = inject(FormBuilder);
  private store = inject(Store);
  private messageService = inject(MessageService);
  private translate = inject(TranslateService);
  private confirmationService = inject(ConfirmationService);

  users$ = this.store.select(selectAllUsers);
  loading$ = this.store.select(selectUsersLoading);
  saving$ = this.store.select(selectUsersSaving);
  error$ = this.store.select(selectUsersError);
  branches$ = this.store.select(selectAllBranches);

  dialogVisible = signal(false);
  editingUser = signal<UserListItem | null>(null);
  userForm!: FormGroup;

  localeOptions = [
    { label: 'العربية', value: 'ar' },
    { label: 'English', value: 'en' },
  ];

  ngOnInit(): void {
    this.initForm();
    this.store.dispatch(UsersActions.loadUsers({}));
    this.store.dispatch(BranchesActions.loadBranches({}));
  }

  roleOptions = [
    { label: 'Owner', value: 'owner' },
    { label: 'Admin', value: 'admin' },
    { label: 'Manager', value: 'manager' },
    { label: 'Accountant', value: 'accountant' },
    { label: 'Cashier', value: 'cashier' },
    { label: 'Employee', value: 'employee' },
  ];

  private initForm(): void {
    this.userForm = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: [''],
      email: ['', [Validators.required, Validators.email]],
      password: [''],
      password_confirmation: [''],
      phone: [''],
      locale: ['ar'],
      branch_ids: [[]],
      role: ['admin'],
      is_active: [true],
    });
  }

  openNew(): void {
    this.editingUser.set(null);
    this.userForm.reset({ locale: 'ar', is_active: true, role: 'admin', branch_ids: [] });
    this.userForm.get('password')?.setValidators([Validators.required, Validators.minLength(6)]);
    this.userForm.get('password')?.updateValueAndValidity();
    this.dialogVisible.set(true);
  }

  editUser(user: UserListItem): void {
    this.editingUser.set(user);
    this.userForm.patchValue({
      name_ar: user.name_ar,
      name_en: user.name_en,
      email: user.email,
      phone: user.phone,
      locale: user.locale,
      branch_ids: (user.branches || []).map(b => b.id),
      role: user.roles?.length ? user.roles[0] : 'employee',
      is_active: user.is_active,
    });
    this.userForm.get('password')?.clearValidators();
    this.userForm.get('password')?.updateValueAndValidity();
    this.dialogVisible.set(true);
  }

  getRoleSeverity(role: string): 'success' | 'info' | 'warn' | 'danger' | 'secondary' | 'contrast' {
    switch (role) {
      case 'owner': return 'contrast';
      case 'admin': return 'danger';
      case 'manager': return 'warn';
      case 'accountant': return 'info';
      case 'cashier': return 'success';
      default: return 'secondary';
    }
  }

  deleteUser(user: UserListItem): void {
    this.confirmationService.confirm({
      message: `Delete user "${user.name}"?`,
      header: 'Confirm Delete',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.store.dispatch(UsersActions.deleteUser({ id: user.id }));
        const sub = this.store.select(selectUsersSaving).subscribe((saving) => {
          if (!saving) {
            sub.unsubscribe();
            this.store.select(selectUsersError).subscribe((error) => {
              if (error) {
                this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: error });
              } else {
                this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: 'User deleted successfully' });
              }
            }).unsubscribe();
          }
        });
      },
    });
  }

  onSave(): void {
    if (this.userForm.valid) {
      const formValue = { ...this.userForm.value };
      formValue.name = formValue.name_ar;
      if (this.editingUser()) {
        // Only send password if user filled it in
        if (formValue.password) {
          formValue.password_confirmation = formValue.password;
        } else {
          delete formValue.password;
          delete formValue.password_confirmation;
        }
        this.store.dispatch(UsersActions.updateUser({
          id: this.editingUser()!.id,
          user: formValue,
        }));
      } else {
        formValue.password_confirmation = formValue.password;
        this.store.dispatch(UsersActions.createUser({ user: formValue }));
      }

      const sub = this.store.select(selectUsersSaving).subscribe((saving) => {
        if (!saving) {
          sub.unsubscribe();
          this.store.select(selectUsersError).subscribe((error) => {
            if (error) {
              this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: error });
            } else {
              this.dialogVisible.set(false);
              this.messageService.add({
                severity: 'success',
                summary: this.translate.instant('COMMON.SUCCESS'),
                detail: this.editingUser() ? 'User updated successfully' : 'User created successfully',
              });
            }
          }).unsubscribe();
        }
      });
    } else {
      this.userForm.markAllAsTouched();
    }
  }

  retry(): void {
    this.store.dispatch(UsersActions.loadUsers({ forceReload: true }));
  }
}
