import React, { useState, useEffect, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import axiosInstance from "../../../utils/axiosConfig";
import {
  DASHBOARD_STATS_URL,
  DASHBOARD_AUDIT_TRENDS_URL,
  DASHBOARD_HARM_DISTRIBUTIONS_URL,
  DASHBOARD_RPN_AUDIT_COUNTS_URL,
  DASHBOARD_OBSERVATIONS_OPEN_CLOSED_URL,
  DASHBOARD_SIO_OIO_CA_STATS_URL,
} from "../../../utils/config";
import DashboardHeader from "./pages/DashboardHeader";
import StatCard from "./common/StatCard";
import AddToPersonalizedButton from "./common/AddToPersonalizedButton";
import DashboardSection from "./common/DashboardSection";
import AnswersTrendChart from "./pages/AnswersTrendChart";
import SeverityOfHarmPieChart from "./pages/SeverityOfHarmPieChart";
import LikelihoodOfHarmPieChart from "./pages/LikelihoodOfHarmPieChart";
import RpnAuditBarChart from "./pages/RpnAuditBarChart";
import ObservationsOpenClosedBarChart from "./pages/ObservationsOpenClosedBarChart";
import SioOioCaCharts from "./pages/SioOioCaCharts";
import TopSitesList from "./pages/TopSitesList";
import RecentActivities from "./pages/RecentActivities";
import "./styles/Dashboard.css";

const defaultAnswersTrend = () =>
  Array.from({ length: 6 }, (_, i) => ({
    month: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"][i],
    answers: 0,
    submissions: 0,
    audits: 0,
  }));

const defaultTopSites = () => [];
const defaultRecentActivities = () => [];
const normalizeAuditTrendData = (rows = []) =>
  (Array.isArray(rows) ? rows : []).map((row) => ({
    ...row,
    month: row?.month ?? row?.label ?? "",
    audits: Number(row?.audits ?? row?.sat_audits ?? 0),
    submissions: Number(row?.submissions ?? row?.sat_submissions ?? 0),
    answers: Number(row?.answers ?? row?.sat_answers ?? 0),
  }));

const statIcons = {
  audits: (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <path d="m20 20-4.35-4.35" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  compliance: (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M20 6L9 17l-5-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  findings: (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <line x1="12" y1="9" x2="12" y2="13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <line x1="12" y1="17" x2="12.01" y2="17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  answers: (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M14 2v6h6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M16 13H8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M16 17H8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M10 9H8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
};

const currentYear = new Date().getFullYear();
const AUDIT_TREND_YEARS = Array.from({ length: 8 }, (_, i) => currentYear - 3 + i); // e.g. 2023–2030
const AUDIT_TREND_PERIODS = [
  { value: "daily", label: "Daily" },
  { value: "monthly", label: "Monthly" },
  { value: "quarterly", label: "Quarterly" },
  { value: "yearly", label: "Yearly" },
];

const Dashboard = () => {
  const navigate = useNavigate();
  const [selectedPeriod, setSelectedPeriod] = useState("month");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [dashboardData, setDashboardData] = useState(null);
  const [auditTrendYear, setAuditTrendYear] = useState(currentYear);
  const [auditTrendPeriod, setAuditTrendPeriod] = useState("monthly");
  const [auditTrendData, setAuditTrendData] = useState([]);
  const [auditTrendLoading, setAuditTrendLoading] = useState(false);
  const [severityOfHarmData, setSeverityOfHarmData] = useState([]);
  const [likelihoodOfHarmData, setLikelihoodOfHarmData] = useState([]);
  const [rpnAuditCountsData, setRpnAuditCountsData] = useState([]);
  const [observationsOpenClosedData, setObservationsOpenClosedData] = useState([]);
  const [obsTimePeriod, setObsTimePeriod] = useState("all");
  const [sioOioCaData, setSioOioCaData] = useState(null);

  useEffect(() => {
    let cancelled = false;

    const fetchDashboard = async () => {
      setLoading(true);
      setError(null);
      try {
        const params = selectedPeriod ? { params: { period: selectedPeriod } } : {};
        const [statsRes, harmRes, rpnCountsRes, sioOioCaRes] = await Promise.all([
          axiosInstance.get(DASHBOARD_STATS_URL, params),
          axiosInstance.get(DASHBOARD_HARM_DISTRIBUTIONS_URL).catch(() => ({ data: { data: {} } })),
          axiosInstance.get(DASHBOARD_RPN_AUDIT_COUNTS_URL).catch(() => ({ data: { data: [] } })),
          axiosInstance.get(DASHBOARD_SIO_OIO_CA_STATS_URL).catch(() => ({ data: {} })),
        ]);

        if (cancelled) return;

        const data = statsRes.data?.data;
        if (data) setDashboardData(data);

        const harmData = harmRes.data?.data;
        if (harmData) {
          setSeverityOfHarmData(harmData.severityOfHarm || []);
          setLikelihoodOfHarmData(harmData.likelihoodOfHarm || []);
        }
        const rpnCounts = rpnCountsRes.data?.data;
        if (Array.isArray(rpnCounts)) setRpnAuditCountsData(rpnCounts);
        const sioOioCa = sioOioCaRes.data?.data ?? sioOioCaRes.data;
        if (sioOioCa && typeof sioOioCa === 'object') setSioOioCaData(sioOioCa);
      } catch (err) {
        if (!cancelled) {
          setError(err.response?.data?.message || err.message || "Failed to load dashboard");
          setDashboardData(null);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    fetchDashboard();
    return () => { cancelled = true; };
  }, [selectedPeriod]);

  useEffect(() => {
    let cancelled = false;
    const fetchObservations = async () => {
      try {
        const res = await axiosInstance.get(DASHBOARD_OBSERVATIONS_OPEN_CLOSED_URL, {
          params: { period: obsTimePeriod },
        });
        if (!cancelled && res.data?.data) setObservationsOpenClosedData(res.data.data);
        else if (!cancelled) setObservationsOpenClosedData([]);
      } catch (err) {
        if (!cancelled) setObservationsOpenClosedData([]);
      }
    };
    fetchObservations();
    return () => { cancelled = true; };
  }, [obsTimePeriod]);

  useEffect(() => {
    let cancelled = false;
    const fetchAuditTrends = async () => {
      setAuditTrendLoading(true);
      try {
        const res = await axiosInstance.get(DASHBOARD_AUDIT_TRENDS_URL, {
          params: { year: auditTrendYear, period: auditTrendPeriod },
        });
        if (!cancelled && res.data?.data) {
          setAuditTrendData(normalizeAuditTrendData(res.data.data));
        }
        else if (!cancelled) setAuditTrendData([]);
      } catch (err) {
        if (!cancelled) setAuditTrendData([]);
      } finally {
        if (!cancelled) setAuditTrendLoading(false);
      }
    };
    fetchAuditTrends();
    return () => { cancelled = true; };
  }, [auditTrendYear, auditTrendPeriod]);

  const answersTrendData = useMemo(() => {
    if (!dashboardData?.answersTrend?.length) return defaultAnswersTrend();
    return dashboardData.answersTrend;
  }, [dashboardData]);

  const topSitesByCompliance = useMemo(() => {
    if (!dashboardData?.topSites?.length) return defaultTopSites();
    return dashboardData.topSites;
  }, [dashboardData]);

  const recentActivities = useMemo(() => {
    if (!dashboardData?.recentActivities?.length) return defaultRecentActivities();
    return dashboardData.recentActivities;
  }, [dashboardData]);

  const stats = useMemo(() => {
    const s = dashboardData?.stats;
    return [
      {
        label: "Total Audits",
        value: s ? String(s.totalAudits ?? 0) : "0",
        change: "+0",
        trend: "up",
        icon: statIcons.audits,
        description: "All audits created in the system (planned and in progress). Use this to track audit workload and coverage.",
      },
      {
        label: "Audit Completion Rate",
        value: s ? `${s.complianceRate ?? 0}%` : "0%",
        subtitle: (() => {
          if (!s) return "0 of 0 audits";
          const total = s.totalAudits ?? 0;
          const completed = Math.round(((s.complianceRate ?? 0) / 100) * total);
          return `${completed} of ${total} audit${total !== 1 ? "s" : ""} completed`;
        })(),
        change: "+0%",
        trend: "up",
        icon: statIcons.compliance,
        description: "Percentage of audits that are closed based on audit status (audit completion rate). Click to view audits status.",
        to: "/audit-status",
      },
      {
        label: "Critical Findings",
        value: s ? String(s.auditsWithRpn32To128 ?? 0) : "0",
        subtitle: s ? `${s.auditsWithRpn32To128 ?? 0} audits with RPN 32–128` : "0 audits with RPN 32–128",
        change: "0",
        trend: "down",
        icon: statIcons.findings,
        description: "Audits that have at least one answer with RPN between 32 and 128. Click to view list.",
        to: "/critical-findings",
      },
      {
        label: "Total Users",
        value: s ? String(s.totalUsers ?? 0).replace(/\B(?=(\d{3})+(?!\d))/g, ",") : "0",
        subtitle: s ? `${s.totalUsers ?? 0} user${(s.totalUsers ?? 0) !== 1 ? "s" : ""} in system` : "0 users in system",
        change: "+0",
        trend: "up",
        icon: statIcons.answers,
        description: "Total users in the system. Click to view users list.",
        to: "/users",
      },
    ];
  }, [dashboardData?.stats]);

  if (loading) {
    return (
      <div className="dashboard-container">
        <div className="dashboard-loading">
          <div className="dashboard-loading-spinner" />
          <p>Loading dashboard…</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="dashboard-container">
        <div className="dashboard-error">
          <p>{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="dashboard-container">
      <DashboardHeader
        selectedPeriod={selectedPeriod}
        onPeriodChange={setSelectedPeriod}
        onViewLogs={() => navigate("/activity-log")}
      />

      <div className="dashboard-stats-wrap">
        <div className="dashboard-stats-grid">
          {stats.map((stat, index) => {
            const widgetIds = ["statTotalAudits", "statComplianceRate", "statCriticalFindings", "statTotalUsers"];
            const widgetId = widgetIds[index];
            return (
              <div key={index} className="dashboard-stat-card-wrap dashboard-stat-card-wrap--has-add-btn">
                <AddToPersonalizedButton widgetId={widgetId} />
                <StatCard stat={stat} index={index} />
              </div>
            );
          })}
        </div>
      </div>

      <DashboardSection
        title="Audit Trends"
        description="View audit, submission and answer counts by year and time period."
      >
        <div className="dashboard-charts-row dashboard-charts-row-1">
          {auditTrendLoading ? (
            <div className="audit-trends-loading">Loading audit trends…</div>
          ) : (
            <AnswersTrendChart
              data={auditTrendData.length ? auditTrendData : defaultAnswersTrend()}
              variant="auditTrends"
              widgetId="answersTrend"
              xAxisInterval={auditTrendPeriod === "daily" && auditTrendData.length > 30 ? Math.ceil(auditTrendData.length / 14) : undefined}
              filterControls={
                <div className="audit-trends-filters">
                  <div className="audit-trends-filter-group">
                    <label htmlFor="audit-trend-year" className="audit-trends-filter-label">Select Year</label>
                    <select
                      id="audit-trend-year"
                      value={auditTrendYear}
                      onChange={(e) => setAuditTrendYear(Number(e.target.value))}
                      className="audit-trends-select"
                      aria-label="Select year for audit trends"
                    >
                      {AUDIT_TREND_YEARS.map((y) => (
                        <option key={y} value={y}>{y}</option>
                      ))}
                    </select>
                  </div>
                  <div className="audit-trends-filter-group">
                    <label htmlFor="audit-trend-period" className="audit-trends-filter-label">Time Period</label>
                    <select
                      id="audit-trend-period"
                      value={auditTrendPeriod}
                      onChange={(e) => setAuditTrendPeriod(e.target.value)}
                      className="audit-trends-select"
                      aria-label="Select time period for audit trends"
                    >
                      {AUDIT_TREND_PERIODS.map(({ value, label }) => (
                        <option key={value} value={value}>{label}</option>
                      ))}
                    </select>
                  </div>
                </div>
              }
            />
          )}
        </div>
      </DashboardSection>

      <DashboardSection
        title="Audits by RPN Value, Severity of Harm & Likelihood of Harm"
        description="RPN audit distribution (top); severity and likelihood of harm distributions (bottom). Click charts to view details."
      >
        <div className="dashboard-rpn-harm-grid">
          <div className="dashboard-rpn-harm-top">
            <RpnAuditBarChart data={rpnAuditCountsData} />
          </div>
          <div className="dashboard-rpn-harm-bottom">
            <SeverityOfHarmPieChart data={severityOfHarmData} />
            <LikelihoodOfHarmPieChart data={likelihoodOfHarmData} />
          </div>
        </div>
      </DashboardSection>

      <DashboardSection
        title="Observations: Open vs Closed"
        description="How many opening observations are open (no closing linked) vs closed (closing form linked)."
      >
        <div className="dashboard-charts-row dashboard-charts-row-1">
          <ObservationsOpenClosedBarChart
            data={observationsOpenClosedData}
            timePeriod={obsTimePeriod}
            onTimePeriodChange={setObsTimePeriod}
          />
        </div>
      </DashboardSection>

      <DashboardSection
        title="SIO / OIO / CA & SIO PA %"
      >
        <div className="dashboard-charts-row dashboard-charts-row-1">
          <SioOioCaCharts data={sioOioCaData} />
        </div>
      </DashboardSection>

      <DashboardSection
        title="Sites & Activity"
        description="Top sites by compliance and recent activity."
      >
        <div className="dashboard-main-grid">
          <TopSitesList sites={topSitesByCompliance} widgetId="topSites" />
          <RecentActivities activities={recentActivities} widgetId="recentActivities" />
        </div>
      </DashboardSection>
    </div>
  );
};

export default Dashboard;
