"""
HTML Report Generator for Intravariable Imperfection Analysis

This module contains all the HTML generation logic for creating comprehensive reports with collapsible sections and interactive elements.
"""

from datetime import datetime
from pathlib import Path

import polars as pl

from imperfekt.analysis.utils.html_reporting_helpers import (
    fig_to_html,
    get_apple_style_css,
    get_javascript,
)


class IntravariableHTMLReportGenerator:
    """Generates HTML reports for intravariable imperfection analysis results."""

    def __init__(self, analysis_instance):
        """
        Initialize the report generator.

        Args:
            analysis_instance: The IntravariableImperfection instance containing results
        """
        self.analysis = analysis_instance

    def generate_report(
        self, report_path: str = "intravariable_report.html", title: str = None
    ) -> Path:
        """
        Generates an HTML report from the analysis results.

        Args:
            report_path: The filename for the HTML report

        Returns:
            Path to the generated report file
        """
        # Get full report path
        full_report_path = self.analysis.save_path / report_path

        # Generate HTML content
        html_content = self._generate_html_content(title=title)

        # Write to file
        with open(full_report_path, "w", encoding="utf-8") as f:
            f.write(html_content)

        return full_report_path

    def _generate_html_content(self, title: str = None) -> str:
        """Generates the complete HTML content for the report."""
        # Get current timestamp
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # Start building HTML
        html = f"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Intravariable Imperfection Analysis Report</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <style>
        {get_apple_style_css()}
    </style>
</head>
<body>
    <div class="container">
        <header class="header">
            <div class="header-content">
                <h1>📊 Intravariable Imperfection Analysis Report{f" - {title}" if title else ""}</h1>
                <div class="metadata">
                    <span class="badge">Generated: {timestamp}</span>
                    <span class="badge">Analyzed Imperfection: {self.analysis.imperfection}</span>
                    <span class="badge">Columns: {len(self.analysis.cols)}</span>
                    <span class="badge">α = {self.analysis.alpha}</span>
                    <span class="badge">Total Observations: {self.analysis.df.height}, Unique Encounters: {self.analysis.df.select(pl.col(self.analysis.id_col).n_unique()).item()}</span>
                </div>
            </div>
        </header>

        <main class="main-content">
            {self._generate_column_statistics_section()}
            {self._generate_gap_statistics_section()}
            {self._generate_gap_returns_section()}
            {self._generate_markov_section()}
            {self._generate_autocorrelation_section()}
            {self._generate_windowed_significance_section()}
            {self._generate_datetime_section()}
        </main>

        <footer class="footer">
            <p>Report generated by Imperfekt Analysis Framework</p>
        </footer>
    </div>

    <script>
        {get_javascript()}
    </script>
