package com.rit.ems.controller;

import com.rit.ems.model.User;
import com.rit.ems.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;

@RestController
@RequestMapping("/api/admin/users")
public class AdminController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @PostMapping
    public ResponseEntity<?> createUser(@RequestBody User userPayload) {
        Optional<User> existing = userRepository.findByEmailIgnoreCase(userPayload.getEmail());
        String role = userPayload.getRole() != null ? userPayload.getRole() : "FACULTY";
        String department = userPayload.getDepartment() != null ? userPayload.getDepartment() : 
                            ((role.equals("HOD") || role.equals("FACULTY")) ? "H&S Dept" : "");

        if (existing.isPresent()) {
            User existingUser = existing.get();
            if ("STUDENT".equals(existingUser.getRole())) {
                // Promote existing student to faculty/staff
                existingUser.setRole(role);
                existingUser.setDepartment(department);
                existingUser.setFullName(userPayload.getFullName());
                if (userPayload.getAssignedClubs() != null) {
                    existingUser.setAssignedClubs(userPayload.getAssignedClubs());
                }
                userRepository.save(existingUser);
                return ResponseEntity.ok(existingUser);
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("message", "User with this email already exists"));
            }
        }

        userPayload.setId(System.currentTimeMillis() + new Random().nextInt(1000));
        userPayload.setEmail(userPayload.getEmail().trim().toLowerCase());
        userPayload.setFullName(userPayload.getFullName().trim());
        userPayload.setRole(role);
        userPayload.setDepartment(department);
        if (userPayload.getAssignedClubs() == null) {
            userPayload.setAssignedClubs(new java.util.ArrayList<>());
        }

        userRepository.save(userPayload);
        return ResponseEntity.ok(userPayload);
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody Map<String, Object> payload) {
        Optional<User> userOpt = userRepository.findById(id);
        if (userOpt.isEmpty()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("message", "User not found"));
        }

        User user = userOpt.get();
        if (payload.containsKey("fullName")) user.setFullName((String) payload.get("fullName"));
        if (payload.containsKey("email")) user.setEmail(((String) payload.get("email")).trim().toLowerCase());
        if (payload.containsKey("role")) user.setRole((String) payload.get("role"));
        if (payload.containsKey("department")) user.setDepartment((String) payload.get("department"));
        if (payload.containsKey("isClubCoordinator")) user.setIsClubCoordinator((Boolean) payload.get("isClubCoordinator"));
        if (payload.containsKey("isPlacementStaff")) user.setIsPlacementStaff((Boolean) payload.get("isPlacementStaff"));
        if (payload.containsKey("isClassIncharge")) user.setIsClassIncharge((Boolean) payload.get("isClassIncharge"));
        if (payload.containsKey("classStrength")) user.setClassStrength(Integer.parseInt(payload.get("classStrength").toString()));
        if (payload.containsKey("inchargeClass")) user.setInchargeClass((String) payload.get("inchargeClass"));
        if (payload.containsKey("inchargeBatch")) user.setInchargeBatch((String) payload.get("inchargeBatch"));
        if (payload.containsKey("inchargeSection")) user.setInchargeSection((String) payload.get("inchargeSection"));
        if (payload.containsKey("year")) user.setYear((String) payload.get("year"));
        if (payload.containsKey("section")) user.setSection((String) payload.get("section"));
        if (payload.containsKey("regNo")) user.setRegNo((String) payload.get("regNo"));
        if (payload.containsKey("phone")) user.setPhone((String) payload.get("phone"));
        if (payload.containsKey("gender")) user.setGender((String) payload.get("gender"));
        if (payload.containsKey("collegeName")) user.setCollegeName((String) payload.get("collegeName"));
        if (payload.containsKey("assignedClubs")) {
            user.setAssignedClubs((List<String>) payload.get("assignedClubs"));
        }

        userRepository.save(user);
        return ResponseEntity.ok(user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        userRepository.deleteById(id);
        return ResponseEntity.ok(Map.of("message", "User deleted successfully"));
    }
}
