#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pandas as pd
import dash
from dash import Dash, dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objects as go

# ============================
# 1. CARGA DE DATOS
# ============================
df = pd.read_csv(
    "data/Produccion_centros_cultivo_2000_2024_consolidado.csv",
    low_memory=False
)

# Normalizar nombres de columnas
df.columns = df.columns.str.strip()

# Renombrar región a mayúsculas para ser consistente
if "Región" in df.columns:
    df = df.rename(columns={"Región": "REGION"})

# Asegurar que Año sea numérico
df["Año"] = pd.to_numeric(df["Año"], errors="coerce")

# Filtrar años válidos
df = df[df["Año"].between(2000, 2025)]

# ============================
# 1b. ESPECIES DE INTERÉS
# ============================
especies_interes = [
    "CHORITO",
    "OSTION DEL NORTE",
    "SALMON DEL ATLANTICO",
    "SALMON PLATEADO O COHO",
    "SALMON REY"
]

df = df[df["Especie"].isin(especies_interes)].copy()

# ============================
# 1c. LIMPIEZA REGIONES
# ============================
df["REGION"] = df["REGION"].astype(str).str.strip()
df["REGION"] = df["REGION"].str.replace(".0", "", regex=False)

# Por si hubiese una región 99 o códigos raros:
df = df[df["REGION"] != "99"]

# Diccionario oficial con número romano + nombre, en orden geográfico
dicc_regiones = {
    "15": "XV Arica y Parinacota",
    "1":  "I Tarapacá",
    "2":  "II Antofagasta",
    "3":  "III Atacama",
    "4":  "IV Coquimbo",
    "5":  "V Valparaíso",
    "6":  "VI Libertador General Bernardo O'Higgins",
    "7":  "VII Maule",
    "16": "XVI Ñuble",
    "8":  "VIII Biobío",
    "9":  "IX de Araucanía",
    "14": "XIV Los Ríos",
    "10": "X Los Lagos",
    "11": "XI Aysén del General Carlos Ibáñez del Campo",
    "12": "XII Magallanes y Antártica Chilena",
}

# Orden geográfico
region_order_geo = [
    "15",  # XV Arica y Parinacota
    "1",   # I Tarapacá
    "2",   # II Antofagasta
    "3",   # III Atacama
    "4",   # IV Coquimbo
    "5",   # V Valparaíso
    "13",  # RM
    "6",   # VI O'Higgins
    "7",   # VII Maule
    "16",  # XVI Ñuble
    "8",   # VIII Biobío
    "9",   # IX Araucanía
    "14",  # XIV Los Ríos
    "10",  # X Los Lagos
    "11",  # XI Aysén
    "12",  # XII Magallanes
]

# Códigos de región presentes en los datos
region_codes_in_data = sorted(df["REGION"].dropna().unique().tolist())

# Mapa código -> nombre bonito
map_region_nombre = {
    code: dicc_regiones.get(code, code)
    for code in region_codes_in_data
}

# ============================
# Dropdown values
# ============================
especies = especies_interes
etapas = sorted(df["Etapa"].dropna().unique())
default_etapa = "ADULTOS" if "ADULTOS" in etapas else etapas[0]

years_sorted = sorted(df["Año"].dropna().unique().tolist())
default_year_bar = max(years_sorted) if years_sorted else 2000

# ============================
# 2. ESTILOS (MISMO LOOK QUE OTRAS APPS)
# ============================
COLORS = {
    "bg": "#f5f7fa",
    "card": "white",
    "accent": "#005f73",
    "accent_light": "#e0fbfc",
    "text": "#222222",
    "muted": "#666666",
}

CARD_STYLE = {
    "backgroundColor": COLORS["card"],
    "borderRadius": "8px",
    "padding": "15px",
    "boxShadow": "0 2px 5px rgba(0,0,0,0.08)",
    "marginBottom": "15px",
}

# ============================
# 3. CONFIGURACIÓN DASH
# ============================
app = Dash(
    __name__,
    requests_pathname_prefix="/apps/produccion-centros/",
)
server = app.server  # útil si después quieres desplegar en WSGI/gunicorn

