import { useMemo, useState } from "react";
import DashboardRoleTrendChart from "./DashboardRoleTrendChart.jsx";
import { buildTrendSeriesData, TREND_GRANULARITY } from "./dashboardTrendSeries.js";
import { buildCategoryMapsFromStatuses, categorizeExecutorRow } from "./executorAssignmentCategories.js";
import "./ra-admin-trend-embed.css";

function isAssignedAssessment(a) {
  return Boolean(a.executor_id || a.verifier_id);
}

export default function RAAdminTrendWidget({ assessments, statuses }) {
  const [trendGranularity, setTrendGranularity] = useState(TREND_GRANULARITY.MONTH);
  const { executorMap } = useMemo(() => buildCategoryMapsFromStatuses(statuses), [statuses]);
  const assignedForTrend = useMemo(
    () => (Array.isArray(assessments) ? assessments : []).filter(isAssignedAssessment),
    [assessments]
  );

  const adminTrendData = useMemo(
    () =>
      buildTrendSeriesData(
        assignedForTrend,
        categorizeExecutorRow,
        executorMap,
        trendGranularity
      ),
    [assignedForTrend, executorMap, trendGranularity]
  );

  return (
    <div className="ex-dash ra-admin-trend-embed">
      <DashboardRoleTrendChart
        data={adminTrendData}
        role="admin"
        hasAssignments={assignedForTrend.length > 0}
        granularity={trendGranularity}
        onGranularityChange={setTrendGranularity}
        subtitle="Assigned and completed assessments over time"
        seriesLabels={{ assigned: "Assigned", completed: "Completed" }}
      />
    </div>
  );
}
