package com.project.whatsappchatbot.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.whatsappchatbot.controller.BotController.WhatsAppBotController;
import com.project.whatsappchatbot.model.*;
import com.project.whatsappchatbot.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.*;

import javax.annotation.PostConstruct;

import static com.project.whatsappchatbot.controller.BotController.WhatsAppBotController.WHATSAPP_API_URL;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/api")
public class RazorpayController {

    @Autowired
    private InvoiceRepository invoiceRepository;

    @Autowired
    private ComplaintRepository complaintRepository;
    @Autowired
    private HelpSupportRepository helpSupportRepository;

    @Autowired
    private PaymentLinkRepository paymentLinkRepository;
    private static final RestTemplate restTemplate = new RestTemplate();
    @Autowired
    private MechanicRepository mechanicRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ChatMessageRepository chatMessageRepository;

    @Autowired
    private FeedbackRepository feedbackRepository;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private ServiceRepository serviceRepository;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Value("${phone.notification.numbers}")
    private String notificationNumbers;

    private List<String> notificationNumberList;

    @PostConstruct
    public void initPhonesNotificationNumber() {
        if (notificationNumbers != null && !notificationNumbers.isBlank()) {
        	notificationNumberList = Arrays.asList(notificationNumbers.split(","));
        } else {
            notificationNumberList = new ArrayList<>();
        }
    }


    public void sendTextMessage(String recipientNumber, String text) {
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("messaging_product", "whatsapp");
            payload.put("recipient_type", "individual");
            payload.put("to", recipientNumber);
            payload.put("type", "text");
            payload.put("text", Map.of("body", text));

            sendMessage(payload);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    void sendMessage(Map<String, Object> payload) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(WhatsAppBotController.WHATSAPP_API_TOKEN);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    WHATSAPP_API_URL,
                    HttpMethod.POST,
                    entity,
                    String.class
            );

            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new HttpClientErrorException(response.getStatusCode(), "Failed to send message: " + response.getBody());
            }

            System.out.println("Message sent successfully: " + response.getBody());
        } catch (HttpClientErrorException e) {
            System.err.println("HTTP Error: " + e.getStatusCode() + " - " + e.getResponseBodyAsString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Autowired
    private RazorpayService razorpayService;


    @PostMapping("/razorpay-webhook")
    public ResponseEntity<String> handleRazorpayWebhook(@RequestBody String payload) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            System.out.println("Received webhook payload: " + payload);

            // Parse the payload to JSON
            JsonNode rootNode = objectMapper.readTree(payload);

            // Get the event type
            String event = rootNode.get("event").asText();
            System.out.println("Webhook event received: " + event);

            // Check if the event is "payment_link.paid"
            if ("payment_link.paid".equals(event)) {
                // Extract the description from the "payment_link.entity" section
                JsonNode paymentLinkNode = rootNode.path("payload").path("payment_link").path("entity");

                // Retrieve the description field
                String description = paymentLinkNode.path("description").asText(null);
                String orderId = paymentLinkNode.path("order_id").asText(null);
                double amount = paymentLinkNode.path("amount_paid").asDouble(0) / 100;
                String currency = paymentLinkNode.path("currency").asText(null);
                String customerEmail = paymentLinkNode.path("customer").path("email").asText(null);
                String customerContact = paymentLinkNode.path("customer").path("contact").asText(null);

                // Log the details
                System.out.println("Payment details - Description: " + description + ", Order ID: " + orderId +
                        ", Amount: " + amount + " " + currency + ", Customer Contact: " + customerContact);

                if (description != null && customerContact != null) {
                    // Match the description or process the payment further
                    String descriptionToMatch = description.trim().toLowerCase();

                    // Assuming you use the description to find a PaymentLink
                    Optional<PaymentLink> paymentLinkOptional = paymentLinkRepository.findByDescriptionIgnoreCase(descriptionToMatch);

                    if (paymentLinkOptional.isPresent()) {
                        PaymentLink paymentLink = paymentLinkOptional.get();
                        String serviceName = "General Service";

                        // Fetch the order associated with the payment link
                        Order order = orderRepository.findById(Long.valueOf(paymentLink.getOrderId())).orElse(null);

                        if (order != null) {
                            Optional<Service> optionalService = serviceRepository.findById(order.getServiceId());
                            if (optionalService.isPresent()) {
                                Service service = optionalService.get();
                                serviceName = service.getName();
                            }

                            Customer customer = order.getUser();
                            if (customer != null) {
                                if (!customerContact.equalsIgnoreCase(customer.getPhone().trim())) {
                                    // Send a thank you message via WhatsApp
                                    WhatsAppBotController.sendTemplateMessageThankyou(customer.getPhone(), paymentLink.getOrderId(), serviceName, amount + " " + currency);
                                }
                            }
                        }

                        paymentLink.setPaymentStatus("paid");
                        order.setIsPaid(1);

                        // Send thank you message to the customer
                        WhatsAppBotController.sendTemplateMessageThankyou(customerContact, paymentLink.getOrderId(), serviceName, amount + " " + currency);

                        // Notify admins
                        for (String adminNumber : notificationNumberList) {
                            WhatsAppBotController.sendTemplateMessagePaymentReceived(adminNumber, paymentLink.getOrderId(), serviceName, amount + " " + currency, customerContact);
                        }

                        System.out.println("Admins notified about payment for order ID: " + orderId);
                        return ResponseEntity.ok("Webhook processed successfully.");
                    } else {
                        System.out.println("No payment link found for description: " + descriptionToMatch);
                        return ResponseEntity.ok("Webhook received but no payment link found for the description.");
                    }
                } else {
                    System.err.println("Missing required fields in webhook payload.");
                    return ResponseEntity.status(400).body("Invalid payload - missing required fields.");
                }
            }

            System.out.println("Webhook received but no action taken. Event was not 'payment_link.paid'.");
            return ResponseEntity.ok("Webhook received but no action taken.");
        } catch (IOException e) {

            e.printStackTrace();
            System.err.println("Error processing webhook payload: " + e.getMessage());
            return ResponseEntity.status(500).body("Error processing webhook payload.");
        }
    }


}
