import dash_bootstrap_components as dbc
from dash import html, dcc
import json
import plotly.graph_objects as go
import pandas as pd

from config import MAPBOX_ACCESS_TOKEN


def make_real_epc_piechart(real_epc_breakdown):
    labels = [x["is_real_epc"] for x in real_epc_breakdown]
    values = [x["count"] for x in real_epc_breakdown]

    marker_colors = ["#027fa6", "rgb(225 225 225)"]

    fig = go.Figure(
        data=[go.Pie(labels=labels, values=values, marker_colors=marker_colors)],
    )

    fig.update_layout(margin={"t": 0})

    plot = dcc.Graph(figure=fig, config={"displayModeBar": False})

    return plot


def make_epc_rating_piechart(epc_rating_breakdown):
    # Re-order from G to A
    epc_rating_breakdown = sorted(epc_rating_breakdown, key=lambda x: x["EPC"])

    labels = [x["EPC"] for x in epc_rating_breakdown]
    values = [x["count"] for x in epc_rating_breakdown]

    # marker_colors = ["#117d58", "#2da55c", "#8dbd40", "#f7cd14", "#f3a96a", "#ef8026", "#e41e3b"]
    marker_colors = ["#8dbd40", "#f7cd14", "#f3a96a", "#ef8026", "#e41e3b"]

    fig = go.Figure(
        data=[go.Pie(labels=labels, values=values, marker_colors=marker_colors, sort=False)],
    )

    fig.update_layout(margin={"t": 0})

    plot = dcc.Graph(figure=fig, config={"displayModeBar": False})

    return plot


def make_map(locations):
    if not locations:
        return None

    df = pd.DataFrame(locations)

    # Create custom hover text
    df['hover_text'] = df.apply(
        lambda row: f"UPRN: {int(row['uprn'])}<br>Address: {row['standardised_address']}<br>Postcode: "
                    f"{row['standardised_postcode']}<br>Latitude: {row['LATITUDE']}<br>Longitude: "
                    f"{row['LONGITUDE']}<br>Walls: {row['Walls']}<br>Roofs: {row['Roofs']}<br>Main Fuel: "
                    f"{row['Main Fuel']}<br>Heating: {row['Heating']}<br>Age: {row['Age']}<br>Property Type: "
                    f"{row['Property Type']}",
        axis=1)

    data = [
        go.Scattermapbox(
            lat=df["LATITUDE"].tolist(),
            lon=df["LONGITUDE"].tolist(),
            mode="markers",
            marker=go.scattermapbox.Marker(size=10, color="#027fa6"),
            text=df["hover_text"],  # Use the custom hover text
            hoverinfo='text'
        )
    ]

    layout = go.Layout(
        autosize=True,
        hovermode="closest",
        mapbox=go.layout.Mapbox(
            accesstoken=MAPBOX_ACCESS_TOKEN,
            bearing=0,
            center=go.layout.mapbox.Center(lat=53, lon=-1.5),
            pitch=0,
            zoom=5,
        ),
        margin={"t": 0},
    )

    fig = go.Figure(data=data, layout=layout)

    plot = dcc.Graph(figure=fig, config={"displayModeBar": False})

    return plot


def layout():
    # Get the data
    with open("Stonewater Mapping Data.json", "r") as file:
        locations = json.load(file)

    # Get the EPC breakdown data
    # with open("Stonewater real EPC breakdown.json") as file:
    #     real_epc_breakdown = json.load(file)

    # Get the EPC ratings data
    with open("Stonewater EPC rating breakdown.json") as file:
        epc_rating_breakdown = json.load(file)

    page = dbc.Container(
        [
            dbc.Row(
                dbc.Col(
                    html.Div(
                        [
                            # Banner with logos
                            dbc.Row(
                                [
                                    dbc.Col(
                                        html.Img(src="assets/stonewater-logo.png", height="50px"),
                                        width="auto"
                                    ),
                                    dbc.Col(
                                        html.Img(src="assets/osmosis-Logo.svg", height="50px"),
                                        width="auto"
                                    ),
                                    dbc.Col(
                                        html.Div(
                                            style={"color": "white", "font-size": "1.5rem", "font-weight": "bold"}
                                        ),
                                        width=True,
                                        className="text-center"
                                    )
                                ],
                                className="align-items-center",
                                style={"background-color": "#027fa6", "padding": "10px"}
                            ),
                            dbc.Row(
                                [
                                    dbc.Col("Powered by", style={"color": "#027fa6", "fontSize": "1rem", 'zIndex': 10},
                                            width="auto"),
                                    dbc.Col(
                                        html.A(
                                            html.Img(src="assets/hestia-logo.png", height="50px"),
                                            href="https://hestia.homes",
                                        ),
                                        width="auto",
                                        style={"margin-left": "-60px"}
                                    ),
                                ],
                                justify='left',
                                align="center"
                            ),
                            html.H1(
                                "Stonewater Survey Map",
                                style={"font-size": "2.5rem", "font-weight": "bold", "margin-bottom": "20px"}
                            ),
                            html.P(
                                "This map shows the location of the properties that are to be surveyed by Osmosis. "
                                "These properties span across 30 counties and 155 postal regions",
                                style={"font-size": "1.25rem", "margin-bottom": "40px"}
                            ),
                        ],
                        className="text-center"
                    ),
                    width=12
                ),
                className="mt-5"
            ),
            dbc.Row(
                dbc.Col(
                    make_map(locations=locations),
                    width=10,
                    align="center",
                    className="text-center"
                ),
                justify="center"
            ),
            dbc.Row(
                [
                    # dbc.Col(
                    #     [
                    #         html.Div(
                    #             "Breakdown of real EPCs",
                    #             style={"fontSize": "1.5rem", "fontWeight": "bold", "marginBottom": "1em"},
                    #             className='text-center'
                    #         ),
                    #         html.Div(
                    #             "This pie chart shows the proportion of real EPCs in the asset list. Currently, "
                    #             "there are EPCs for 3736 of the 5245 properties that have a UPRN in the asset list",
                    #             style={"marginBottom": "1em"}
                    #         ),
                    #         make_real_epc_piechart(real_epc_breakdown),
                    #     ],
                    #     width={"size": 5},
                    # ),
                    dbc.Col(
                        [
                            html.Div(
                                "EPC Ratings for properties with an EPC",
                                style={"fontSize": "1.5rem", "fontWeight": "bold", "marginBottom": "1em"},
                                className='text-center'
                            ),
                            html.Div(
                                [
                                    "This pie chart shows the breakdown of expected and real EPC ratings, "
                                    "for properties "
                                    "that have been selected for sample",
                                ],
                                style={"marginBottom": "1em"}
                            ),
                            make_epc_rating_piechart(epc_rating_breakdown),
                        ],

                        width={"size": 5},
                    ),
                ],
                justify="center"
            )
        ],
        fluid=True,
        className="p-5"
    )

    return page
