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.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Random;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> payload) {
        String email = payload.get("email");
        String password = payload.get("password");

        if (email == null || password == null) {
            return ResponseEntity.badRequest().body(Map.of("message", "Email and password are required"));
        }

        String emailLower = email.trim().toLowerCase();
        Optional<User> userOpt = userRepository.findByEmailIgnoreCase(emailLower);

        if (userOpt.isPresent()) {
            User user = userOpt.get();
            if (password.equals(user.getPassword())) {
                // Exclude password from return payload
                Map<String, Object> userData = new HashMap<>();
                userData.put("id", user.getId());
                userData.put("email", user.getEmail());
                userData.put("fullName", user.getFullName());
                userData.put("role", user.getRole());
                userData.put("department", user.getDepartment() != null ? user.getDepartment() : "N/A");
                userData.put("isClubCoordinator", user.getIsClubCoordinator());
                userData.put("isPlacementStaff", user.getIsPlacementStaff());
                userData.put("isClassIncharge", user.getIsClassIncharge());
                userData.put("classStrength", user.getClassStrength());
                userData.put("inchargeClass", user.getInchargeClass());
                userData.put("inchargeBatch", user.getInchargeBatch());
                userData.put("inchargeSection", user.getInchargeSection());
                userData.put("year", user.getYear());
                userData.put("section", user.getSection());
                userData.put("regNo", user.getRegNo());
                userData.put("phone", user.getPhone());
                userData.put("gender", user.getGender());
                userData.put("collegeName", user.getCollegeName());
                userData.put("assignedClubs", user.getAssignedClubs() != null ? user.getAssignedClubs() : new ArrayList<>());
                return ResponseEntity.ok(userData);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("message", "Invalid password for this registered email"));
            }
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("message", "Invalid email or passcode. Please check your credentials or register a new account."));
    }

    @PostMapping("/google-login")
    public ResponseEntity<?> googleLogin(@RequestBody Map<String, String> payload) {
        String email = payload.get("email");
        String fullName = payload.get("fullName");

        if (email == null) {
            return ResponseEntity.badRequest().body(Map.of("message", "Email is required"));
        }

        String emailLower = email.trim().toLowerCase();
        Optional<User> userOpt = userRepository.findByEmailIgnoreCase(emailLower);

        if (userOpt.isPresent()) {
            User user = userOpt.get();
            Map<String, Object> userData = convertUserToMap(user);
            return ResponseEntity.ok(userData);
        }

        // Auto-registration logic for RIT students
        boolean isRitEmail = emailLower.contains("@ritchennai.edu.in") || emailLower.contains(".ritchennai.edu.in");
        if (isRitEmail) {
            String rollNo = "";
            String rawDept = "CSE";
            
            // Try to match student patterns: student.240007@cse.ritchennai.edu.in
            if (emailLower.startsWith("student.")) {
                try {
                    String[] parts = emailLower.split("@");
                    rollNo = parts[0].substring(8); // extracts "240007"
                    rawDept = parts[1].split("\\.")[0]; // cse
                } catch (Exception e) {
                    rollNo = String.valueOf(100000 + new Random().nextInt(900000));
                }
            } else {
                rollNo = String.valueOf(100000 + new Random().nextInt(900000));
            }

            // Calculate joining year and academic year (current local time is 2026-06-30)
            int joinYear = 2000 + Integer.parseInt(rollNo.substring(0, Math.min(rollNo.length(), 2)));
            int currentYear = 2026;
            int academicYearOffset = 1; // Since month is June (June is >= 5)
            int yearIndex = currentYear - joinYear + academicYearOffset;
            String[] years = {"1st Year", "2nd Year", "3rd Year", "4th Year"};
            String calculatedYear = (yearIndex >= 1 && yearIndex <= 4) ? years[yearIndex - 1] : "3rd Year";

            // Map department
            String dept = rawDept.toUpperCase();
            if (dept.equals("AIDS")) dept = "AI&DS";
            else if (dept.equals("AIML")) dept = "AI&ML";
            else if (dept.equals("VLSI")) dept = "EE(VLSI)";
            else if (dept.equals("BIOTECH") || dept.equals("BIO-TECH")) dept = "BIOTECH";
            else if (dept.equals("H&S")) dept = "H&S Dept";

            User newUser = new User();
            newUser.setId(System.currentTimeMillis() + new Random().nextInt(1000));
            newUser.setEmail(emailLower);
            newUser.setPassword("google-oauth-placeholder");
            newUser.setFullName(fullName != null ? fullName : "Student " + rollNo);
            newUser.setRole("STUDENT");
            newUser.setDepartment(dept);
            newUser.setYear(calculatedYear);
            newUser.setSection("A");
            newUser.setRegNo(rollNo);
            newUser.setPhone("");
            newUser.setGender("Male");
            newUser.setCollegeName("Rajalakshmi Institute of Technology");
            newUser.setIsClubCoordinator(false);
            newUser.setIsPlacementStaff(false);
            newUser.setIsClassIncharge(false);
            newUser.setAssignedClubs(new java.util.ArrayList<>());

            userRepository.save(newUser);
            return ResponseEntity.ok(convertUserToMap(newUser));
        }

        // Register external students automatically
        User newUser = new User();
        newUser.setId(System.currentTimeMillis() + new Random().nextInt(1000));
        newUser.setEmail(emailLower);
        newUser.setPassword("google-oauth-placeholder");
        newUser.setFullName(fullName != null ? fullName : emailLower.split("@")[0]);
        newUser.setRole("STUDENT");
        newUser.setDepartment("Others");
        newUser.setYear("N/A");
        newUser.setSection("N/A");
        newUser.setRegNo("EXT-" + (10000 + new Random().nextInt(90000)));
        newUser.setPhone("");
        newUser.setGender("Male");
        newUser.setCollegeName("External Institution");
        newUser.setIsClubCoordinator(false);
        newUser.setIsPlacementStaff(false);
        newUser.setIsClassIncharge(false);
        newUser.setAssignedClubs(new java.util.ArrayList<>());

        userRepository.save(newUser);
        return ResponseEntity.ok(convertUserToMap(newUser));
    }

    @PostMapping("/signup")
    public ResponseEntity<?> signup(@RequestBody Map<String, Object> payload) {
        String email = (String) payload.get("email");
        if (email == null) {
            return ResponseEntity.badRequest().body(Map.of("message", "Email is required"));
        }

        String emailLower = email.trim().toLowerCase();
        if (userRepository.findByEmailIgnoreCase(emailLower).isPresent()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("message", "A user with this email already exists"));
        }

        User newUser = new User();
        newUser.setId(System.currentTimeMillis() + new Random().nextInt(1000));
        newUser.setEmail(emailLower);
        newUser.setPassword((String) payload.get("password"));
        newUser.setFullName((String) payload.get("fullName"));
        newUser.setRole("STUDENT");
        newUser.setDepartment(payload.get("department") != null ? (String) payload.get("department") : "CSE");
        newUser.setYear(payload.get("year") != null ? (String) payload.get("year") : "1st Year");
        newUser.setSection(payload.get("section") != null ? (String) payload.get("section") : "A");
        newUser.setRegNo((String) payload.get("regNo"));
        newUser.setPhone((String) payload.get("phone"));
        newUser.setGender(payload.get("gender") != null ? (String) payload.get("gender") : "Male");
        
        boolean isRitEmail = emailLower.contains("@ritchennai.edu.in") || emailLower.contains(".ritchennai.edu.in");
        newUser.setCollegeName(isRitEmail ? "Rajalakshmi Institute of Technology" : (String) payload.get("collegeName"));

        userRepository.save(newUser);
        return ResponseEntity.ok(convertUserToMap(newUser));
    }

    private Map<String, Object> convertUserToMap(User user) {
        Map<String, Object> userData = new HashMap<>();
        userData.put("id", user.getId());
        userData.put("email", user.getEmail());
        userData.put("fullName", user.getFullName());
        userData.put("role", user.getRole());
        userData.put("department", user.getDepartment() != null ? user.getDepartment() : "N/A");
        userData.put("isClubCoordinator", user.getIsClubCoordinator());
        userData.put("isPlacementStaff", user.getIsPlacementStaff());
        userData.put("isClassIncharge", user.getIsClassIncharge());
        userData.put("classStrength", user.getClassStrength());
        userData.put("inchargeClass", user.getInchargeClass());
        userData.put("inchargeBatch", user.getInchargeBatch());
        userData.put("inchargeSection", user.getInchargeSection());
        userData.put("year", user.getYear());
        userData.put("section", user.getSection());
        userData.put("regNo", user.getRegNo());
        userData.put("phone", user.getPhone());
        userData.put("gender", user.getGender());
        userData.put("collegeName", user.getCollegeName());
        userData.put("assignedClubs", user.getAssignedClubs() != null ? user.getAssignedClubs() : new ArrayList<>());
        return userData;
    }
}
