package com.walkguide.controller;

import com.walkguide.dto.ApiResponse;
import com.walkguide.dto.request.*;
import com.walkguide.dto.response.*;
import com.walkguide.security.SecurityHelper;
import com.walkguide.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/guardian")
@RequiredArgsConstructor
public class GuardianController {

    private final GuardianDashboardService dashboardService;
    private final LocationService locationService;
    private final ActivityLogService activityLogService;
    private final ObstacleLogService obstacleLogService;
    private final NotificationService notificationService;
    private final SosService sosService;
    private final AiConfigService aiConfigService;
    private final VoiceCommandService voiceCommandService;
    private final HardwareShortcutService hardwareShortcutService;
    private final GeofenceService geofenceService;
    private final UserSettingsService userSettingsService;

    @GetMapping("/dashboard")
    public ResponseEntity<ApiResponse<DashboardResponse>> dashboard() {
        return ResponseEntity.ok(ApiResponse.ok(
                dashboardService.getDashboard(SecurityHelper.getCurrentUserId()),
                "Dashboard Guardian"));
    }

    @GetMapping("/user-location")
    public ResponseEntity<ApiResponse<LocationResponse>> userLocation() {
        return ResponseEntity.ok(ApiResponse.ok(
                locationService.getLastLocationForGuardian(SecurityHelper.getCurrentUserId()).orElse(null),
                "Lokasi terakhir user"));
    }

    @GetMapping("/location-history")
    public ResponseEntity<ApiResponse<Page<LocationResponse>>> locationHistory(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size) {
        // Guardian lihat location history user yang dipair
        Long guardianId = SecurityHelper.getCurrentUserId();
        // Perlu ambil userId dulu — delegasikan ke service
        return ResponseEntity.ok(ApiResponse.ok(
                locationService.getLocationHistory(guardianId,
                        PageRequest.of(page, size, Sort.by("createdAt").descending())),
                "Riwayat lokasi"));
    }

    @GetMapping("/activity-logs")
    public ResponseEntity<ApiResponse<Page<ActivityLogResponse>>> activityLogs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        return ResponseEntity.ok(ApiResponse.ok(
                activityLogService.getLogsForGuardian(SecurityHelper.getCurrentUserId(),
                        PageRequest.of(page, size)), "Log aktivitas user"));
    }

    @GetMapping("/obstacle-logs")
    public ResponseEntity<ApiResponse<Page<ObstacleLogResponse>>> obstacleLogs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        return ResponseEntity.ok(ApiResponse.ok(
                obstacleLogService.getObstacleLogs(SecurityHelper.getCurrentUserId(),
                        PageRequest.of(page, size)), "Log obstacle user"));
    }

    @PostMapping("/notifications/send")
    public ResponseEntity<ApiResponse<NotificationResponse>> sendNotif(
            @RequestBody SendNotificationRequest req) {
        return ResponseEntity.ok(ApiResponse.ok(
                notificationService.sendNotification(SecurityHelper.getCurrentUserId(), req),
                "Notifikasi terkirim"));
    }

    @GetMapping("/sos-events")
    public ResponseEntity<ApiResponse<Page<SosEventResponse>>> sosEvents(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        return ResponseEntity.ok(ApiResponse.ok(
                sosService.getSosEventsForGuardian(SecurityHelper.getCurrentUserId(),
                        PageRequest.of(page, size)), "SOS events"));
    }

    @PutMapping("/sos/{id}/acknowledge")
    public ResponseEntity<ApiResponse<SosEventResponse>> acknowledgeSos(@PathVariable Long id) {
        return ResponseEntity.ok(ApiResponse.ok(
                sosService.acknowledgeSos(SecurityHelper.getCurrentUserId(), id),
                "SOS diakui"));
    }

    @GetMapping("/ai-config")
    public ResponseEntity<ApiResponse<AiConfigResponse>> getAiConfig() {
        // Guardian lihat config user yang dipair
        return ResponseEntity.ok(ApiResponse.ok(
                aiConfigService.getConfig(SecurityHelper.getCurrentUserId()),
                "AI config"));
    }

    @PutMapping("/ai-config")
    public ResponseEntity<ApiResponse<AiConfigResponse>> updateAiConfig(
            @RequestBody AiConfigUpdateRequest req) {
        return ResponseEntity.ok(ApiResponse.ok(
                aiConfigService.updateConfigByGuardian(SecurityHelper.getCurrentUserId(), req),
                "AI config diperbarui"));
    }

    @GetMapping("/voice-commands")
    public ResponseEntity<ApiResponse<?>> getVoiceCommands() {
        return ResponseEntity.ok(ApiResponse.ok(
                voiceCommandService.getAll(SecurityHelper.getCurrentUserId()),
                "Voice commands"));
    }

    @PutMapping("/voice-commands")
    public ResponseEntity<ApiResponse<VoiceCommandResponse>> updateVoiceCommand(
            @RequestBody VoiceCommandUpdateRequest req) {
        return ResponseEntity.ok(ApiResponse.ok(
                voiceCommandService.updateByGuardian(SecurityHelper.getCurrentUserId(), req),
                "Voice command diperbarui"));
    }

    @GetMapping("/shortcuts")
    public ResponseEntity<ApiResponse<?>> getShortcuts() {
        return ResponseEntity.ok(ApiResponse.ok(
                hardwareShortcutService.getAll(SecurityHelper.getCurrentUserId()),
                "Hardware shortcuts"));
    }

    @GetMapping("/geofence")
    public ResponseEntity<ApiResponse<GeofenceResponse>> getGeofence() {
        return ResponseEntity.ok(ApiResponse.ok(
                geofenceService.getConfig(SecurityHelper.getCurrentUserId()),
                "Geofence config"));
    }

    @PutMapping("/geofence")
    public ResponseEntity<ApiResponse<GeofenceResponse>> updateGeofence(
            @RequestBody GeofenceConfigRequest req) {
        return ResponseEntity.ok(ApiResponse.ok(
                geofenceService.updateConfig(SecurityHelper.getCurrentUserId(), req),
                "Geofence diperbarui"));
    }

    @GetMapping("/user-settings")
    public ResponseEntity<ApiResponse<UserSettingsResponse>> getUserSettings() {
        return ResponseEntity.ok(ApiResponse.ok(
                userSettingsService.getSettings(SecurityHelper.getCurrentUserId()),
                "User settings"));
    }

    @PutMapping("/user-settings")
    public ResponseEntity<ApiResponse<UserSettingsResponse>> updateUserSettings(
            @RequestBody UserSettingsUpdateRequest req) {
        return ResponseEntity.ok(ApiResponse.ok(
                userSettingsService.updateSettings(SecurityHelper.getCurrentUserId(), req),
                "User settings diperbarui"));
    }
}