# ============================
# 4. LAYOUT
# ============================
app.layout = html.Div(
    style={"fontFamily": "Arial, sans-serif", "backgroundColor": COLORS["bg"], "minHeight": "100vh"},
    children=[
        # ----- TOP BAR -----
        html.Div(
            style={
                "backgroundColor": COLORS["accent"],
                "color": "white",
                "padding": "12px 25px",
                "display": "flex",
                "justifyContent": "space-between",
                "alignItems": "center",
            },
            children=[
                html.Div([
                    html.H1(
                        "Producción en Centros de Cultivo",
                        style={"margin": "0", "fontSize": "22px", "fontWeight": "bold"},
                    ),
                    html.Div(
                        "Serie de tiempo 2000–2024 · Filtro por región, especie y etapa",
                        style={"fontSize": "13px", "opacity": 0.9},
                    ),
                ]),
            ],
        ),

        # ----- CONTENIDO -----
        html.Div(
            style={"padding": "20px 25px"},
            children=[
                html.Div(
                    style={"display": "flex", "gap": "20px", "flexWrap": "wrap"},
                    children=[

                        # --------- FILTROS (IZQUIERDA) ----------
                        html.Div(
                            style={"flex": "1 1 280px", "maxWidth": "380px"},
                            children=[
                                html.Div(
                                    style=CARD_STYLE,
                                    children=[
                                        html.H3(
                                            "Filtros",
                                            style={"marginTop": 0, "fontSize": "16px", "color": COLORS["accent"]},
                                        ),

                                        html.Label("Región", style={"fontWeight": "bold", "fontSize": "13px"}),
                                        dcc.Dropdown(
                                            id="filtro-region",
                                            options=(
                                                [{"label": "Nacional (todas las regiones)", "value": "NACIONAL"}]
                                                + [
                                                    {
                                                        "label": map_region_nombre.get(code, code),
                                                        "value": code,
                                                    }
                                                    for code in region_order_geo
                                                    if code in region_codes_in_data
                                                ]
                                            ),
                                            value="NACIONAL",
                                            clearable=False,
                                            style={"marginBottom": "12px"},
                                        ),

                                        html.Label("Especie", style={"fontWeight": "bold", "fontSize": "13px"}),
                                        dcc.Dropdown(
                                            id="filtro-especie",
                                            options=[{"label": e, "value": e} for e in especies],
                                            value=especies[0],
                                            clearable=False,
                                            style={"marginBottom": "12px"},
                                        ),

                                        html.Label("Etapa", style={"fontWeight": "bold", "fontSize": "13px"}),
                                        dcc.Dropdown(
                                            id="filtro-etapa",
                                            options=[{"label": e, "value": e} for e in etapas],
                                            value=default_etapa,
                                            clearable=False,
                                            style={"marginBottom": "12px"},
                                        ),

                                        html.Label("Año para comparación regional",
                                                   style={"fontWeight": "bold", "fontSize": "13px"}),
                                        dcc.Dropdown(
                                            id="year-bar-dropdown",
                                            options=[{"label": int(y), "value": int(y)} for y in years_sorted],
                                            value=int(default_year_bar),
                                            clearable=False,
                                            style={"marginBottom": "4px"},
                                        ),
                                        html.Div(
                                            "Este año se usa para el gráfico de barras por región (abajo).",
                                            style={"fontSize": "11px", "color": COLORS["muted"]},
                                        ),
                                    ],
                                ),
                            ],
                        ),

                        # --------- GRÁFICOS (DERECHA) ----------
                        html.Div(
                            style={"flex": "3 1 500px", "minWidth": "0"},
                            children=[
                                html.Div(
                                    style={**CARD_STYLE, "height": "100%"},
                                    children=[
                                        # Serie de tiempo
                                        dcc.Graph(
                                            id="grafico-egresos",
                                            config={"scrollZoom": True},
                                        ),

                                        # Barras por región
                                        dcc.Graph(
                                            id="grafico-regiones",
                                            config={"scrollZoom": False},
                                            style={"marginTop": "30px"},
                                        ),

                                        html.Div(
                                            children=[
                                                html.P(
                                                    "Valores (arriba): EGRESOS K anuales (kilos cosechados/egresados) "
                                                    "por especie, etapa y región seleccionada.",
                                                    style={
                                                        "fontSize": "11px",
                                                        "color": COLORS["muted"],
                                                        "marginBottom": "4px",
                                                    },
                                                ),
                                                html.P(
                                                    "Gráfico de barras (abajo): distribución regional de kilos cosechados/egresados "
                                                    "para el año seleccionado, a escala nacional.",
                                                    style={
                                                        "fontSize": "11px",
                                                        "color": COLORS["muted"],
                                                    },
                                                ),
                                            ],
                                            style={"marginTop": "10px"},
                                        ),

                                        html.Div(
                                            children=[
                                                "Elaboración: Instituto en Socio-Ecología Costera (SECOS) – Datacenter",
                                            ],
                                            style={
                                                "fontSize": "11px",
                                                "color": COLORS["muted"],
                                                "marginTop": "4px",
                                            },
                                        ),
                                        html.Div(
                                            children=[
                                                "Fuente: SERNAPESCA",
                                            ],
                                            style={
                                                "fontSize": "11px",
                                                "color": COLORS["muted"],
                                            },
                                        ),
                                    ],
                                ),
                            ],
                        ),
                    ],
                ),
            ],
        ),
    ],
)

