import {
  Area,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
  AreaChart
} from 'recharts';
import AddToPersonalizedButton from '../common/AddToPersonalizedButton.jsx';
import { TREND_GRANULARITY } from './dashboardTrendSeries.js';

const TREND_PERIOD_OPTIONS = [
  { value: TREND_GRANULARITY.WEEK, label: 'Weekly' },
  { value: TREND_GRANULARITY.MONTH, label: 'Monthly' },
  { value: TREND_GRANULARITY.QUARTER, label: 'Quarterly' },
  { value: TREND_GRANULARITY.YEAR, label: 'Yearly' }
];

/**
 * @param {object} props
 * @param {{ label: string, assigned: number, completed: number }[]} props.data
 * @param {'executor'|'verifier'|'admin'} props.role
 * @param {boolean} props.hasAssignments
 * @param {import('./dashboardTrendSeries.js').TrendGranularity} props.granularity
 * @param {string} [props.caption]
 * @param {{ assigned?: string, completed?: string }} [props.seriesLabels] — legend & tooltip (defaults: In progress / Completed)
 * @param {string} [props.emptyMessage]
 * @param {string} [props.addToPersonalizedWidgetId] — when set, shows “add to personalised dashboard” inside the card header
 * @param {string} [props.subtitle] — one-line description under the main heading
 */
/**
 * @param {object} props
 * @param {import('./dashboardTrendSeries.js').TrendGranularity} props.granularity
 * @param {(g: import('./dashboardTrendSeries.js').TrendGranularity) => void} [props.onGranularityChange]
 */
