package com.ffii.lioner.modules.lioner.template.web;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.ffii.core.response.DataRes;
import com.ffii.core.response.RecordsRes;
import com.ffii.core.utils.CriteriaArgsBuilder;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import com.ffii.core.exception.NotFoundException;
import com.ffii.core.utils.Params;

import com.ffii.lioner.modules.lioner.template.req.UpdateTemplateReq;
import com.ffii.lioner.modules.lioner.template.service.TemplateService;


@RestController
@RequestMapping("/template")
@CrossOrigin(origins = "", allowedHeaders = "")

public class TemplateController {

    private TemplateService templateService;

    public TemplateController(TemplateService templateService) {
        this.templateService = templateService;
    }

    // @GetMapping("/{id}")
	// public List<Map<String, Object>> get(@PathVariable Long id) {
	// 	return Map.of(
	// 			Params.DATA, templateService.findByClientId(id).orElseThrow(NotFoundException::new)
	// 		);
	// }

    @GetMapping
	public RecordsRes<Map<String, Object>> list(HttpServletRequest request) throws ServletRequestBindingException {
		return new RecordsRes<>(templateService.list(
            CriteriaArgsBuilder.withRequest(request)
                        .addStringLike("name")
                        .addDate("createDateFrom")
                        .addDate("createDateTo")
                        .addStringLike("remarks")
						.build()));
	}

    @GetMapping("/{id}")
	public Map<String, Object> get(@PathVariable Long id) {
        return templateService.loadTemplate(id);
	}
    
    // Endpoint to receive the filled PDF from the frontend
    @Transactional(isolation = Isolation.SERIALIZABLE, rollbackFor = Exception.class, readOnly = false)
    @PostMapping(value = "/save", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Map<String, Object> saveTemplatePdf(@RequestParam("record") String recordJson,
            @RequestParam("file") MultipartFile file, @RequestParam("newUpload") Boolean newUpload) {
        
        return Map.of(
				Params.DATA,templateService.saveOrUpdate(recordJson, file, newUpload)
			);
    }

    // Optional: Endpoint to receive just the form data (e.g., JSON)
    @PostMapping("/saveFormData")
    public ResponseEntity<Map<String, String>> saveFormData(@RequestBody Map<String, Object> formData) {
        System.out.println("Received form data: " + formData);
        Map<String, String> response = new HashMap<>();
        response.put("message", "Form data received and processed successfully.");
        return ResponseEntity.ok(response);
    }
}
