import { useEffect, useMemo, useState } from 'react';
import { getSessionUserId } from '../../apiConfig.js';
import { fetchExecutorDashboardData } from '../../api.js';
import {
  buildCategoryMapsFromStatuses,
  countByCategory,
  categorizeExecutorRow,
  categorizeVerifierRow
} from './executorAssignmentCategories.js';
import { buildTrendSeriesData, TREND_GRANULARITY } from './dashboardTrendSeries.js';
import DashboardRoleTrendChart from './DashboardRoleTrendChart.jsx';
import DashboardBucketPieChart from './DashboardBucketPieChart.jsx';
import './ExecutorDashboard.css';

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' }
];

const ROWS_EXECUTOR = [
  { key: 'not_started', title: 'Not Started',          hint: 'Open jobs waiting for you',       category: 'not_started' },
  { key: 'verification_required', title: 'Submitted to Verifier', hint: 'With verifier for review', category: 'verification_required' },
  { key: 'returned',    title: 'Returned by Verifier', hint: 'Verifier sent this back for your follow-up', category: 'returned' },
  { key: 'done',        title: 'Assessment Done',     hint: 'Ready or completed reviews',      category: 'done' }
];
const ROWS_VERIFIER = [
  { key: 'not_started', title: 'Not Started',         hint: 'Awaiting your first pass',                category: 'not_started' },
  { key: 'in_process',  title: 'Resubmitted by executor', hint: 'Executor resubmitted — continue your review', category: 'in_process' },
  { key: 'returned',    title: 'Returned to executor', hint: 'Sent back — waiting on executor',        category: 'returned' },
  { key: 'done',        title: 'Assessment Done',    hint: 'Signed-off items',                         category: 'done' }
];

/** Saturated fills for pie chart segments. */
function pieBucketFill(category, isVerifier) {
  const shared = {
    not_started: '#facc15',
    done: '#34d399'
  };
  if (isVerifier) {
    const v = {
      ...shared,
      returned: '#3b82f6',
      in_process: '#fb923c'
    };
    return v[category] ?? '#94a3b8';
  }
  const e = { ...shared, returned: '#c084fc', verification_required: '#fb923c' };
  return e[category] ?? '#94a3b8';
}

/* ── Inline SVG icons ── */
function IconUser() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
      <circle cx="12" cy="8" r="4" /><path d="M4.5 20a7.5 7.5 0 0 1 15 0" strokeLinecap="round" />
    </svg>
  );
}
function IconSearch() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
      <circle cx="11" cy="11" r="7" /><path d="m20 20-3-3" strokeLinecap="round" />
    </svg>
  );
}
function IconArrow() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" aria-hidden style={{ width: 13, height: 13 }}>
      <path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function recentActivityPillClass(label) {
  const ll = label.toLowerCase();
  let pill = 'ex-dash-recent-pill';
  if (ll.includes('complete') || ll.includes('done')) pill += ' ex-dash-recent-pill--done';
  else if (ll.includes('progress') || ll.includes('ongoing')) pill += ' ex-dash-recent-pill--active';
  else if (ll.includes('not started')) pill += ' ex-dash-recent-pill--pending';
  return pill;
}

function RecentActivityBlock({ headingId, title, subtitle, items }) {
  return (
    <section className="ex-dash-recent ex-dash-recent--role" aria-labelledby={headingId}>
      <div className="ex-dash-recent-head">
        <h2 id={headingId} className="ex-dash-recent-title">
          {title}
        </h2>
        <p className="ex-dash-recent-sub">{subtitle}</p>
      </div>
      <div className="ex-dash-recent-table">
        <div className="ex-dash-recent-row ex-dash-recent-row--head">
          <span>Title</span>
          <span>Role</span>
          <span>Status</span>
          <span>Date</span>
        </div>
        {items.length === 0 ? (
          <div className="ex-dash-recent-row ex-dash-recent-row--empty">No assignments yet</div>
        ) : (
          items.map((row) => {
            const label = row.assessment_status_name || `Status ${row.assessment_status_id}`;
            return (
              <div className="ex-dash-recent-row" key={`${row.assessment_id}-${row._roles.join('-')}`}>
                <span className="ex-dash-recent-cell-title">{row.video_title || '—'}</span>
                <span className="ex-dash-recent-cell-muted">{row._roles.join(' · ')}</span>
                <span>
                  <span className={recentActivityPillClass(label)}>{label}</span>
                </span>
                <span className="ex-dash-recent-cell-muted">{row.video_capture_date || '—'}</span>
              </div>
            );
          })
        )}
      </div>
    </section>
  );
}

