package com.example.computers.view;

import com.example.computers.entity.Repair;
import com.example.computers.repository.*;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.html.*;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Route(value = "", layout = MainView.class)
@PageTitle("Dashboard")
public class DashboardView extends VerticalLayout {

    @Autowired
    public DashboardView(ComputerRepository computerRepository,
                         RepairRepository repairRepository,
                         ComponentRepository componentRepository,
                         ManufacturerRepository manufacturerRepository,
                         LocationRepository locationRepository) {

        setPadding(true);
        setSpacing(true);
        getStyle().set("background", "#F0F4F8").set("min-height", "100%");

        // Заголовок
        H2 title = new H2("Обзор системы");
        title.getStyle().set("margin-bottom", "16px").set("color", "#1565C0");

        // Карточки с кликом
        HorizontalLayout cards = new HorizontalLayout(
                createStatCard("Компьютеры",    String.valueOf(computerRepository.count()),     VaadinIcon.DESKTOP,  "#1E88E5", "computers"),
                createStatCard("Производители", String.valueOf(manufacturerRepository.count()), VaadinIcon.FACTORY,  "#43A047", "manufacturers"),
                createStatCard("Локации",       String.valueOf(locationRepository.count()),     VaadinIcon.OFFICE,   "#FB8C00", "locations"),
                createStatCard("Комплектующие", String.valueOf(componentRepository.count()),    VaadinIcon.COG,      "#8E24AA", "components"),
                createStatCard("Ремонты",       String.valueOf(repairRepository.count()),       VaadinIcon.TOOLS,    "#E53935", "repairs")
        );
        cards.setWidthFull();
        cards.setSpacing(true);

        // Секция последних ремонтов
        H3 repairsTitle = new H3("Последние ремонты");
        repairsTitle.getStyle().set("color", "#1565C0").set("margin-top", "32px");

        VerticalLayout recentRepairs = new VerticalLayout();
        recentRepairs.setPadding(false);
        recentRepairs.setSpacing(false);
        recentRepairs.getStyle()
                .set("background", "white")
                .set("border-radius", "12px")
                .set("box-shadow", "0 2px 8px rgba(0,0,0,0.1)")
                .set("overflow", "hidden");

        List<Repair> repairs = repairRepository.findAll();
        List<Repair> lastRepairs = repairs.stream()
                .sorted((a, b) -> {
                    if (a.getRepairDate() == null) return 1;
                    if (b.getRepairDate() == null) return -1;
                    return b.getRepairDate().compareTo(a.getRepairDate());
                })
                .limit(5)
                .toList();

        if (lastRepairs.isEmpty()) {
            Span empty = new Span("Нет данных о ремонтах");
            empty.getStyle().set("padding", "16px").set("color", "#90A4AE");
            recentRepairs.add(empty);
        } else {
            // Шапка таблицы
            HorizontalLayout header = new HorizontalLayout();
            header.setWidthFull();
            header.getStyle()
                    .set("background", "#F5F7FA")
                    .set("padding", "10px 16px")
                    .set("border-bottom", "1px solid #E0E0E0");
            header.add(styledCell("Компьютер", true),
                    styledCell("Дата", true),
                    styledCell("Описание", true),
                    styledCell("Стоимость", true));
            recentRepairs.add(header);

            for (int i = 0; i < lastRepairs.size(); i++) {
                Repair r = lastRepairs.get(i);
                HorizontalLayout row = new HorizontalLayout();
                row.setWidthFull();
                row.getStyle()
                        .set("padding", "10px 16px")
                        .set("background", i % 2 == 0 ? "white" : "#FAFAFA")
                        .set("border-bottom", "1px solid #F0F0F0");

                row.add(
                        styledCell(r.getComputer() != null ? r.getComputer().getModel() : "—", false),
                        styledCell(r.getRepairDate() != null ? r.getRepairDate().toString() : "—", false),
                        styledCell(r.getDescription() != null ? r.getDescription() : "—", false),
                        styledCell(r.getCost() != null ? r.getCost() + " ₽" : "—", false)
                );
                recentRepairs.add(row);
            }
        }

        // Инфо блок внизу
        H3 infoTitle = new H3("Информация о системе");
        infoTitle.getStyle().set("color", "#1565C0").set("margin-top", "32px");

        HorizontalLayout infoCards = new HorizontalLayout(
                createInfoCard("О системе",
                        "Система учета вычислительных машин позволяет управлять парком оборудования организации.",
                        VaadinIcon.INFO_CIRCLE, "#1E88E5"),
                createInfoCard("Возможности",
                        "Добавление, редактирование и удаление записей. Поиск и фильтрация по всем таблицам.",
                        VaadinIcon.BULLETS, "#43A047"),
                createInfoCard("Поддержка",
                        "По всем вопросам работы с системой обращайтесь к системному администратору..",
                        VaadinIcon.WRENCH, "#FB8C00")
        );
        infoCards.setWidthFull();
        infoCards.setSpacing(true);

        add(title, cards, repairsTitle, recentRepairs, infoTitle, infoCards);
    }

