package dev.service;

import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.model.CartItem;
import dev.model.MenuItem;
import dev.model.Order;
import dev.model.OrderDetail;

import java.awt.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class OrderService {

    private final static OrderDetailDao orderDetailDao = new OrderDetailDao();
    private final static OrderDao orderDao = new OrderDao();
    private final static MenuService menuService = new MenuService();
    private final static Scanner scanner = new Scanner(System.in);

    public void placeOrder(int userId) {

        List<CartItem> cart = buildCart(scanner);

        if (cart == null || cart.isEmpty()) {
            System.err.println("The cart is empty. Order placement aborted.");
            return;
        }

        double totalPrice = 0;

        for (CartItem cartItem: cart) {
            totalPrice += cartItem.getSubtotal();
        }

        Order order = new Order();
        order.setUserId(userId);
        order.setCreatedAt(LocalDateTime.now());
        order.setTotalPrice(totalPrice);

        int orderId = orderDao.save(order);

        if (orderId == -1) {
            System.err.println("Order could not be placed (Database error).");
            return;
        }

        order.setId(orderId);

        for (CartItem cartItem : cart){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setMenuItemId( cartItem.getItem().getId());
            orderDetail.setQuantity(cartItem.getQuantity());
            orderDetail.setPrice(cartItem.getItem().getPrice());

            orderDetailDao.save(orderDetail);
        }

        printReceipt(orderId);
        System.out.println("Order saved successfully.");

    }

    public void printReceipt(int orderId) {

        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);

        System.out.println("\n--- order receipt: " + orderId + " ---");
        System.out.printf("%-15s %-5s %-10s%n", "name", "quantity", "totalPrice");

        double total = 0;
        for (OrderDetail d : details) {
            MenuItem item = MenuService.menuItemDao.findById(d.getMenuItemId());
            double sub = d.getPrice() * d.getQuantity();
            total += sub;
            System.out.printf("%-15s %-5d %-10.2f%n", item.getName(), d.getQuantity(), sub);
        }
        System.out.println("------------------------------");
        System.out.printf("totalPrice: %.2f%n", total);
    }

    public void showOrderHistory(int userId) {

        List<Order> orders = orderDao.findByUserId(userId);

        if (orders.isEmpty())
        {
            System.out.println("No orders found.");
            return;
        }

        System.out.println("\n===== ORDER HISTORY =====");

        for (Order order : orders)
        {
            System.out.println("Order ID: " + order.getId()
                    + " | Total: $" + order.getTotalPrice()
                    + " | Date: " + order.getCreatedAt()
            );
        }

    }


    public List<CartItem> buildCart(Scanner scanner) {

        List<CartItem> cart = new ArrayList<>();

        menuService.showMenu();

        while(true) {
            System.out.println("\n[0] End order");
            System.out.println("[-1] Show menu again");
            System.out.println("Please select an item number:");

            if (!scanner.hasNextInt()) {
                System.err.println("Invalid input. Please enter a number.");
                scanner.next();
                continue;
            }

            int choice = scanner.nextInt();

            if (choice == -1) {
                menuService.showMenu();
                continue;
            }

            if (choice == 0) {
                if (cart.isEmpty()) {
                    System.out.println("Your cart is empty. Please select items.");
                    continue;
                }
                break;
            }

            MenuItem item = MenuService.menuItemDao.findById(choice);

            if (item == null) {
                System.err.println("Invalid item ID, please try again.");
                continue;
            }

            System.out.println("Enter quantity for " + item.getName() + ": ");

            if (!scanner.hasNextInt()) {
                System.err.println("Invalid quantity input. Please enter a number.");
                scanner.next();
                continue;
            }

            int quantity = scanner.nextInt();

            if (quantity <= 0){
                System.err.println("Invalid quantity. Must be greater than 0.");
                continue;
            }

            cart.add(new CartItem(item, quantity));
            System.out.println(quantity + "x " + item.getName() + " added to cart.");
        }

        return cart;
    }

}