export default function DashboardRoleTrendChart({
  data,
  role,
  caption,
  hasAssignments,
  granularity,
  onGranularityChange,
  seriesLabels,
  emptyMessage,
  addToPersonalizedWidgetId,
  subtitle
}) {
  const g = granularity ?? TREND_GRANULARITY.WEEK;
  const assignedLabel = seriesLabels?.assigned ?? 'In progress';
  const completedLabel = seriesLabels?.completed ?? 'Completed';

  const axisProps =
    g === TREND_GRANULARITY.YEAR
      ? { angle: 0, textAnchor: 'middle', height: 32, tick: { fontSize: 10, fill: 'var(--ex-muted, #737373)' } }
      : g === TREND_GRANULARITY.MONTH || g === TREND_GRANULARITY.QUARTER
        ? {
            angle: -32,
            textAnchor: 'end',
            height: 58,
            tick: { fontSize: 9, fill: 'var(--ex-muted, #737373)' }
          }
        : {
            angle: -28,
            textAnchor: 'end',
            height: 52,
            tick: { fontSize: 10, fill: 'var(--ex-muted, #737373)' }
          };

  const gid = role === 'verifier' ? 'ver' : role === 'admin' ? 'adm' : 'ex';
  const assignedStroke =
    role === 'verifier' ? '#64748b' : role === 'admin' ? '#8b1538' : '#dc2626';
  const completedStroke = role === 'admin' ? '#189e52' : '#0f172a';

  const canChangeGranularity = typeof onGranularityChange === 'function';

  const emptyMsgDefault =
    role === 'admin'
      ? 'No assigned assessments yet — trend will appear once you assign executors or verifiers.'
      : 'No assignments yet — trend will appear once you have queue items.';

  const periodSelector = canChangeGranularity ? (
    <div
      className="ex-dash-trend-period"
      role="group"
      aria-label="Time span"
    >
      {TREND_PERIOD_OPTIONS.map(({ value, label }) => (
        <button
          key={value}
          type="button"
          className={`ex-dash-trend-period-btn${
            g === value ? ' ex-dash-trend-period-btn--active' : ''
          }`}
          onClick={() => onGranularityChange(value)}
          aria-pressed={g === value}
        >
          {label}
        </button>
      ))}
    </div>
  ) : null;

  const addToPd =
    addToPersonalizedWidgetId != null && addToPersonalizedWidgetId !== '' ? (
      <AddToPersonalizedButton widgetId={addToPersonalizedWidgetId} />
    ) : null;

  if (!hasAssignments) {
    return (
      <div className={`ex-dash-trend ex-dash-trend--empty ex-dash-trend--role-${role}`}>
        {(periodSelector || addToPd || subtitle) && (
          <div className="ex-dash-trend-head ex-dash-trend-head--empty">
            <div className="ex-dash-trend-head-intro">
              <span className="ex-dash-trend-title">Assessments trends</span>
              {subtitle ? <p className="ex-dash-trend-subtitle">{subtitle}</p> : null}
            </div>
            <div className="ex-dash-trend-head-controls">
              {addToPd}
              {periodSelector}
            </div>
          </div>
        )}
        <p className="ex-dash-trend-empty-msg">{emptyMessage ?? emptyMsgDefault}</p>
        {caption ? <p className="ex-dash-trend-caption">{caption}</p> : null}
      </div>
    );
  }

  return (
    <div className={`ex-dash-trend ex-dash-trend--role-${role}`}>
      <div className="ex-dash-trend-head">
        <div className="ex-dash-trend-head-intro">
          <span className="ex-dash-trend-title">Assessments trends</span>
          {subtitle ? <p className="ex-dash-trend-subtitle">{subtitle}</p> : null}
        </div>
        <div className="ex-dash-trend-head-controls">
          {addToPd}
          {periodSelector}
          <span className="ex-dash-trend-legend-inline" aria-hidden>
            <span className="ex-dash-trend-key ex-dash-trend-key--assigned" /> {assignedLabel}
            <span className="ex-dash-trend-key ex-dash-trend-key--completed" /> {completedLabel}
          </span>
        </div>
      </div>
      <div className="ex-dash-trend-chart-wrap">
        <ResponsiveContainer width="100%" height={240}>
          <AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 4 }}>
            <defs>
              <linearGradient id={`fillAssigned-${gid}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={assignedStroke} stopOpacity={0.28} />
                <stop offset="100%" stopColor={assignedStroke} stopOpacity={0.02} />
              </linearGradient>
              <linearGradient id={`fillCompleted-${gid}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={completedStroke} stopOpacity={role === 'admin' ? 0.22 : 0.2} />
                <stop offset="100%" stopColor={completedStroke} stopOpacity={0.02} />
              </linearGradient>
            </defs>
            <CartesianGrid
              strokeDasharray="4 8"
              stroke="rgba(148, 163, 184, 0.35)"
              vertical={false}
            />
            <XAxis dataKey="label" interval={0} {...axisProps} stroke="rgba(100, 116, 139, 0.5)" tickLine={false} axisLine={false} />
            <YAxis
              allowDecimals={false}
              tick={{ fontSize: 10, fill: 'var(--ex-muted, #737373)' }}
              width={36}
              tickLine={false}
              axisLine={false}
            />
            <Tooltip
              contentStyle={{
                borderRadius: 12,
                border: 'none',
                boxShadow: '0 8px 30px rgba(15, 23, 42, 0.12)',
                fontSize: 12
              }}
              labelStyle={{ fontWeight: 600 }}
              formatter={(value, name) => [
                value,
                name === 'assigned' ? assignedLabel : completedLabel
              ]}
            />
            <Area
              type="monotone"
              dataKey="assigned"
              name="assigned"
              stroke={assignedStroke}
              strokeWidth={2.5}
              fill={`url(#fillAssigned-${gid})`}
              dot={{ r: 0 }}
              activeDot={{ r: 5, strokeWidth: 0 }}
            />
            <Area
              type="monotone"
              dataKey="completed"
              name="completed"
              stroke={completedStroke}
              strokeWidth={2.5}
              fill={`url(#fillCompleted-${gid})`}
              dot={{ r: 0 }}
              activeDot={{ r: 5, strokeWidth: 0 }}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>
      {caption ? <p className="ex-dash-trend-caption">{caption}</p> : null}
    </div>
  );
}