# ============================
# 5. CALLBACK
# ============================
@app.callback(
    Output("grafico-egresos", "figure"),
    Output("grafico-regiones", "figure"),
    [
        Input("filtro-region", "value"),
        Input("filtro-especie", "value"),
        Input("filtro-etapa", "value"),
        Input("year-bar-dropdown", "value"),
    ],
)
def actualizar_graficos(region, especie, etapa, year_bar):
    # ---------------------------
    # FIGURA 1: SERIE DE TIEMPO
    # ---------------------------
    dff_ts = df[
        (df["Especie"] == especie) &
        (df["Etapa"] == etapa)
    ].copy()

    if region != "NACIONAL":
        dff_ts = dff_ts[dff_ts["REGION"] == region]

    df_anual_ts = (
        dff_ts.groupby("Año")["EGRESOS K"]
        .sum()
        .reset_index()
        .sort_values("Año")
    )

    fig_ts = go.Figure()

    if not df_anual_ts.empty:
        fig_ts.add_trace(go.Scatter(
            x=df_anual_ts["Año"],
            y=df_anual_ts["EGRESOS K"],
            mode="lines+markers",
            line=dict(color="#006699", width=3),
            marker=dict(size=8),
            name="Cosecha (Kilos) (total)",
        ))

        nombre_region = (
            map_region_nombre.get(region, region)
            if region != "NACIONAL"
            else "Total nacional"
        )

        titulo_ts = f"Cosecha (Kilos) — {especie} / {etapa} / {nombre_region}"
    else:
        titulo_ts = "Sin datos de EGRESOS K para el filtro seleccionado"
        fig_ts.add_annotation(
            text="No hay registros disponibles.",
            xref="paper", yref="paper",
            x=0.5, y=0.5,
            showarrow=False,
            font=dict(size=14),
        )

    fig_ts.update_layout(
        title=titulo_ts,
        xaxis_title="Año",
        yaxis_title="Kilos (Cosech)",
        template="simple_white",
        font=dict(size=14),
        margin={"l": 60, "r": 20, "t": 70, "b": 40},
        hovermode="x unified",
    )

    # ---------------------------------------------
    # FIGURA 2: BARRAS POR REGIÓN (AÑO SELECCIONADO)
    # ---------------------------------------------
    dff_bar = df[
        (df["Especie"] == especie) &
        (df["Etapa"] == etapa) &
        (df["Año"] == year_bar)
    ].copy()

    df_reg = (
        dff_bar.groupby("REGION")["EGRESOS K"]
        .sum()
        .reset_index()
    )

    fig_bar = go.Figure()

    if not df_reg.empty:
        # Agregar nombre de región
        df_reg["REGION_NOMBRE"] = df_reg["REGION"].map(dicc_regiones).fillna(df_reg["REGION"])

        # Ordenar por EGRESOS K descendente
        df_reg = df_reg.sort_values("EGRESOS K", ascending=False)

        fig_bar.add_bar(
            x=df_reg["REGION_NOMBRE"],
            y=df_reg["EGRESOS K"],
            marker_color="#118ab2",
            name="EGRESOS K",
        )

        titulo_bar = f"Distribución regional de Cosecha (Kilos) — {especie} / {etapa} / Año {year_bar}"
    else:
        titulo_bar = f"Sin datos de EGRESOS K para {especie}, {etapa}, año {year_bar}"
        fig_bar.add_annotation(
            text="No hay registros disponibles.",
            xref="paper", yref="paper",
            x=0.5, y=0.5,
            showarrow=False,
            font=dict(size=14),
        )

    fig_bar.update_layout(
        title=titulo_bar,
        xaxis_title="Región",
        yaxis_title="Kilos (Cosecha)",
        template="simple_white",
        font=dict(size=13),
        margin={"l": 60, "r": 20, "t": 60, "b": 120},
        xaxis=dict(tickangle=-45),
    )

    return fig_ts, fig_bar

# ============================
# 6. EJECUCIÓN
# ============================
if __name__ == "__main__":
    app.run(
        host="127.0.0.1",   # sólo interno/local
        port=8054,
        debug=False,
    )