import React, { useState, useEffect, useMemo, useRef } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import axiosInstance from "../../../../utils/axiosConfig";
import {
  DASHBOARD_HARM_DISTRIBUTIONS_URL,
  DASHBOARD_HARM_SEVERITY_AUDITS_URL,
} from "../../../../utils/config";
import "../styles/HarmStatsPage.css";

const SEVERITY_COLORS = {
  Fatality: "#ef4444",
  Severe: "#f97316",
  High: "#eab308",
  Medium: "#22c55e",
  Low: "#3b82f6",
};

const VIEW_LIST = "list";
const VIEW_CARD = "card";

const SeverityOfHarmStats = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState("All");
  const [audits, setAudits] = useState([]);
  const [auditsLoading, setAuditsLoading] = useState(false);
  const [auditsError, setAuditsError] = useState(null);
  const [viewMode, setViewMode] = useState(VIEW_CARD);
  const [auditSearchQuery, setAuditSearchQuery] = useState("");
  const appliedSegmentRef = useRef(null);

  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await axiosInstance.get(DASHBOARD_HARM_DISTRIBUTIONS_URL);
      if (response.data?.success && response.data?.data?.severityOfHarm) {
        setData(response.data.data.severityOfHarm);
      } else {
        setData([]);
      }
    } catch (err) {
      console.error("Error fetching severity of harm stats:", err);
      setError("Failed to load statistics. Please try again.");
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    if (!data.length) {
      setActiveTab("All");
      return;
    }
    const names = data.map((row) => row.name).filter(Boolean);
    const segmentFromUrl = searchParams.get("segment");
    if (segmentFromUrl && names.includes(segmentFromUrl)) {
      if (appliedSegmentRef.current !== segmentFromUrl) {
        appliedSegmentRef.current = segmentFromUrl;
        setActiveTab(segmentFromUrl);
      }
    } else {
      appliedSegmentRef.current = null;
      if (activeTab !== "All" && !names.includes(activeTab)) {
        setActiveTab("All");
      }
    }
  }, [data, activeTab, searchParams]);

  const total = useMemo(
    () => data.reduce((sum, row) => sum + (row.value || 0), 0),
    [data],
  );

  const tabOptions = useMemo(() => {
    const names = data.map((row) => row.name).filter(Boolean);
    const uniqueNames = Array.from(new Set(names));
    return ["All", ...uniqueNames];
  }, [data]);

  const visibleRows = useMemo(() => {
    if (!data.length) return [];
    if (activeTab === "All") return data;
    return data.filter((row) => row.name === activeTab);
  }, [data, activeTab]);

  const fetchAuditsForTab = async (tabLabel) => {
    // When there is no distribution data yet, do not call the API.
    if (!data.length) {
      setAudits([]);
      return;
    }
    try {
      setAuditsLoading(true);
      setAuditsError(null);
      const isFilteredTab = Boolean(tabLabel && tabLabel !== "All");
      const requestVariants = isFilteredTab
        ? [
            { params: { severity: tabLabel }, timeout: 20000 },
            { params: { severity_of_harm: tabLabel }, timeout: 20000 },
          ]
        : [{ timeout: 20000 }];
      let response = null;
      let lastError = null;
      for (const requestConfig of requestVariants) {
        try {
          response = await axiosInstance.get(
            DASHBOARD_HARM_SEVERITY_AUDITS_URL,
            requestConfig
          );
          break;
        } catch (requestError) {
          lastError = requestError;
        }
      }
      if (!response) {
        throw lastError || new Error("Failed to load severity audits");
      }
      if (response.data?.success && Array.isArray(response.data.data)) {
        setAudits(response.data.data);
      } else {
        setAudits([]);
      }
    } catch (err) {
      console.error("Error fetching audits by severity of harm:", err);
      console.error("Severity audits API details:", {
        status: err?.response?.status,
        message: err?.response?.data?.message || err?.message,
      });
      setAuditsError("Failed to load audits for this severity. Please try again.");
      setAudits([]);
    } finally {
      setAuditsLoading(false);
    }
  };

  useEffect(() => {
    if (!loading) {
      fetchAuditsForTab(activeTab);
    }
  }, [activeTab, loading, data.length]);

  const filteredAudits = useMemo(() => {
    const query = auditSearchQuery.trim().toLowerCase();
    if (!query) return audits;
    return audits.filter(
      (audit) =>
        (audit.audit_name && String(audit.audit_name).toLowerCase().includes(query)) ||
        (audit.auditor_name && String(audit.auditor_name).toLowerCase().includes(query)) ||
        (audit.location_name && String(audit.location_name).toLowerCase().includes(query)) ||
        (audit.audit_id && String(audit.audit_id).includes(query))
    );
  }, [audits, auditSearchQuery]);

  const formatDateTime = (dateStr) => {
    if (!dateStr) return "—";
    const d = new Date(dateStr);
    return d.toLocaleString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  return (
    <div className="harm-stats-container">
      <div className="harm-stats-header">
        <h1 className="harm-stats-title">
          Severity of Harm
          <span className="harm-stats-title-badge">Detailed statistics</span>
        </h1>
        <div className="harm-stats-actions">
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate("/dashboard")}
          >
            Back to Dashboard
          </button>
          <button
            type="button"
            className="btn btn-primary"
            onClick={fetchData}
            disabled={loading}
          >
            {loading ? "Loading…" : "Refresh"}
          </button>
        </div>
      </div>

      <p className="harm-stats-intro">
        Distribution of form answers by severity of harm (Fatality, Severe, High, Medium, Low).
      </p>

      {error && (
        <div className="harm-stats-error">
          <p>{error}</p>
        </div>
      )}

      {loading ? (
        <div className="harm-stats-loading">
          <div className="harm-stats-spinner" />
          <p>Loading statistics…</p>
        </div>
      ) : (
        <>
          <div className="harm-stats-summary">
            <div className="harm-stats-summary-card">
              <span className="harm-stats-summary-label">Total audits</span>
              <span className="harm-stats-summary-value">{total}</span>
            </div>
            <div className="harm-stats-summary-card">
              <span className="harm-stats-summary-label">Categories</span>
              <span className="harm-stats-summary-value">{data.length}</span>
            </div>
          </div>

          <div className="harm-stats-tabs">
            <div className="harm-stats-tabs-list" role="tablist" aria-label="Filter audits by severity of harm">
              {tabOptions.map((tab) => (
                <button
                  key={tab}
                  type="button"
                  role="tab"
                  aria-selected={activeTab === tab}
                  className={
                    activeTab === tab
                      ? "harm-stats-tab harm-stats-tab--active"
                      : "harm-stats-tab"
                  }
                  onClick={() => setActiveTab(tab)}
                >
                  {tab === "All" ? "All audits" : tab}
                </button>
              ))}
            </div>
            <p className="harm-stats-tabs-heading">
              {activeTab === "All"
                ? "All audits grouped by severity of harm."
                : `${activeTab} audits – distribution within all responses.`}
            </p>
          </div>

          <div className="harm-stats-table-wrap">
            <table className="harm-stats-table">
              <thead>
                <tr>
                  <th>Severity of Harm</th>
                  <th>Count</th>
                  <th>Percentage</th>
                  <th>Share</th>
                </tr>
              </thead>
              <tbody>
                {visibleRows.length === 0 ? (
                  <tr>
                    <td colSpan={4} className="harm-stats-empty">
                      No severity of harm data yet. Submit observations with severity of harm questions to see statistics here.
                    </td>
                  </tr>
                ) : (
                  visibleRows.map((row, index) => {
                    const pct = total ? ((row.value || 0) / total) * 100 : 0;
                    const severity = row.name || "Other";
                    const baseColor = SEVERITY_COLORS[severity] || "#64748b";
                    const barStyle = {
                      width: `${pct}%`,
                      background: `linear-gradient(90deg, ${baseColor} 0%, ${baseColor}cc 55%, ${baseColor}99 100%)`,
                    };

                    return (
                      <tr
                        key={severity || index}
                        className="harm-stats-row"
                      >
                        <td className="harm-stats-name">{severity}</td>
                        <td>{row.value ?? 0}</td>
                        <td>{pct.toFixed(1)}%</td>
                        <td>
                          <div className="harm-stats-bar-wrap">
                            <div
                              className="harm-stats-bar"
                              style={barStyle}
                            />
                          </div>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>

          <div className="harm-stats-audits-section">
            <div className="harm-stats-audits-header">
              <h2 className="harm-stats-audits-title">
                Audits for{" "}
                {activeTab === "All" ? "all severities" : activeTab}
              </h2>
              <button
                type="button"
                className="btn btn-secondary btn-sm"
                disabled={auditsLoading}
                onClick={() => fetchAuditsForTab(activeTab)}
              >
                {auditsLoading ? "Loading…" : "Refresh audits"}
              </button>
            </div>

            {audits.length > 0 && (
              <div className="harm-stats-audits-search-wrap">
                <input
                  type="text"
                  className="harm-stats-audits-search-input"
                  placeholder="Search audits by name, auditor, location or ID…"
                  value={auditSearchQuery}
                  onChange={(e) => setAuditSearchQuery(e.target.value)}
                  aria-label="Search audits"
                />
              </div>
            )}

            {audits.length > 0 && (
              <div className="harm-stats-audits-view-tabs">
                <button
                  type="button"
                  className={
                    viewMode === VIEW_LIST
                      ? "harm-stats-audits-tab harm-stats-audits-tab--active"
                      : "harm-stats-audits-tab"
                  }
                  onClick={() => setViewMode(VIEW_LIST)}
                >
                  <span className="harm-stats-audits-tab-label">List view</span>
                  <span className="harm-stats-audits-tab-desc">
                    Compact table of audits
                  </span>
                </button>
                <button
                  type="button"
                  className={
                    viewMode === VIEW_CARD
                      ? "harm-stats-audits-tab harm-stats-audits-tab--active"
                      : "harm-stats-audits-tab"
                  }
                  onClick={() => setViewMode(VIEW_CARD)}
                >
                  <span className="harm-stats-audits-tab-label">Card view</span>
                  <span className="harm-stats-audits-tab-desc">
                    Detailed audit cards
                  </span>
                </button>
              </div>
            )}

            {auditsError && (
              <div className="harm-stats-audits-error">
                {auditsError}
              </div>
            )}

            {auditsLoading && !audits.length ? (
              <div className="harm-stats-audits-loading">
                Loading audits…
              </div>
            ) : audits.length === 0 ? (
              <div className="harm-stats-audits-empty">
                No audits found for this severity yet.
              </div>
            ) : filteredAudits.length === 0 ? (
              <div className="harm-stats-audits-empty">
                No audits match your search.
              </div>
            ) : viewMode === VIEW_LIST ? (
              <div className="harm-stats-audits-table-wrap">
                <table className="harm-stats-audits-table">
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>Audit</th>
                      <th>Severity</th>
                      <th>Auditor</th>
                      <th>Location</th>
                      <th>Created</th>
                      <th>Observed</th>
                      <th />
                    </tr>
                  </thead>
                  <tbody>
                    {filteredAudits.map((audit) => (
                      <tr key={audit.audit_id}>
                        <td>#{audit.audit_id}</td>
                        <td>{audit.audit_name || "—"}</td>
                        <td>{audit.severity_label || activeTab}</td>
                        <td>{audit.auditor_name || "—"}</td>
                        <td>{audit.location_name || "—"}</td>
                        <td>{formatDateTime(audit.created_at)}</td>
                        <td>{formatDateTime(audit.observed_at)}</td>
                        <td className="harm-stats-audits-table-actions">
                          <button
                            type="button"
                            className="btn btn-sm btn-forms"
                            onClick={() =>
                              navigate(`/audit/${audit.audit_id}/forms`)
                            }
                          >
                            View
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="harm-stats-audits-list">
                {filteredAudits.map((audit) => (
                  <article
                    key={audit.audit_id}
                    className="harm-stats-audit-card"
                  >
                    <header className="harm-stats-audit-card-header">
                      <div className="harm-stats-audit-title-wrap">
                        <h3 className="harm-stats-audit-title">
                          {audit.audit_name || "—"}
                        </h3>
                        <span className="harm-stats-audit-id">
                          #{audit.audit_id}
                        </span>
                      </div>
                      <span className="harm-stats-audit-severity">
                        {audit.severity_label || activeTab}
                      </span>
                    </header>
                    <dl className="harm-stats-audit-meta">
                      <div className="harm-stats-audit-meta-row">
                        <dt>Auditor</dt>
                        <dd>{audit.auditor_name || "—"}</dd>
                      </div>
                      <div className="harm-stats-audit-meta-row">
                        <dt>Location</dt>
                        <dd>{audit.location_name || "—"}</dd>
                      </div>
                      <div className="harm-stats-audit-meta-row">
                        <dt>Created</dt>
                        <dd>{formatDateTime(audit.created_at)}</dd>
                      </div>
                      <div className="harm-stats-audit-meta-row">
                        <dt>Observed</dt>
                        <dd>{formatDateTime(audit.observed_at)}</dd>
                      </div>
                    </dl>
                    <footer className="harm-stats-audit-footer">
                      <button
                        type="button"
                        className="btn btn-sm btn-forms"
                        onClick={() =>
                          navigate(`/audit/${audit.audit_id}/forms`)
                        }
                      >
                        View observations
                      </button>
                    </footer>
                  </article>
                ))}
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
};

export default SeverityOfHarmStats;
