package com.realnet.OpenAi.Controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.realnet.OpenAi.Services.HtmlBuilder4;
import com.realnet.OpenAi.Services.HtmlBuilder5;
import com.realnet.OpenAi.Services.HtmlGenerTorService;
import com.realnet.dlf.Entity.Design_lbrary;
import com.realnet.dlf.Services.Design_lbraryService;
import com.realnet.dlf.Services.HtmlService;
import com.realnet.fnd.response.EntityResponse;

@RestController
@RequestMapping("/api/html")
public class HtmlGeneratorController {

	@Autowired
	private HtmlGenerTorService htmlGenerTorService;

	@Autowired
	private Design_lbraryService designLibraryService;

	@PostMapping
	public String generateHtmlFromJson(@RequestBody String jsonBody) {
		String json = htmlGenerTorService.generateHtmlFromJson(jsonBody);
		return json;
	}
//
//	@PostMapping("/generate")
//	public ResponseEntity<Map<String, String>> generateHtml(@RequestBody HtmlRequest request) {
//		String sectionType = request.getSectionType();
//		Map<String, Object> structure = request.getJsonStructure();
//
//		String html = HtmlRenderer.render(sectionType, structure);
//
//		Map<String, String> result = new HashMap<>();
//		result.put("html", html);
//		return ResponseEntity.ok(result);
//	}

//	@PostMapping("/generate")
//	public ResponseEntity<?> generateHtml(@RequestBody Map<String, Object> request) {
//		try {
//			Object jsonStructure = request.get("jsonStructure");
//
//			if (jsonStructure == null) {
//				return ResponseEntity.badRequest().body("Missing 'jsonStructure' in request.");
//			}
//
//			String html = HtmlBuilder5.buildHtml(jsonStructure);
////			String html = HtmlService.buildHtml(jsonStructure);
//			return ResponseEntity.ok(new EntityResponse(html));
//		} catch (Exception e) {
//			e.printStackTrace();
//			return ResponseEntity.status(500).body("⚠️ Failed to generate HTML due to server error.");
//		}
//	}

	@PostMapping("/generate")
	public ResponseEntity<?> generateHtml(@RequestBody Map<String, Object> jsonInput) {
		try {
			StringBuilder html = new StringBuilder();

			for (Map.Entry<String, Object> entry : jsonInput.entrySet()) {
				Map<String, Object> root = (Map<String, Object>) entry.getValue();
				root.put("element", entry.getKey()); // use key as tag like "section"
				html.append(HtmlBuilder5.buildHtml(root));
			}

			return ResponseEntity.ok(new EntityResponse(html.toString()));

		} catch (Exception e) {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
					.body("Error generating HTML: " + e.getMessage());
		}
	}

	@GetMapping("/generate/id/{id}")
	public ResponseEntity<?> generatehtml(@PathVariable int id) throws JsonMappingException, JsonProcessingException {

		ObjectMapper objectMapper = new ObjectMapper();

		Design_lbrary lbrary = designLibraryService.getdetailsbyId(id);
		String htmljson = lbrary.getHtmljson();
		Object jsonStructure = objectMapper.readValue(htmljson, Object.class);

		try {
//			Object jsonStructure = request.get("jsonStructure");

			if (jsonStructure == null) {
				return ResponseEntity.badRequest().body("Missing 'jsonStructure' in request.");
			}

			String html = HtmlBuilder4.buildHtml(jsonStructure);
//			String html = HtmlService.buildHtml(jsonStructure);
			return ResponseEntity.ok(new EntityResponse(html));
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.status(500).body("⚠️ Failed to generate HTML due to server error.");
		}
	}

	@GetMapping("/generate/html/id/{id}")
	public ResponseEntity<?> generatehtmlwithcss(@PathVariable int id)
			throws JsonMappingException, JsonProcessingException {

		ObjectMapper objectMapper = new ObjectMapper();

		Design_lbrary lbrary = designLibraryService.getdetailsbyId(id);
		String htmljson = lbrary.getHtmljson();
		String css = lbrary.getCss();

		try {
			if (htmljson == null || htmljson.trim().isEmpty()) {
				return ResponseEntity.badRequest().body("Missing 'htmljson' in request.");
			}

			// Convert JSON string to object (Map/List)
			Object jsonStructure = objectMapper.readValue(htmljson, Object.class);

			// Generate inner body HTML
			String bodyHtml = HtmlService.buildHtml(jsonStructure);

			if (bodyHtml.equalsIgnoreCase("<div></div>")) {
				bodyHtml = "<div>Empty Data</div>";

			}

			// Build full HTML page
//			StringBuilder finalHtml = new StringBuilder();
//			finalHtml.append("<!DOCTYPE html>\n");
//			finalHtml.append("<html lang=\"en\">\n");
//			finalHtml.append("<head>\n");
//			finalHtml.append("  <meta charset=\"UTF-8\">\n");
//			finalHtml.append("  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n");
//			finalHtml.append("  <title>Generated Page</title>\n");
//			finalHtml.append("  <style>\n").append(css).append("\n  </style>\n");
//			finalHtml.append("</head>\n");
//			finalHtml.append("<body>\n");
//			finalHtml.append(bodyHtml).append("\n");
//			finalHtml.append("</body>\n");
//			finalHtml.append("</html>");

			return ResponseEntity.ok(new EntityResponse(bodyHtml.toString()));
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.status(500).body("⚠️ Failed to generate HTML due to server error.");
		}
	}

}
