package de.antco.projekt;

import de.antco.projekt.model.Person;
import de.antco.projekt.model.ServiceItem;
import de.antco.projekt.model.Vehicle;
import de.antco.projekt.model.WorkOrderDetails;
import de.antco.projekt.model.WorkOrderItem;
import de.antco.projekt.service.WorkshopService;
import de.antco.projekt.importers.IImporter;
import de.antco.projekt.importers.CsvPersonImporter;
import de.antco.projekt.exporters.IExporter;
import de.antco.projekt.exporters.CsvPersonExporter;

import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class ConsoleUi {
    private final WorkshopService service;
    private final Scanner scanner = new Scanner(System.in);

    public ConsoleUi(WorkshopService service) {
        this.service = service;
    }

    public void start() {
        boolean running = true;
        while (running) {
            printMenu();
            String input = scanner.nextLine();
            try {
                switch (input) {
                    case "1" -> addPerson();
                    case "2" -> listPersons();
                    case "3" -> addVehicle();
                    case "4" -> listVehiclesOfPerson();
                    case "5" -> createWorkOrder();
                    case "6" -> listWorkOrders();
                    case "7" -> importPersons();
                    case "8" -> exportPersons();
                    case "0" -> running = false;
                    default -> System.out.println("Unbekannte Auswahl");
                }
            } catch (SQLException e) {
                System.out.println("Fehler: " + e.getMessage());
            }
        }
        System.out.println("Bis dann");
    }

    private void printMenu() {
        System.out.println();
        System.out.println("==== Werkstatt Menü ====");
        System.out.println("1) Kunde anlegen");
        System.out.println("2) Kunden anzeigen");
        System.out.println("3) Fahrzeug anlegen");
        System.out.println("4) Fahrzeuge einer Person");
        System.out.println("5) Werkstattvorgang anlegen");
        System.out.println("6) Vorgänge anzeigen");
        System.out.println("7) Personen importieren (CSV)");
        System.out.println("8) Personen exportieren (CSV)");
        System.out.println("0) Ende");
        System.out.print("Auswahl: ");
    }

    private void addPerson() throws SQLException {
        System.out.print("Name: ");
        String name = scanner.nextLine();
        System.out.print("Telefon: ");
        String phone = scanner.nextLine();
        Person person = service.createPerson(name, phone);
        System.out.println("Kunde gespeichert mit ID " + person.getId());
    }

    private void listPersons() throws SQLException {
        List<Person> persons = service.listPersons();
        if (persons.isEmpty()) {
            System.out.println("Keine Personen da");
            return;
        }
        persons.forEach(p -> System.out.println(p.toString()));
    }

    private void addVehicle() throws SQLException {
        System.out.print("Personen ID: ");
        int personId = parseInt(scanner.nextLine());
        Person owner = service.findPerson(personId);
        if (owner == null) {
            System.out.println("Person nicht gefunden");
            return;
        }
        System.out.print("Hersteller: ");
        String brand = scanner.nextLine();
        System.out.print("Modell: ");
        String model = scanner.nextLine();
        System.out.print("Kennzeichen: ");
        String plate = scanner.nextLine();
        Vehicle vehicle = service.createVehicle(personId, brand, model, plate);
        System.out.println("Fahrzeug gespeichert mit ID " + vehicle.getId());
    }

    private void listVehiclesOfPerson() throws SQLException {
        System.out.print("Personen ID: ");
        int personId = parseInt(scanner.nextLine());
        Person owner = service.findPerson(personId);
        if (owner == null) {
            System.out.println("Person nicht gefunden");
            return;
        }
        List<Vehicle> vehicles = service.listVehicles(personId);
        System.out.println("Fahrzeuge von " + owner.getName() + ":");
        if (vehicles.isEmpty()) {
            System.out.println("Keine Einträge");
            return;
        }
        vehicles.forEach(v -> System.out.println(v.toString()));
    }

    private void createWorkOrder() throws SQLException {
        System.out.print("Fahrzeug ID: ");
        int vehicleId = parseInt(scanner.nextLine());
        Vehicle vehicle = service.findVehicle(vehicleId);
        if (vehicle == null) {
            System.out.println("Fahrzeug nicht gefunden");
            return;
        }
        System.out.print("Notiz: ");
        String note = scanner.nextLine();
        List<ServiceItem> catalog = service.listServiceItems();
        Map<Integer, Integer> selected = new LinkedHashMap<>();
        boolean adding = true;
        while (adding) {
            showCatalog(catalog);
            System.out.print("Service ID (leer = fertig): ");
            String input = scanner.nextLine();
            if (input.isBlank()) {
                adding = false;
            } else {
                int serviceId = parseInt(input);
                ServiceItem item = catalog.stream().filter(s -> s.getId() == serviceId).findFirst().orElse(null);
                if (item == null) {
                    System.out.println("Service gibt es nicht");
                    continue;
                }
                System.out.print("Menge: ");
                int qty = parseInt(scanner.nextLine());
                if (qty <= 0) {
                    System.out.println("Menge muss > 0 sein");
                    continue;
                }
                selected.put(serviceId, selected.getOrDefault(serviceId, 0) + qty);
            }
        }
        if (selected.isEmpty()) {
            System.out.println("Keine Positionen gespeichert");
            return;
        }
        int orderId = service.createWorkOrder(vehicleId, note, selected);
        System.out.println("Vorgang angelegt mit ID " + orderId);
    }

    private void showCatalog(List<ServiceItem> items) {
        System.out.println("Katalog:");
        items.forEach(item -> System.out.println(item.toString()));
    }

    private void listWorkOrders() throws SQLException {
        List<WorkOrderDetails> orders = service.listWorkOrders();
        if (orders.isEmpty()) {
            System.out.println("Keine Vorgänge gespeichert");
            return;
        }
        for (WorkOrderDetails order : orders) {
            System.out.println("--- Vorgang " + order.getOrderId() + " ---");
            System.out.println("Kunde: " + order.getPersonName());
            System.out.println("Fahrzeug: " + order.getVehicleText());
            System.out.println("Datum: " + order.getCreatedAt());
            if (order.getNote() != null && !order.getNote().isBlank()) {
                System.out.println("Notiz: " + order.getNote());
            }
            for (WorkOrderItem item : order.getItems()) {
                System.out.println("  * " + item.getServiceItem().getTitle() + " x" + item.getQuantity() +
                        " = " + item.getTotalPrice() + " €");
            }
            System.out.println("Summe: " + order.getTotal() + " €");
        }
    }

    private void importPersons() {
        System.out.print("Pfad zur CSV-Datei: ");
        String path = scanner.nextLine();
        IImporter<Person> importer = new CsvPersonImporter();
        try {
            List<Person> imported = importer.importData(path);
            int count = 0;
            for (Person p : imported) {
                service.createPerson(p.getName(), p.getPhone());
                count++;
            }
            System.out.println(count + " Personen erfolgreich importiert.");
        } catch (Exception e) {
            System.out.println("Fehler beim Import: " + e.getMessage());
        }
    }

    private void exportPersons() {
        System.out.print("Pfad zur Ziel-Datei: ");
        String path = scanner.nextLine();
        try {
            List<Person> persons = service.listPersons();
            IExporter<Person> exporter = new CsvPersonExporter();
            exporter.exportData(persons, path);
            System.out.println(persons.size() + " Personen exportiert.");
        } catch (Exception e) {
            System.out.println("Fehler beim Export: " + e.getMessage());
        }
    }

    private int parseInt(String input) {
        try {
            return Integer.parseInt(input.trim());
        } catch (NumberFormatException e) {
            return -1;
        }
    }
}
