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

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

import org.springframework.core.io.ClassPathResource;
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.annotation.GetMapping;
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.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/pdf")
public class PdfController {

    // Endpoint to serve the initial template PDF
    @GetMapping(value = "/template", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<byte[]> getPdfTemplate() throws IOException {
        // Ensure your template PDF is in src/main/resources/static/
        ClassPathResource pdfFile = new ClassPathResource("static/template_form.pdf");
        if (!pdfFile.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("PDF template not found.".getBytes());
        }
        byte[] pdfBytes;
        try (InputStream is = pdfFile.getInputStream()) {
            pdfBytes = is.readAllBytes();
        }

        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
    @PostMapping(value = "/saveFilled", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Map<String, String>> saveFilledPdf(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("message", "No file uploaded."));
        }
        try {
            // Generate a unique filename and save to an 'uploads' directory
            String fileName = "filled_form_" + UUID.randomUUID().toString() + ".pdf";
            Path filePath = Paths.get("uploads", fileName);
            Files.createDirectories(filePath.getParent()); // Ensure directory exists
            Files.copy(file.getInputStream(), filePath);

            Map<String, String> response = new HashMap<>();
            response.put("message", "PDF saved successfully: " + fileName);
            response.put("filePath", filePath.toString());
            return ResponseEntity.ok(response);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                 .body(Map.of("message", "Failed to save PDF: " + e.getMessage()));
        }
    }

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