package com.ffii.lioner.modules.lioner.pdf.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.pdf.req.UpdatePdfReq;
import com.ffii.lioner.modules.lioner.pdf.service.PdfService;


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

public class PdfController {

    private PdfService pdfService;

    public PdfController(PdfService pdfService) {
        this.pdfService = pdfService;
    }

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

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

    @GetMapping("/{id}")
	public Map<String, Object> get(@PathVariable Long id) {
        return pdfService.loadPDF(id);
        // return Map.of(
		// 		Params.DATA, pdfService.loadPDF(id)
		// 	);
	}

    // Endpoint to serve the initial template PDF
    @GetMapping(value = "/template", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<byte[]> getPdfTemplate() throws IOException {
        
        byte[] pdfBytes = pdfService.getTemplateForm();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("inline", "template_form.pdf");
        headers.setContentType(MediaType.APPLICATION_PDF);
        return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
    }

    // 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> saveFilledPdf(@RequestParam("pdf") @Valid UpdatePdfReq req, @RequestParam("file") MultipartFile file) {
    // public Map<String, Object> saveFilledPdf(@RequestParam("record") UpdatePdfReq req, @RequestParam("file") MultipartFile file) {
    public Map<String, Object> saveFilledPdf(@RequestParam("record") String recordJson, @RequestParam("file") MultipartFile file) {
        return Map.of(
				Params.DATA,pdfService.saveOrUpdate(recordJson, file)
			);
    }

    // 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);
    }
}
