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.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 static void placeOrder(int userId) {
        List<CartItem> cart = new ArrayList<>();
        double total = 0;

        while (true){
            System.out.println("==========Menu==========");
            menuService.showMenu();
            System.out.println("[0] finish.");
            System.out.print("Select an item :");

            int selectedId = scanner.nextInt();

            if (selectedId == 0) {
                if (cart.isEmpty()) {
                    System.err.println("Cart is empty.");
                    continue;
                }
                break;
            }

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

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

            System.out.println("Enter quantity: ");
            int quantity = scanner.nextInt();

            if (quantity <= 0){
                System.err.println("Invalid quantity.");
            }
            else {
                cart.add(new CartItem(
                        item,
                        quantity
                ));
                total += item.getPrice() * quantity;
                System.out.println(quantity + "x " + item.getName() + " Added to cart.");

            }
        }


        Order order = new Order(
                userId,
                LocalDateTime.now(),
                total
        );

        int orderId = orderDao.save(order);

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

        for (CartItem cartItem : cart){
            OrderDetail orderDetail = new OrderDetail(
                    orderId,
                    cartItem.getItem().getId(),
                    cartItem.getQuantity(),
                    cartItem.getItem().getPrice()
            );

            orderDetailDao.save(orderDetail);
        }

        System.out.printf("Order placed, total: $%.2f%n", total);

    }

    public static void printReceipt(int orderId) {
        List<OrderDetail> orderDetails = orderDetailDao.findByOrderId(orderId);

        System.out.println("==========Receipt==========");
        System.out.println("Order ID: " + orderId);
        System.out.println("---------------------------");

        if (orderDetails.isEmpty()) {
            System.out.println("No order items found.");
            System.out.println("===========================\n");
            return;
        }

        double total = 0;
        for (OrderDetail detail : orderDetails) {
            double subtotal = detail.getPrice() * detail.getQuantity();
            total += subtotal;
            System.out.printf("%-20s %dx  $%.2f%n",
                    MenuService.menuItemDao.findById(detail.getMenuItemId()).getName(),
                    detail.getQuantity(),
                    subtotal
            );
        }

        System.out.println("---------------------------");
        System.out.printf("Total: $%.2f%n", total);
        System.out.println("===========================\n");
    }

    public static void showOrderHistory(int userId) {
        List<Order> orders = orderDao.findByUserId(userId);

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

        System.out.println("===========Order history===========");
        for (Order order : orders){
            System.out.println("Order ID: " + order.getId());
            System.out.println("Date: " + order.getCreatedAt());
            System.out.printf("Total: $%.2f%n", order.getTotalPrice());
            System.out.println("---------------------------------");
            printReceipt(order.getId());
        }
    }

}