/* Compact metric card (2×2 grid per role) */
function BucketCard({ row, count, isVerifier, onNavigate }) {
  return (
    <button
      type="button"
      className={`ex-dash-metric-card ex-dash-metric-card--${row.category}${
        isVerifier && row.category === 'returned' ? ' ex-dash-metric-card--returned-ver' : ''
      }`}
      onClick={onNavigate}
    >
      <div className="ex-dash-metric-card-top">
        <div className="ex-dash-metric-card-count-row">
          <span className="ex-dash-metric-card-count">{count}</span>
          <span className="ex-dash-metric-card-go" aria-hidden><IconArrow /></span>
        </div>
      </div>
      <div className="ex-dash-metric-card-title">{row.title}</div>
      <p className="ex-dash-metric-card-hint">{row.hint}</p>
    </button>
  );
}

export default function ExecutorDashboard({ onNavigateAssignments }) {
  const [executorAssessments, setExecutorAssessments] = useState([]);
  const [verifierAssessments, setVerifierAssessments] = useState([]);
  const [statuses, setStatuses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [trendGranularity, setTrendGranularity] = useState(TREND_GRANULARITY.MONTH);

  useEffect(() => {
    const userId = getSessionUserId();
    if (!userId) {
      setError('Unable to identify current user.');
      setLoading(false);
      return;
    }
    let cancelled = false;
    setLoading(true);
    setError('');
    fetchExecutorDashboardData()
      .then(({ statuses: st, executorAssessments: execRows, verifierAssessments: verRows }) => {
        if (cancelled) return;
        setStatuses(st);
        setExecutorAssessments(execRows);
        setVerifierAssessments(verRows);
      })
      .catch((e) => {
        if (!cancelled) setError(e.message || 'Unable to load assessments.');
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const { executorMap } = useMemo(() => buildCategoryMapsFromStatuses(statuses), [statuses]);

  const executorCounts = useMemo(
    () => countByCategory(executorAssessments, categorizeExecutorRow, executorMap),
    [executorAssessments, executorMap]
  );
  const verifierCounts = useMemo(
    () => countByCategory(verifierAssessments, categorizeVerifierRow, null),
    [verifierAssessments]
  );

  const trendCaption = useMemo(() => {
    const by = {
      [TREND_GRANULARITY.WEEK]:
        'Calendar weeks (Mon–Sun). By creation date: In progress = not Done; Completed = Done.',
      [TREND_GRANULARITY.MONTH]: 'Calendar months. Same counting rules by creation date.',
      [TREND_GRANULARITY.QUARTER]: 'Calendar quarters (Q1–Q4). Same counting rules by creation date.',
      [TREND_GRANULARITY.YEAR]: 'Calendar years. Same counting rules by creation date.'
    };
    return by[trendGranularity] ?? by[TREND_GRANULARITY.MONTH];
  }, [trendGranularity]);

  const executorTrendData = useMemo(
    () =>
      buildTrendSeriesData(
        executorAssessments,
        categorizeExecutorRow,
        executorMap,
        trendGranularity
      ),
    [executorAssessments, executorMap, trendGranularity]
  );
  const verifierTrendData = useMemo(
    () =>
      buildTrendSeriesData(verifierAssessments, categorizeVerifierRow, null, trendGranularity),
    [verifierAssessments, trendGranularity]
  );

  const executorPieSegments = useMemo(
    () =>
      ROWS_EXECUTOR.map((row) => ({
        category: row.category,
        title: row.title,
        hint: row.hint,
        value: executorCounts[row.category] ?? 0,
        fill: pieBucketFill(row.category, false)
      })),
    [executorCounts]
  );

  const verifierPieSegments = useMemo(
    () =>
      ROWS_VERIFIER.map((row) => ({
        category: row.category,
        title: row.title,
        hint: row.hint,
        value: verifierCounts[row.category] ?? 0,
        fill: pieBucketFill(row.category, true)
      })),
    [verifierCounts]
  );

  const handleRow = (view, category) => {
    if (typeof onNavigateAssignments === 'function') onNavigateAssignments({ view, category });
  };

  const exTotal = executorAssessments.length;
  const verTotal = verifierAssessments.length;
  const totalWork = exTotal + verTotal;
  const totalDone = (executorCounts.done ?? 0) + (verifierCounts.done ?? 0);
  const totalNotStarted =
    (executorCounts.not_started ?? 0) + (verifierCounts.not_started ?? 0);
  /** In-flight work: assigned but neither completed nor not-started. */
  const totalStarted = Math.max(0, totalWork - totalDone - totalNotStarted);

  const recentActivityMerged = useMemo(() => {
    const byId = new Map();
    for (const r of executorAssessments) {
      const id = String(r.assessment_id);
      const prev = byId.get(id);
      if (prev) {
        if (!prev._roles.includes('Executor')) prev._roles.push('Executor');
      } else {
        byId.set(id, { ...r, _roles: ['Executor'] });
      }
    }
    for (const r of verifierAssessments) {
      const id = String(r.assessment_id);
      const prev = byId.get(id);
      if (prev) {
        if (!prev._roles.includes('Verifier')) prev._roles.push('Verifier');
      } else {
        byId.set(id, { ...r, _roles: ['Verifier'] });
      }
    }
    const merged = [...byId.values()];
    merged.sort((a, b) => {
      const da = String(a.video_capture_date || a.created_at || '');
      const db = String(b.video_capture_date || b.created_at || '');
      if (da && db) return db.localeCompare(da);
      return Number(b.assessment_id) - Number(a.assessment_id);
    });
    return merged;
  }, [executorAssessments, verifierAssessments]);

  const recentActivityExecutor = useMemo(
    () => recentActivityMerged.filter((r) => r._roles.includes('Executor')).slice(0, 8),
    [recentActivityMerged]
  );
  const recentActivityVerifier = useMemo(
    () => recentActivityMerged.filter((r) => r._roles.includes('Verifier')).slice(0, 8),
    [recentActivityMerged]
  );

  if (loading) {
    return (
      <main className="dashboard-main ex-dash ex-dash-page">
        <div className="ex-dash-loading" aria-busy="true" aria-live="polite">
          <span className="ex-dash-loading-text">Loading your workspace…</span>
        </div>
      </main>
    );
  }

  return (
    <main className="dashboard-main ex-dash ex-dash-page">
      {error ? (
        <div className="ex-dash-error" role="alert">
          {error}
        </div>
      ) : null}

      <header className="ex-dash-hero">
        <div className="ex-dash-hero-text">
          <p className="ex-dash-hero-eyebrow">EHS · Risk assessment</p>
          <h1 className="ex-dash-hero-title">Workspace overview</h1>
          <p className="ex-dash-hero-lede">
            Monitor workload as executor and verifier, review trends, and open filtered assignment lists from any
            bucket.
          </p>
        </div>
      </header>

      <h2 className="ex-dash-combined-stats-heading" id="ex-dash-combined-stats-heading">
        Executor and Verifier Combined statistics
      </h2>

      <div className="ex-dash-summary-wrap" aria-labelledby="ex-dash-combined-stats-heading">
        <div className="ex-dash-summary-bar">
          <div className="ex-dash-summary-item">
            <span className="ex-dash-summary-num ex-dash-summary-num--green">{totalDone}</span>
            <span className="ex-dash-summary-lbl">Completed</span>
          </div>
          <div className="ex-dash-summary-sep" aria-hidden />
          <div className="ex-dash-summary-item">
            <span className="ex-dash-summary-num ex-dash-summary-num--amber">{totalNotStarted}</span>
            <span className="ex-dash-summary-lbl">Not started</span>
          </div>
          <div className="ex-dash-summary-sep" aria-hidden />
          <div className="ex-dash-summary-item">
            <span className="ex-dash-summary-num ex-dash-summary-num--blue">{totalStarted}</span>
            <span className="ex-dash-summary-lbl">Started</span>
          </div>
        </div>
      </div>

      {/* ── Metric cards: 2×2 per role (8 total) ── */}
      <div className="ex-dash-grid">
        <div className="ex-dash-buckets-wrap">
          <section className="ex-dash-role-block ex-dash-role-panel" aria-labelledby="ex-executor-heading">
            <div className="ex-dash-role-block-head">
              <div className="ex-dash-role-block-title">
                <div className="ex-dash-panel-icon ex-dash-role-block-icon" aria-hidden><IconUser /></div>
                <div>
                  <p id="ex-executor-heading" className="ex-dash-panel-label">Executor</p>
                  <p className="ex-dash-role-block-caption">
                    <span className="ex-dash-role-block-total">{exTotal}</span>
                    <span className="ex-dash-role-block-caption-lbl"> assignments</span>
                  </p>
                </div>
              </div>
            </div>
            <div className="ex-dash-metric-grid">
              {ROWS_EXECUTOR.map((row) => (
                <BucketCard
                  key={row.key}
                  row={row}
                  count={executorCounts[row.category] ?? 0}
                  isVerifier={false}
                  onNavigate={() => handleRow('executor', row.category)}
                />
              ))}
            </div>
            <div className="ex-dash-trend-pie-row">
              <DashboardRoleTrendChart
                data={executorTrendData}
                role="executor"
                hasAssignments={exTotal > 0}
                granularity={trendGranularity}
                onGranularityChange={setTrendGranularity}
                caption={trendCaption}
              />
            </div>
            <div className="ex-dash-pie-recent-row">
              <DashboardBucketPieChart
                role="executor"
                total={exTotal}
                segments={executorPieSegments}
                onSegmentClick={(category) => handleRow('executor', category)}
              />
              <RecentActivityBlock
                headingId="ex-executor-recent-heading"
                title="Recent activity"
                subtitle="Latest assessments where you are executor"
                items={recentActivityExecutor}
              />
            </div>
          </section>

          <section
            className="ex-dash-role-block ex-dash-role-block--verifier ex-dash-role-panel ex-dash-role-panel--verifier"
            aria-labelledby="ex-verifier-heading"
          >
            <div className="ex-dash-role-block-head">
              <div className="ex-dash-role-block-title">
                <div className="ex-dash-panel-icon ex-dash-panel-icon--verifier ex-dash-role-block-icon" aria-hidden><IconSearch /></div>
                <div>
                  <p id="ex-verifier-heading" className="ex-dash-panel-label">Verifier</p>
                  <p className="ex-dash-role-block-caption">
                    <span className="ex-dash-role-block-total">{verTotal}</span>
                    <span className="ex-dash-role-block-caption-lbl"> reviews you own</span>
                  </p>
                </div>
              </div>
            </div>
            <div className="ex-dash-metric-grid">
              {ROWS_VERIFIER.map((row) => (
                <BucketCard
                  key={row.key}
                  row={row}
                  count={verifierCounts[row.category] ?? 0}
                  isVerifier
                  onNavigate={() => handleRow('verifier', row.category)}
                />
              ))}
            </div>
            <div className="ex-dash-trend-pie-row">
              <DashboardRoleTrendChart
                data={verifierTrendData}
                role="verifier"
                hasAssignments={verTotal > 0}
                granularity={trendGranularity}
                onGranularityChange={setTrendGranularity}
                caption={trendCaption}
              />
            </div>
            <div className="ex-dash-pie-recent-row">
              <DashboardBucketPieChart
                role="verifier"
                total={verTotal}
                segments={verifierPieSegments}
                onSegmentClick={(category) => handleRow('verifier', category)}
              />
              <RecentActivityBlock
                headingId="ex-verifier-recent-heading"
                title="Recent activity"
                subtitle="Latest assessments where you are verifier"
                items={recentActivityVerifier}
              />
            </div>
          </section>
        </div>
      </div>
    </main>
  );
}
