package dev.service;

import dev.dao.MenuItemDao;
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 Scanner scanner =
            new Scanner(System.in);

    private final MenuItemDao menuItemDao =
            new MenuItemDao();

    private final OrderDao orderDao =
            new OrderDao();

    private final OrderDetailDao orderDetailDao =
            new OrderDetailDao();

    public void placeOrder(int userId)
    {
        List<CartItem> cart = new ArrayList<>();

        while (true)
        {
            System.out.println();
            System.out.println("Available Items:");

            List<MenuItem> items = menuItemDao.findAll();

            for (MenuItem item : items)
            {
                System.out.printf(
                        "%d - %s - $%.2f%n",
                        item.getId(),
                        item.getName(),
                        item.getPrice()
                );
            }

            System.out.print("Enter item id (0 to finish): ");

            int itemId = scanner.nextInt();

            if (itemId == 0)
                break;

            MenuItem menuItem = menuItemDao.findById(itemId);

            if (menuItem == null)
            {
                System.out.println("Invalid item id.");
                continue;
            }

            System.out.print("Quantity: ");

            int quantity = scanner.nextInt();

            if (quantity <= 0)
            {
                System.out.println("Quantity must be positive.");
                continue;
            }

            cart.add(new CartItem(menuItem, quantity));

            System.out.println("Added successfully.");
        }

        if (cart.isEmpty())
        {
            System.out.println("No items selected.");
            return;
        }

        double total = 0.0;

        for (CartItem cartItem : cart)
            total += cartItem.getMenuItem().getPrice() * cartItem.getQuantity();

        Order order = new Order();

        order.setUserId(userId);
        order.setCreatedAt(LocalDateTime.now());
        order.setTotalPrice(total);

        int orderId = orderDao.save(order);

        if (orderId == -1)
        {
            System.out.println("Failed to save order.");
            return;
        }

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

            orderDetailDao.save(detail);
        }

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

        printReceipt(orderId);
    }

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

        System.out.println();
        System.out.println("========== RECEIPT ==========");
        System.out.printf("%-15s %-8s %-10s %-10s%n", "Item", "Qty", "Unit", "Total");
        System.out.println("------------------------------------------");

        double grandTotal = 0;

        for (OrderDetail detail : details)
        {
            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            double subtotal = detail.getQuantity() * detail.getPrice();

            grandTotal += subtotal;

            System.out.printf(
                    "%-15s %-8d %-10.2f %-10.2f%n",
                    item.getName(),
                    detail.getQuantity(),
                    detail.getPrice(),
                    subtotal
            );
        }

        System.out.println("------------------------------------------");
        System.out.printf("Final Total: %.2f%n", grandTotal);
        System.out.println("==============================");
    }

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

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

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

        for (Order order : orders)
        {
            System.out.printf(
                    "Order #%d | %s | $%.2f%n",
                    order.getId(),
                    order.getCreatedAt(),
                    order.getTotalPrice()
            );
        }
    }
}