    private Component createStatCard(String label, String value, VaadinIcon icon,
                                     String color, String route) {
        VerticalLayout card = new VerticalLayout();
        card.setSpacing(false);
        card.setPadding(true);
        card.setAlignItems(FlexComponent.Alignment.CENTER);
        card.getStyle()
                .set("background", "white")
                .set("border-radius", "12px")
                .set("box-shadow", "0 2px 8px rgba(0,0,0,0.1)")
                .set("padding", "24px")
                .set("flex", "1")
                .set("min-width", "140px")
                .set("cursor", "pointer")
                .set("transition", "transform 0.15s, box-shadow 0.15s");

        // Hover эффект
        card.getElement().executeJs(
                "this.addEventListener('mouseover', () => {" +
                        "  this.style.transform='translateY(-3px)';" +
                        "  this.style.boxShadow='0 6px 16px rgba(0,0,0,0.15)';" +
                        "});" +
                        "this.addEventListener('mouseout', () => {" +
                        "  this.style.transform='translateY(0)';" +
                        "  this.style.boxShadow='0 2px 8px rgba(0,0,0,0.1)';" +
                        "});"
        );

        // Клик — переход на страницу
        card.addClickListener(e -> UI.getCurrent().navigate(route));

        Icon cardIcon = icon.create();
        cardIcon.getStyle()
                .set("width", "36px")
                .set("height", "36px")
                .set("color", color)
                .set("margin-bottom", "8px");

        H2 count = new H2(value);
        count.getStyle()
                .set("margin", "0")
                .set("font-size", "2em")
                .set("color", color);

        Span name = new Span(label);
        name.getStyle()
                .set("color", "#607D8B")
                .set("font-size", "0.9em")
                .set("margin-top", "4px");

        card.add(cardIcon, count, name);
        return card;
    }

    private Component createInfoCard(String title, String text, VaadinIcon icon, String color) {
        VerticalLayout card = new VerticalLayout();
        card.setSpacing(false);
        card.setPadding(true);
        card.getStyle()
                .set("background", "white")
                .set("border-radius", "12px")
                .set("box-shadow", "0 2px 8px rgba(0,0,0,0.1)")
                .set("padding", "20px")
                .set("flex", "1");

        Icon cardIcon = icon.create();
        cardIcon.getStyle()
                .set("width", "28px")
                .set("height", "28px")
                .set("color", color)
                .set("margin-bottom", "8px");

        H4 cardTitle = new H4(title);
        cardTitle.getStyle()
                .set("margin", "0 0 8px 0")
                .set("color", "#263238");

        Paragraph cardText = new Paragraph(text);
        cardText.getStyle()
                .set("margin", "0")
                .set("color", "#607D8B")
                .set("font-size", "0.9em")
                .set("line-height", "1.5");

        card.add(cardIcon, cardTitle, cardText);
        return card;
    }

    private Span styledCell(String text, boolean isHeader) {
        Span cell = new Span(text);
        cell.getStyle()
                .set("flex", "1")
                .set("font-size", "0.9em")
                .set("color", isHeader ? "#607D8B" : "#263238")
                .set("font-weight", isHeader ? "600" : "400");
        return cell;
    }
}