package dev.service;

import dev.dao.MenuItemDao;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
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 OrderDao orderDao ;
    private final OrderDetailDao orderDetailDao ;
    private final MenuItemDao menuItemDao ;
    private final Scanner scanner ;

    public OrderService(OrderDao orderDao, OrderDetailDao orderDetailDao, MenuItemDao menuItemDao) {
        this.orderDao = orderDao;
        this.orderDetailDao = orderDetailDao;
        this.menuItemDao = menuItemDao;
        this.scanner = new Scanner(System.in);
    }

    public void placeOrder(int userId) {
        List<OrderDetail> cart = new ArrayList<>();
        double totalPrice = 0.0;

        System.out.println("\n--- 🛒 STARTING NEW ORDER ---");
        System.out.println("Enter Menu ID to add to cart. Type '0' to finish and checkout.");


        while (true){
            List<MenuItem> menu = menuItemDao.findAll();
            for (MenuItem item : menu) {
                System.out.println(item.toString());
            }

            System.out.print("\nSelect Menu ID: ");
            int selectedId;
            try {
                selectedId = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println(" Invalid input. Please enter a number.");
                continue;
            }

            if (selectedId == 0) break;

            MenuItem item = menuItemDao.findById(selectedId);
            if (item == null) {
                System.out.println(" Invalid Menu ID! Try again.");
                continue;
            }

            System.out.print("Enter quantity for " + item.getName() + ": ");
            int qty;
            try {
                qty = Integer.parseInt(scanner.nextLine());
                if (qty <= 0) throw new NumberFormatException();
            } catch (NumberFormatException e) {
                System.out.println(" Quantity must be a positive number.");
                continue;
            }

            double subtotal = item.getPrice() * qty;
            totalPrice += subtotal;
            cart.add(new OrderDetail(0, 0, item.getId(), qty, item.getPrice()));
            System.out.println(" Added to cart.");
        }

        if (cart.isEmpty()) {
            System.out.println("🛒 Cart is empty. Order cancelled.");
            return;
        }

        Order order = new Order(0, userId, LocalDateTime.now(), totalPrice);
        int orderId = orderDao.save(order);

        if (orderId != -1){
            for (OrderDetail detail : cart){
                detail.setOrderId(orderId);
                orderDetailDao.save(detail);
            }
            System.out.println("\n Order placed successfully!");
            printReceipt(orderId);
        }else {
            System.out.println(" Error occurred while saving the order.");
        }
    }

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

        System.out.println("\n=================================");
        System.out.println("             RECEIPT");
        System.out.println("=================================");


        for (OrderDetail detail : details){
            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            if (item == null)   continue;

            double subtotal = detail.getQuantity() * detail.getPrice();
            grandTotal += subtotal;

            System.out.printf("%-15s x%d  $%.2f%n", item.getName(), detail.getQuantity(), subtotal);
        }
        System.out.println("--------------------------------");
        System.out.printf("GRAND TOTAL:        $%.2f%n", grandTotal);
        System.out.println("================================\n");
    }

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

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

        System.out.println("\n==========  YOUR ORDER HISTORY ==========");
        for (Order order : orders) {
            System.out.printf("Order ID: %d | Date: %s | Total: $%.2f%n",
                    order.getId(), order.getCreatedAt().toString(), order.getTotalPrice());
        }
        System.out.println("------------------------------");
    }
}