package br.gov.sigefp.rh.api;

import br.gov.sigefp.rh.api.dto.AgentImportResultDTO;
import br.gov.sigefp.rh.service.AgentImportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/rh/agents/imports")
@RequiredArgsConstructor
@Slf4j
public class ImportController {

    private final AgentImportService importService;

    @PostMapping("/excel")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<AgentImportResultDTO> importAgents(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(
                    AgentImportResultDTO.builder()
                            .errors(java.util.List.of("Arquivo está vazio."))
                            .build());
        }

        log.info("Iniciando importação de agentes a partir do arquivo: {}", file.getOriginalFilename());
        AgentImportResultDTO result = importService.importAgents(file);

        return ResponseEntity.ok(result);
    }

    @GetMapping("/template")
    public ResponseEntity<byte[]> getTemplate() throws java.io.IOException {
        try (org.apache.poi.xssf.usermodel.XSSFWorkbook workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook()) {
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet("Agentes");

            // Header style
            org.apache.poi.ss.usermodel.CellStyle headerStyle = workbook.createCellStyle();
            org.apache.poi.ss.usermodel.Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(org.apache.poi.ss.usermodel.IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND);

            // Date cell style (formato texto para evitar conversão automática do Excel)
            org.apache.poi.ss.usermodel.CellStyle textStyle = workbook.createCellStyle();
            org.apache.poi.ss.usermodel.DataFormat textFormat = workbook.createDataFormat();
            textStyle.setDataFormat(textFormat.getFormat("@")); // Formato texto

            org.apache.poi.ss.usermodel.Row header = sheet.createRow(0);

            String[] columns = {
                    "NOME", "NIF", "MATRICULA", "BI", "DATA_NASCIMENTO", "SEXO", "ESTADO_CIVIL",
                    "HABILITACAO_LITERARIA", "CATEGORIA_CODIGO", "UNIDADE_ORG_CODIGO",
                    "NOMEACAO", "TIPO_CONTRATO", "DATA_INICIO_CONTRATO", "DATA_FIM_CONTRATO",
                    "BANCO_CODIGO", "IBAN"
            };

            // Colunas de data: 4 (DATA_NASCIMENTO), 10 (NOMEACAO), 12 (DATA_INICIO), 13
            // (DATA_FIM)
            int[] dateColumns = { 4, 10, 12, 13 };

            for (int i = 0; i < columns.length; i++) {
                org.apache.poi.ss.usermodel.Cell cell = header.createCell(i);
                cell.setCellValue(columns[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 4500); // Largura padrão
            }

            // Formatar colunas de data como texto para toda a coluna
            for (int dateCol : dateColumns) {
                sheet.setDefaultColumnStyle(dateCol, textStyle);
            }

            // Sample Row
            org.apache.poi.ss.usermodel.Row sample = sheet.createRow(1);
            sample.createCell(0).setCellValue("Exemplo João Silva");
            sample.createCell(1).setCellValue("999999999");
            sample.createCell(2).setCellValue("MAT-001");
            sample.createCell(3).setCellValue("12345678");

            // Datas como texto para evitar problemas de formatação
            org.apache.poi.ss.usermodel.Cell dataNasc = sample.createCell(4);
            dataNasc.setCellValue("01/01/1980");
            dataNasc.setCellStyle(textStyle);

            sample.createCell(5).setCellValue("M");
            sample.createCell(6).setCellValue("SOLTEIRO");
            sample.createCell(7).setCellValue("LICENCIATURA");
            sample.createCell(8).setCellValue("");
            sample.createCell(9).setCellValue("");

            org.apache.poi.ss.usermodel.Cell nomeacao = sample.createCell(10);
            nomeacao.setCellValue("15/01/2024");
            nomeacao.setCellStyle(textStyle);

            sample.createCell(11).setCellValue("NOMEACAO");

            org.apache.poi.ss.usermodel.Cell dataInicio = sample.createCell(12);
            dataInicio.setCellValue("01/01/2024");
            dataInicio.setCellStyle(textStyle);

            org.apache.poi.ss.usermodel.Cell dataFim = sample.createCell(13);
            dataFim.setCellValue("");
            dataFim.setCellStyle(textStyle);

            sample.createCell(14).setCellValue("");
            sample.createCell(15).setCellValue("");

            java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
            workbook.write(out);

            return ResponseEntity.ok()
                    .header(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=template_agentes.xlsx")
                    .contentType(org.springframework.http.MediaType
                            .parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .body(out.toByteArray());
        }
    }
}