</body>
</html>
"""
        return html

    def _generate_column_statistics_section(self) -> str:
        """Generates the column statistics section."""
        if self.analysis.results.cs_overall_statistics is None:
            return self._generate_empty_section(
                "📊 Column Statistics", "No column statistics available"
            )

        # Convert DataFrame to HTML
        try:
            table_html = self.analysis.results.cs_overall_statistics.to_pandas().to_html(
                index=False,
                table_id=None,
                classes="table",
                escape=False,
                float_format="%.4g",
            )
        except Exception:
            table_html = "<p>Unable to display column statistics table</p>"

        try:
            case_level_table_html = (
                self.analysis.results.cs_case_level_statistics.to_pandas()
                .describe()
                .to_html(
                    index=True,
                    table_id=None,
                    classes="table",
                    escape=False,
                    float_format="%.4g",
                )
            )
        except Exception:
            case_level_table_html = "<p>Unable to display column case-levelstatistics table</p>"

        plots_html = ""
        # Add plots if available
        for col in self.analysis.cols:
            # Collect both plots for this column
            col_plots = []

            if col in self.analysis.results.plots.cs_imperfection_histogram:
                try:
                    fig_html = fig_to_html(
                        self.analysis.results.plots.cs_imperfection_histogram[col]
                    )
                    col_plots.append(fig_html)
                except Exception as e:
                    col_plots.append(f"<p>Error loading histogram for {col}: {str(e)}</p>")

            if col in self.analysis.results.plots.cs_imperfection_boxplot:
                try:
                    fig_html = fig_to_html(self.analysis.results.plots.cs_imperfection_boxplot[col])
                    col_plots.append(fig_html)
                except Exception as e:
                    col_plots.append(f"<p>Error loading boxplot for {col}: {str(e)}</p>")

            # Only create the collapsible section if we have plots
            if col_plots:
                plots_content = "".join(col_plots)
                plots_html += f"""
                    <div class="plot-section">

                    <div class="plot-header" onclick="togglePlot(this)">
                        <h4>Imperfection Distribution - {col}</h4>
                        <span class="plot-chevron">▼</span>
                    </div>
                    <div class="plot-container collapsible-plot">
                        {plots_content}
                    </div>
                    </div>
                """

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">📊 Column Statistics</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="info">
                    <strong>What this shows:</strong>
                    <p>This section summarizes how often imperfections (e.g., missing values) occur in each column:</p>
                    <ul>
                        <li> Overall Statistics count the number and percentage of imperfect values per column across the full dataset.</li>
                        <li> Case-Level Statistics describe how imperfections are distributed within individual cases (mean, standard deviation, percentiles, etc.).</li>
                    </ul>
                    <p>The accompanying distribution plots illustrate how imperfections vary across cases.</p>
                </div>


                <div class="subsection">
                    <div class="subsection-header">
                        <h3>📋 Overall Statistics</h3>
                        <span class="subsection-chevron">▼</span>
                    </div>
                    <div class="subsection-content">

                        <div class="table-container">
                            {table_html}
                        </div>
                    </div>
                </div>
                <div class="subsection">
                    <div class="subsection-header">
                        <h3>📋 Case-Level Statistics</h3>
                        <span class="subsection-chevron">▼</span>
                    </div>
                    <div class="subsection-content">
                        <div class="table-container">
                            {case_level_table_html}
                        </div>
                    </div>
                </div>
                <div class="subsection">
                    <div class="subsection-header">
                        <h3>📈 Distribution Plots</h3>
                        <span class="subsection-chevron">▼</span>
                    </div>
                    <div class="subsection-content">
                        {plots_html}
                    </div>
                </div>
            </div>
        </section>
        """

    def _generate_gap_statistics_section(self) -> str:
        """Generates the gap statistics section."""
        if self.analysis.results.gs_gaps_observation_runs is None:
            return self._generate_empty_section("🔍 Gap Statistics", "No gap statistics available")

        # Generate descriptive statistics for gs_gaps_df by column
        gaps_describe_content = ""
        if (
            hasattr(self.analysis.results, "gs_gaps_df")
            and self.analysis.results.gs_gaps_df is not None
        ):
            try:
                # Generate descriptive statistics for each column
                gaps_describe_tables = ""

                # gs_gaps_df is a dict of polars dataframes
                if isinstance(self.analysis.results.gs_gaps_df, dict):
                    for col in self.analysis.cols:
                        try:
                            # Get the DataFrame for this specific column
                            if col in self.analysis.results.gs_gaps_df:
                                col_gaps_df = self.analysis.results.gs_gaps_df[col]

                                if not col_gaps_df.is_empty():
                                    # Get descriptive stats
                                    describe_df = col_gaps_df.to_pandas()[
                                        ["time_length", "count_clock_no"]
                                    ].describe()

                                    # Convert to HTML table
                                    table_html = describe_df.to_html(
                                        index=True,
                                        table_id=None,
                                        classes="table",
                                        escape=False,
                                        float_format="%.4g",
                                    )

                                    gaps_describe_tables += f"""
                                        <div class="plot-section">
                                            <div class="plot-header" onclick="togglePlot(this)">
                                                <h4>📊 Gap Statistics Summary - {col}</h4>
                                                <span class="plot-chevron">▼</span>
                                            </div>
                                            <div class="collapsible-plot">
                                                <div class="table-container">
                                                    {table_html}
                                                </div>
                                            </div>
                                        </div>
                                    """
                                else:
                                    gaps_describe_tables += f"""
                                        <div class="plot-section">
                                            <div class="plot-header" onclick="togglePlot(this)">
                                                <h4>📊 Gap Statistics Summary - {col}</h4>
                                                <span class="plot-chevron">▼</span>
                                            </div>
                                            <div class="collapsible-plot">
                                                <p>No gap data available for column {col}</p>
                                            </div>
                                        </div>
                                    """
                            else:
                                gaps_describe_tables += (
                                    f"<p>Column {col} not found in gap statistics data</p>"
                                )
                        except Exception as e:
                            gaps_describe_tables += (
                                f"<p>Error generating gap statistics for {col}: {str(e)}</p>"
                            )

                if gaps_describe_tables:
                    gaps_information_content = """
                    <div class="info">
                        <strong>What this shows:</strong>
                        <p> Descriptive statistics for gap lengths for each analyzed column.  </p>
                        <p> Lengths are captured in seconds and count_clock_no is the number of discrete timestamps. </p>
                        <p> The plots visualize the gap statistics summaries (time_length) as violin plots.  </p>
                    </div>
                    """
                    gaps_describe_content = f"""
                    <div class="subsection">
                        <div class="subsection-header">
                            <h3>📊 Gap Descriptive Statistics by Column</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            {gaps_describe_tables}
                        </div>
                    </div>
                    """
            except Exception as e:
                gaps_describe_content = f"<div class='warning'><p>Error generating gap descriptive statistics: {str(e)}</p></div>"

        plots_html = ""
        # Add gap plots if available
        for col in self.analysis.cols:
            if col in self.analysis.results.plots.gs_gap_lengths_violin:
                try:
                    fig_html = fig_to_html(self.analysis.results.plots.gs_gap_lengths_violin[col])
                    plots_html += f"""
                        <div class="plot-section">
                            <div class="plot-header" onclick="togglePlot(this)">
                                <h4>Gap Lengths - {col}</h4>
                                <span class="plot-chevron">▼</span>
                            </div>
                            <div class="plot-container collapsible-plot">
                                {fig_html}
                            </div>
                        </div>
                    """
                    gaps_plot_content = f"""
                    <div class="subsection">
                        <div class="subsection-header">
                             <h3>📈 Gap Analysis Plots</h3>
                            <span class="subsection-chevron">▼</span>
                        </div>
                        <div class="subsection-content">
                            {plots_html}
                        </div>
                    </div>
                    """
                except Exception as e:
                    plots_html += f"<p>Error loading gap plot for {col}: {str(e)}</p>"

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">🔍 Gap Statistics</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                {gaps_information_content}
                {gaps_describe_content}
                {gaps_plot_content}
            </div>
        </section>
        """

    def _generate_gap_returns_section(self) -> str:
        """Generates the gap returns analysis section."""
        if self.analysis.results.gr_gap_returns is None:
            return self._generate_empty_section(
                "🔄 Gap Returns Analysis", "No gap returns analysis available"
            )

        # Add Kruskal-Wallis results if available
        kruskal_content = ""
        if self.analysis.results.gr_gap_kruskal:
            kruskal_content = """<div class='subsection'>
                        <div class='subsection-header'>
                            <h3>🧮 Kruskal-Wallis Test Results</h3>
                            <span class='subsection-chevron'>▼</span>
                        </div>
                        <div class="subsection-content">"""

            # Create table for all columns
            kruskal_content += "<div class='table-container'><table class='table'>"
            kruskal_content += "<thead><tr><th>Column</th><th>H-Statistic</th><th>P-value</th><th>Effect Size (eta²)</th><th>Confidence Interval</th></tr></thead><tbody>"

            for col, kw_result in self.analysis.results.gr_gap_kruskal.items():
                if isinstance(kw_result, dict):
                    statistic = kw_result.get("statistic", "N/A")
                    p_value = kw_result.get("p_value", "N/A")
                    effect_size = kw_result.get("effect_size", "N/A")
                    ci_lower = kw_result.get("ci_lower", "N/A")
                    ci_upper = kw_result.get("ci_upper", "N/A")

                    # Format values
                    stat_str = (
                        f"{statistic:.4g}"
                        if isinstance(statistic, (int, float))
                        else str(statistic)
                    )
                    pval_str = (
                        f"{p_value:.4g}" if isinstance(p_value, (int, float)) else str(p_value)
                    )
                    es_str = (
                        f"{effect_size:.4g}"
                        if isinstance(effect_size, (int, float))
                        else str(effect_size)
                    )
                    ci_str = (
                        f"{ci_lower:.4g} - {ci_upper:.4g}"
                        if isinstance(ci_lower, (int, float)) and isinstance(ci_upper, (int, float))
                        else str(ci_lower) + " - " + str(ci_upper)
                    )

                    kruskal_content += f"<tr><td>{col}</td><td>{stat_str}</td><td>{pval_str}</td><td>{es_str}</td><td>{ci_str}</td></tr>"

            kruskal_content += "</tbody></table></div></div></div>"

        plots_html = ""
        # Add gap returns plots if available - group by column
        for col in self.analysis.cols:
            col_plots = []

            # Collect all plots for this column
            if col in self.analysis.results.plots.gr_gap_returns_boxplot:
                try:
                    fig_html = fig_to_html(self.analysis.results.plots.gr_gap_returns_boxplot[col])
                    col_plots.append(fig_html)
                except Exception as e:
                    col_plots.append(f"<p>Error loading gap returns boxplot: {str(e)}</p>")

            if (
                col in self.analysis.results.plots.gr_posthoc_pval_heatmap
                and self.analysis.results.plots.gr_posthoc_pval_heatmap[col]
            ):
                try:
                    fig_html = fig_to_html(self.analysis.results.plots.gr_posthoc_pval_heatmap[col])
                    col_plots.append(fig_html)
                except Exception as e:
                    col_plots.append(f"<p>Error loading post-hoc p-value heatmap: {str(e)}</p>")

            if (
                col in self.analysis.results.plots.gr_posthoc_es_heatmap
                and self.analysis.results.plots.gr_posthoc_es_heatmap[col]
            ):
                try:
                    fig_html = fig_to_html(self.analysis.results.plots.gr_posthoc_es_heatmap[col])
                    col_plots.append(fig_html)
                except Exception as e:
                    col_plots.append(f"<p>Error loading post-hoc effect size heatmap: {str(e)}</p>")
            if col_plots:
                plots_content = "".join(col_plots)
                plots_html += f"""
                    <div class="plot-section">
                    <div class="plot-header" onclick="togglePlot(this)">
                    <h4>Gap Returns Analysis - {col}</h4>
                    <span class="plot-chevron">▼</span>
                    </div>
                    <div class="plot-container collapsible-plot">
                    {plots_content}
                    </div>
                    </div>
                """

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">🔄 Gap Returns Analysis</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="info">
                <strong>What this shows:</strong>
                <p>A Kruskal–Wallis H test examines whether the first observation after a gap (the “gap return”) differs depending on the length of the gap:</p>
                <ul>
                    <li>If significant, post hoc pairwise tests identify which gap lengths differ.</li>
                    <li>Boxplots visualize the distribution of these returns, highlighting differences across gap lengths.</li>
                    <li>Predefined bins: {self.analysis.gr_gap_and_return_bins} (if None, quantiles [0.0, 0.125, …, 1.0] are used).</li>
                </ul>
                </div>

                {kruskal_content}
                <div class='subsection'>
                    <div class='subsection-header'>
                        <h3>📈 Gap Returns Analysis Plots</h3>
                        <span class='subsection-chevron'>▼</span>
                    </div>
                    <div class="subsection-content">
                        {plots_html}
                    </div>
                </div>
            </div>
        </section>
        """

    def _generate_markov_section(self) -> str:
        """Generates the Markov chain analysis section."""
        if (
            not hasattr(self.analysis.results, "mc_markov_summary")
            or not self.analysis.results.mc_markov_summary
        ):
            return self._generate_empty_section(
                "🔗 Markov Chain Analysis", "No Markov chain analysis available"
            )

        # Add Markov plots if available
        plots_html = ""
        for col in self.analysis.cols:
            if col in self.analysis.results.plots.mc_heatmap:
                try:
                    fig_html = fig_to_html(self.analysis.results.plots.mc_heatmap[col])
                    plots_html += f"""
                        <div class="plot-section">
                            <div class="plot-header" onclick="togglePlot(this)">
                                <h4>Markov Chain Heatmap - {col}</h4>
                                <span class="plot-chevron">▼</span>
                            </div>
                            <div class="plot-container collapsible-plot">
                                {fig_html}
                            </div>
                        </div>
                    """
                except Exception as e:
                    plots_html += f"<p>Error loading Markov plot for {col}: {str(e)}</p>"

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">🔗 Markov Chain Analysis</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="info">
                    <strong>What this shows:</strong>
                    <p>This section models imperfections as a Markov chain. Heatmaps present the transition matrix for each column:</p>
                    <ul>
                        <li>Probabilities of moving from indicated/imperfect values to observed values (and vice versa) are shown.</li>
                        <li>This highlights persistence or switching patterns of imperfections over time.</li>
                    </ul>
                    </div>

                <div class='subsection'>
                    <div class='subsection-header'>
                        <h3>📈 Markov Chain Visualizations</h3>
                        <span class='subsection-chevron'>▼</span>
                    </div>
                    <div class="subsection-content">
                        {plots_html}
                    </div>
                </div>
            </div>
        </section>
        """

    def _generate_autocorrelation_section(self) -> str:
        """Generates the autocorrelation analysis section."""
        if (
            not hasattr(self.analysis.results, "ac_autocorrelation")
            or not self.analysis.results.ac_autocorrelation
        ):
            return self._generate_empty_section(
                "📈 Autocorrelation Analysis", "No autocorrelation analysis available"
            )

        # Add autocorrelation plots if available
        plots_html = ""
        for col in self.analysis.cols:
            if col in self.analysis.results.plots.ac_lag_plot:
                try:
                    fig_html = fig_to_html(self.analysis.results.plots.ac_lag_plot[col])
                    plots_html += f"""
                        <div class="plot-section">
                            <div class="plot-header" onclick="togglePlot(this)">
                                <h4>Autocorrelation Function - {col}</h4>
                                <span class="plot-chevron">▼</span>
                            </div>
                            <div class="plot-container collapsible-plot">
                                {fig_html}
                            </div>
                        </div>
                    """
                except Exception as e:
                    plots_html += f"<p>Error loading autocorrelation plot for {col}: {str(e)}</p>"

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">📈 Autocorrelation Analysis</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="info">
                    <strong>What this shows:</strong>
                    <p>Autocorrelation measures whether imperfections cluster in time:</p>
                    <ul>
                        <li>Scatter plots display correlation values at different time lags (lags = {self.analysis.ac_autocorrelation_lags}).</li>
                        <li>The sample autocorrelation function (ACF) quantifies how the binary imperfection mask (imperfect vs. valid) relates to itself across various lags.</li>
                    </ul>
                    <p>This indicates whether imperfections tend to repeat periodically or cluster together.</p>
                </div>


                <div class='subsection'>
                    <div class='subsection-header'>
                        <h3>📈 Autocorrelation Plots</h3>
                        <span class='subsection-chevron'>▼</span>
                    </div>
                    <div class="subsection-content">
                        {plots_html}
                    </div>
                </div>
            </div>
        </section>
        """

    def _generate_windowed_significance_section(self) -> str:
        """Generates the windowed significance analysis section."""
        if (
            not hasattr(self.analysis.results, "ws_mwu_result")
            or self.analysis.results.ws_mwu_result is None
        ):
            return self._generate_empty_section(
                "🪟 Windowed Significance Analysis",
                "No windowed significance analysis available",
            )

        try:
            table_html = self.analysis.results.ws_mwu_result.to_pandas().to_html(
                index=False,
                table_id=None,
                classes="table",
                escape=False,
                float_format="%.4g",
            )
        except Exception as e:
            table_html = f"<p>Unable to display windowed significance table: {str(e)}</p>"

        # Add windowed significance plots if available
        plots_html = ""
        for col in self.analysis.cols:
            col_plots = []

            # Collect all plots for this column
            if col in self.analysis.results.plots.ws_overlay_histogram:
                try:
                    fig_html = fig_to_html(self.analysis.results.plots.ws_overlay_histogram[col])
                    col_plots.append(fig_html)
                except Exception as e:
                    col_plots.append(
                        f"<p>Error loading windowed significance overlay plot: {str(e)}</p>"
                    )

            if col in self.analysis.results.plots.ws_multi_boxplot:
                try:
                    fig_html = fig_to_html(self.analysis.results.plots.ws_multi_boxplot[col])
                    col_plots.append(fig_html)
                except Exception as e:
                    col_plots.append(
                        f"<p>Error loading windowed significance boxplot: {str(e)}</p>"
                    )

            # Only create the collapsible section if we have plots
            if col_plots:
                plots_content = "".join(col_plots)
                plots_html += f"""
                    <div class="plot-section">
                    <div class="plot-header" onclick="togglePlot(this)">
                        <h4>Windowed Significance Analysis - {col}</h4>
                        <span class="plot-chevron">▼</span>
                    </div>
                    <div class="plot-container collapsible-plot">
                        {plots_content}
                    </div>
                    </div>
                """

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">🪟 Windowed Significance Analysis</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="info">
                    <strong>What this shows:</strong>
                    <p>Mann–Whitney U-tests compare values within a fixed time window around an imperfect timestamp against values outside the window:</p>
                    <ul>
                        <li>Window duration: {self.analysis.ws_window_size}</li>
                        <li>Window location: {self.analysis.ws_window_location} (before, after, or both sides)</li>
                        <li>This tests whether imperfections coincide with significantly different observations in the time series.</li>
                        <li>Histograms and boxplots visualize the two distributions, making differences visible.</li>
                    </ul>
                </div>


                <div class='subsection'>
                    <div class='subsection-header'>
                        <h3>📋 Windowed Analysis Results</h3>
                        <span class='subsection-chevron'>▼</span>
                    </div>
                    <div class="subsection-content">
                        <div class="table-container">
                            {table_html}
                        </div>
                    </div>
                </div>

                <div class='subsection'>
                    <div class='subsection-header'>
                        <h3>📈 Windowed Significance Plots</h3>
                        <span class='subsection-chevron'>▼</span>
                    </div>
                    <div class="subsection-content">
                        {plots_html}
                    </div>
                </div>
            </div>
        </section>
        """

    def _generate_datetime_section(self) -> str:
        """Generates the datetime analysis section."""
        if (
            not hasattr(self.analysis.results, "dt_date_time_statistics")
            or not self.analysis.results.dt_date_time_statistics
        ):
            return self._generate_empty_section(
                "🕐 DateTime Analysis", "No datetime analysis available"
            )

        datetime_content = ""
        for col, datetime_data in self.analysis.results.dt_date_time_statistics.items():
            try:
                if isinstance(datetime_data, dict):
                    # Create collapsible tables for each statistic
                    tables_html = ""
                    for stat_name, df_data in datetime_data.items():
                        try:
                            # Convert polars DataFrame to HTML table
                            table_html = df_data.to_pandas().to_html(
                                index=False,
                                table_id=None,
                                classes="table",
                                escape=False,
                                float_format="%.4g",
                            )
                            tables_html += f"""
                                <div class="plot-section">
                                    <div class="plot-header" onclick="togglePlot(this)">
                                        <h4>{stat_name}</h4>
                                        <span class="plot-chevron">▼</span>
                                    </div>
                                    <div class="plot-container collapsible-plot">
                                        <div class="table-container">
                                            {table_html}
                                        </div>
                                    </div>
                                </div>
                            """
                        except Exception as e:
                            tables_html += (
                                f"<p>Error displaying table for {stat_name}: {str(e)}</p>"
                            )

                    datetime_content += f"""
                    <div class="plot-section">
                        <div class="plot-header" onclick="togglePlot(this)">
                            <h4>🕐 {col}</h4>
                            <span class="plot-chevron">▼</span>
                        </div>
                        <div class="collapsible-plot">
                            {tables_html}
                        </div>
                    </div>
                    """
                else:
                    datetime_content += f"""
                    <div class="plot-section">
                        <div class="plot-header" onclick="togglePlot(this)">
                            <h4>🕐 {col}</h4>
                            <span class="plot-chevron">▼</span>
                        </div>
                        <div class="collapsible-plot">
                            <p>{str(datetime_data)}</p>
                        </div>
                    </div>
                    """
            except Exception as e:
                datetime_content += f"<p>Error displaying datetime data for {col}: {str(e)}</p>"

        # Add datetime plots if available
        plots_html = ""
        for col in self.analysis.cols:
            if col in self.analysis.results.plots.dt_month_daytime_heatmap:
                try:
                    fig_html = fig_to_html(
                        self.analysis.results.plots.dt_month_daytime_heatmap[col]
                    )
                    plots_html += f"""
                        <div class="plot-section">
                            <div class="plot-header" onclick="togglePlot(this)">
                                <h4>DateTime Heatmap - {col}</h4>
                                <span class="plot-chevron">▼</span>
                            </div>
                            <div class="plot-container collapsible-plot">
                                {fig_html}
                            </div>
                        </div>
                    """
                except Exception as e:
                    plots_html += f"<p>Error loading datetime plot for {col}: {str(e)}</p>"

        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">🕐 DateTime Analysis</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="info">
                    <strong>What this shows:</strong>
                    <p>This section breaks down imperfections by temporal features:</p>
                    <ul>
                        <li>Distributions are analyzed across months, weekdays, and hours of the day for each column.</li>
                        <li>Heatmaps illustrate how the percentage of imperfections varies over time, highlighting potential seasonality and daily cycles.</li>
                    </ul>
                </div>

                <div class='subsection'>
                    <div class='subsection-header'>
                        <h3>📋 DateTime Statistics</h3>
                        <span class='subsection-chevron'>▼</span>
                    </div>
                    <div class="subsection-content">
                        {datetime_content}
                    </div>
                </div>

                <div class='subsection'>
                    <div class='subsection-header'>
                        <h3>📈 DateTime Visualizations</h3>
                        <span class='subsection-chevron'>▼</span>
                    </div>
                    <div class="subsection-content">
                        {plots_html}
                    </div>
                </div>
            </div>
        </section>
        """

    def _generate_empty_section(self, title: str, message: str) -> str:
        """Generates an empty section with a warning message."""
        return f"""
        <section class="section">
            <div class="section-header">
                <h2 class="section-title">{title}</h2>
                <span class="chevron">▼</span>
            </div>
            <div class="section-content">
                <div class="warning">
                    <p>{message}</p>
                </div>
            </div>
        </section>
        """
