import {Component, inject, OnInit, signal} from '@angular/core';
import {Student} from '../models/student';
import {StudentService} from '../services/studentService';

@Component({
  selector: 'app-students',
  imports: [],
  templateUrl: './students.html',
  styleUrl: './students.css',
  standalone: true
})
class Students implements OnInit {

  private studentService = inject(StudentService);
  studentList = signal<Student[]>([]);

  // New variable to track which student is being edited
  selectedStudent: Student | null = null;

  ngOnInit(){
    this.getStudents();
  }

  // Method to be called when "Update" button is clicked in the list
  selectForUpdate(student: Student): void {
    this.selectedStudent = student;
    // This allows the UI to know which ID to use for the PATCH request
  }

  getStudents(): void {
    this.studentService.getStudents().subscribe({
      next: (newStudentList) => this.studentList.set(newStudentList),
      error: () => {},
      complete: () => {}
    });
  }

// English comment: Function to handle the creation of a student with Account and StudyGroup
  // Sending the data to match the backend Entity exactly
  add(firstname: string, lastname: string, email: string, telephone: string, accName: string, groupName: string, city: string): void {
    const newStudent: any = {
      firstname: firstname.trim(),
      lastname: lastname.trim(),
      email: email.trim(),
      telephone: telephone.trim(),

      account: accName.trim() ? {
        accountName: accName.trim(), // Changed from account_name to accountName
        password: 'defaultPassword'
      } : null,

      studyGroup: groupName.trim() ? {
        name: groupName.trim()
      } : null,

      address: city.trim() ? {
        city: city.trim()
      } : null
    };

    this.studentService.addStudent(newStudent).subscribe({
      next: () => {
        this.getStudents();
        this.selectedStudent = null;
      }
    });
  }

  delete(student: Student): void {
    this.studentService.deleteStudent(student).subscribe(() => {
      this.studentList.update(currentList => currentList.filter(c => c !== student));
    });
  }

  deleteAll(): void {
    this.studentService.deleteStudents().subscribe(() => {
      this.studentList.update(() => []);
    });
  }

// Updates both student details and linked ORM entities via a single PATCH request
  // Fixing the field name for the update operation as well
  update(firstname: string, lastname: string, email: string, telephone: string, accName: string, groupName: string, city: string): void {
    const id = this.selectedStudent?.id;
    if (!id) return;

    const updates: any = {
      firstname: firstname.trim(),
      lastname: lastname.trim(),
      email: email.trim(),
      telephone: telephone.trim(),

      account: accName.trim() ? {
        id: this.selectedStudent?.account?.id || null,
        accountName: accName.trim(), // Use accountName to match the DB/JSON
        password: this.selectedStudent?.account?.password || 'default'
      } : null,

      // Other fields remain the same as they already work
      studyGroup: groupName.trim() ? { name: groupName.trim() } : null,
      address: city.trim() ? { city: city.trim() } : null
    };

    this.studentService.patchStudent(id, updates).subscribe({
      next: () => {
        this.getStudents();
        this.selectedStudent = null;
      }
    });
  }

  // Method to trigger the full collection update (PUT All)
  // Add parameters to the method to capture current input values
  updateAll(firstname: string, lastname: string, email: string, telephone: string): void {
    const updatedData: Student = {
      firstname: firstname.trim(),
      lastname: lastname.trim(),
      email: email.trim(),
      telephone: telephone.trim(),
      // Keep existing ORM relations if we are editing a selected student
      account: this.selectedStudent?.account || null,
      address: this.selectedStudent?.address || null,
      studyGroup: this.selectedStudent?.studyGroup || null,
      teamList: this.selectedStudent?.teamList || []
    } as Student;

    const newList = [updatedData];

    // English comment: Send the new collection to the server and update the local state
    this.studentService.updateAllStudents(newList).subscribe({
      next: (newListFromServer: Student[]) => {
        // Update the signal to reflect changes in the UI immediately
        this.studentList.set(newListFromServer);
        console.log('Collection successfully replaced with new data');
      },
      error: (err) => console.error('PUT All request failed:', err)
    });
  }
  // Add to your Students class in students.ts

// English comment: Assign a simple account to the selected student
  addAccountToStudent(student: Student): void {
    const accountName = prompt("Enter account name:");
    if (!accountName) return;

    const updates = { account: { account_name: accountName, password: 'defaultPassword' } };

    this.studentService.patchStudent(student.id!, updates).subscribe({
      next: () => this.getStudents(), // Refresh list to see changes
      error: (err) => console.error('Failed to add account', err)
    });
  }

// English comment: Assign a simple team to the student
  addTeamToStudent(student: Student): void {
    const teamName = prompt("Enter team name:");
    if (!teamName) return;

    // We add to the existing teamList
    const updatedTeams = [...(student.teamList || []), { teamName: teamName }];

    this.studentService.patchStudent(student.id!, { teamList: updatedTeams }).subscribe({
      next: () => this.getStudents(),
      error: (err) => console.error('Failed to add team', err)
    });
  }

// English comment: Remove account by setting it to null via PATCH
  removeAccount(student: Student): void {
    this.studentService.patchStudent(student.id!, { account: null }).subscribe({
      next: () => this.getStudents()
    });
  }
  // English comment: Remove the student from their study group
  leaveGroup(student: Student): void {
    // We send null to clear the relationship in the database
    this.studentService.patchStudent(student.id!, { studyGroup: null }).subscribe({
      next: () => {
        console.log('Student left the group');
        this.getStudents(); // Refresh the list
      },
      error: (err) => console.error('Failed to leave group', err)
    });
  }
}

export default Students;















