package com.nebula.erp.product.controller;

import com.nebula.erp.product.document.TaxSwagger;
import com.nebula.erp.product.model.Tax;
import com.nebula.erp.product.requestmodel.TaxRequest;
import com.nebula.erp.product.service.TaxService;
import com.nebula.erp.product.utility.ApiResponse;
import com.nebula.erp.product.utility.CreateLogger;
import com.nebula.erp.product.utility.JwtRequestUtils;
import com.nebula.erp.product.utility.PermissionHelper;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/tax")
@Tag(name = "Tax APIs", description = "Endpoints for managing Tax")
@TaxSwagger.GlobalErrorResponse
public class TaxController {
    @Autowired
    private TaxService taxService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${users.api}")
    private String userApiUrl;

    @Value("${images.url}")
    private String imagesUrl;

    @Autowired
    private JwtRequestUtils jwtRequestUtils;

    @Autowired
    private PermissionHelper permissionHelper;

    @Autowired
    private CreateLogger createLogger;

    private static final String path = "/tax";

    public String fetchUserDetails(String userId) {
        HttpHeaders headers = jwtRequestUtils.getAuthorizationHeaders();

        // Create HttpEntity with headers
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        try {
            String create_by = "";
            ResponseEntity<Map> response = restTemplate.exchange(userApiUrl + userId, HttpMethod.GET, requestEntity,
                    Map.class);
            Map<String, Object> userDetails = response.getBody();

            // Extract user information from the response structure
            if (userDetails != null && "Success".equals(userDetails.get("status"))) {
                Map<String, Object> userItem = (Map<String, Object>) userDetails.get("data");
                create_by = userItem.get("firstName") + " " + userItem.get("lastName");
            } else {
                throw new IllegalArgumentException("Error getting user details!!");
            }
            return create_by;
        } catch (Exception e) {
            return "";
        }
    }

    @TaxSwagger.GetAllTaxesOperation
    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAllTax(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "search", required = false) String search) {
        try {
            // Check user permissions
            if (!permissionHelper.hasPermission("view-product")) {
                createLogger.createLogger("error", path, "GET",
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        "validation");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ApiResponse<>("error",
                        HttpStatus.FORBIDDEN.value(),
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        null));
            }

            Page<Tax> taxPage = taxService.getAllTax(page, size, search);

            Map<String, Object> pagination = new LinkedHashMap<>();
            pagination.put("current_page", taxPage.getNumber() + 1);
            pagination.put("per_page", taxPage.getSize());
            pagination.put("total", taxPage.getTotalElements());
            pagination.put("last_page", taxPage.getTotalPages());
            pagination.put("next_page_url", taxPage.hasNext() ? "/api/tax?page=" + (page + 1) + "&size=" + size : null);
            pagination.put("prev_page_url",
                    taxPage.hasPrevious() ? "/api/tax?page=" + (page - 1) + "&size=" + size : null);

            Map<String, String> columns = new LinkedHashMap<>();
            columns.put("id", "ID");
            columns.put("type", "TYPE");
            columns.put("rate", "RATE");
            columns.put("is_split", "GST SPLIT"); // NEW
            columns.put("cgst_rate", "CGST (50%)"); // NEW
            columns.put("sgst_rate", "SGST (50%)");
            columns.put("created_by", "CREATED BY");
            columns.put("created_at", "CREATED AT");
            columns.put("updated_at", "UPDATED AT");

            List<Map<String, Object>> taxResponses = taxPage.getContent().stream()
                    .map(this::prepareTaxResponse)
                    .collect(Collectors.toList());

            Map<String, Object> data = new LinkedHashMap<>();
            data.put("pagination", pagination);
            data.put("items", taxResponses);
            data.put("columns", columns);

            ApiResponse<Map<String, Object>> response = new ApiResponse<>("success", HttpStatus.OK.value(),
                    "Tax retrieved successfully", data);
            createLogger.createLogger("application", path, "GET", "Tax retrieved successfully", "");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            createLogger.createLogger("error", path, "GET", e.getMessage(), "runtime");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(new ApiResponse<>("error", HttpStatus.BAD_REQUEST.value(), e.getMessage(), null));
        }
    }

    @TaxSwagger.CreateTaxOperation
    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> createTax(@ModelAttribute TaxRequest taxRequest) {
        try {
            // Check user permissions
            if (!permissionHelper.hasPermission("create-product")) {
                createLogger.createLogger("error", path, "POST",
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        "validation");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ApiResponse<>("error",
                        HttpStatus.FORBIDDEN.value(),
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        null));
            }

            Tax newTax = taxService.createTax(taxRequest);
            Map<String, Object> taxResponse = prepareTaxResponse(newTax);
            ApiResponse<Map<String, Object>> apiResponse = new ApiResponse<>("success", HttpStatus.CREATED.value(),
                    "Tax created successfully", taxResponse);
            createLogger.createLogger("application", path, "POST", "Tax created successfully", "");
            return ResponseEntity.status(HttpStatus.CREATED).body(apiResponse);
        } catch (Exception e) {
            createLogger.createLogger("error", path, "POST", e.getMessage(), "runtime");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(new ApiResponse<>("error", HttpStatus.BAD_REQUEST.value(), e.getMessage(), null));
        }
    }

    @TaxSwagger.GetTaxByIdOperation
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTaxById(@PathVariable Long id) {
        try {
            // Check user permissions
            if (!permissionHelper.hasPermission("view-product")) {
                createLogger.createLogger("error", path, "GET",
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        "validation");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ApiResponse<>("error",
                        HttpStatus.FORBIDDEN.value(),
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        null));
            }

            // Fetch tax data and convert to DTO
            Optional<Tax> taxResponse = taxService.getTax(id);
            if (taxResponse.isPresent()) {
                Tax taxData = taxResponse.get();

                // Create a map to hold prescription data
                Map<String, Object> data = prepareTaxResponse(taxData);

                // Create response structure
                ApiResponse<Map<String, Object>> response = new ApiResponse<>("success", HttpStatus.OK.value(),
                        "Brand retrieved successfully", data);
                createLogger.createLogger("application", path, "GET", "Brand retrieved successfully", "");
                return ResponseEntity.ok(response);
            } else {
                createLogger.createLogger("error", path, "GET", "Tax not found", "runtime");
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>("error", HttpStatus.NOT_FOUND.value(), "Tax not found", null));
            }
        } catch (Exception e) {
            createLogger.createLogger("error", path, "GET", e.getMessage(), "runtime");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(new ApiResponse<>("error", HttpStatus.BAD_REQUEST.value(), e.getMessage(), null));
        }
    }

    @TaxSwagger.UpdateTaxOperation
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateTax(@PathVariable Long id,
            @ModelAttribute TaxRequest taxRequest) {
        try {
            // Check user permissions
            if (!permissionHelper.hasPermission("update-product")) {
                createLogger.createLogger("error", path, "PUT",
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        "validation");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ApiResponse<>("error",
                        HttpStatus.FORBIDDEN.value(),
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        null));
            }

            Tax updatedTax = taxService.updateTax(id, taxRequest);
            Map<String, Object> taxResponse = prepareTaxResponse(updatedTax);
            ApiResponse<Map<String, Object>> apiResponse = new ApiResponse<>("success", HttpStatus.OK.value(),
                    "Tax updated successfully", taxResponse);
            createLogger.createLogger("application", path, "PUT", "Tax updated successfully", "");
            return ResponseEntity.ok(apiResponse);
        } catch (Exception e) {
            createLogger.createLogger("error", path, "PUT", e.getMessage(), "runtime");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(new ApiResponse<>("error", HttpStatus.BAD_REQUEST.value(), e.getMessage(), null));
        }
    }

    @TaxSwagger.DeleteTaxOperation
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteTax(@PathVariable Long id) {
        try {
            // Check user permissions
            if (!permissionHelper.hasPermission("delete-product")) {
                createLogger.createLogger("error", path, "DELETE",
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        "validation");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ApiResponse<>("error",
                        HttpStatus.FORBIDDEN.value(),
                        "Forbidden: You do not have the required permission. Please contact the administration.",
                        null));
            }

            taxService.deleteTax(id);
            ApiResponse<Void> response = new ApiResponse<>("success", HttpStatus.OK.value(), "Tax deleted successfully",
                    null);
            createLogger.createLogger("application", path, "DELETE", "Tax deleted successfully", "");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            createLogger.createLogger("error", path, "DELETE", e.getMessage(), "runtime");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(new ApiResponse<>("error", HttpStatus.BAD_REQUEST.value(), e.getMessage(), null));
        }
    }

    private Map<String, Object> prepareTaxResponse(Tax taxData) {
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("id", taxData.getId());
        data.put("type", taxData.getType());
        data.put("rate", taxData.getRate());
        data.put("is_split", taxData.getIsSplit());

        // NEW: Include CGST/SGST breakdown if split is enabled
        if (Boolean.TRUE.equals(taxData.getIsSplit())) {
            Map<String, Object> breakdown = new LinkedHashMap<>();
            breakdown.put("cgst_rate", taxData.getCgstRate());
            breakdown.put("cgst_label", "CGST (50%)");
            breakdown.put("sgst_rate", taxData.getSgstRate());
            breakdown.put("sgst_label", "SGST (50%)");
            data.put("gst_breakdown", breakdown);
        }

        data.put("created_by", taxData.getCreated_by());
        data.put("created_at", String.valueOf(taxData.getCreated_at()));
        return data;
    }
}