import { useEffect, useMemo, useState } from 'react';
import { fetchAssessments, fetchAssessmentStatuses, fetchCountries } from '../../api.js';
import '../executor/ExecutorDashboard.css';
import DashboardRoleTrendChart from '../executor/DashboardRoleTrendChart.jsx';
import { buildTrendSeriesData, TREND_GRANULARITY } from '../executor/dashboardTrendSeries.js';
import {
  buildCategoryMapsFromStatuses,
  categorizeExecutorRow
} from '../executor/executorAssignmentCategories.js';
import './admin-shared.css';
import './AdminDashboard.css';
import AddToPersonalizedButton from '../common/AddToPersonalizedButton';
import AdminLocationDrilldownPie from './AdminLocationDrilldownPie.jsx';

function displayPersonName(name, id) {
  const n = name && String(name).trim();
  if (n) return n;
  if (id != null && id !== '') return String(id);
  return '—';
}

/** Assessments where an executor or verifier has been set (admin assignment). */
function isAssignedAssessment(a) {
  return Boolean(a.executor_id || a.verifier_id);
}

/**
 * Workflow labels for the admin activity list (ORAC status ids 1–5).
 * Falls back to API name when ids differ.
 */
function getAdminActivityStatusLabel(row) {
  const id = Number(row.assessment_status_id);
  switch (id) {
    case 1:
      return 'Not Started';
    case 2:
      return 'Complete';
    case 3:
      return 'InProgress';
    case 4:
      return 'Returned';
    case 5:
      return 'Verification Required';
    default: {
      const raw = row.assessment_status_name || `Status ${row.assessment_status_id}`;
      return String(raw).replace(/\bVarification\b/gi, 'Verification');
    }
  }
}

function adminActivityStatusPillClass(row) {
  const id = Number(row.assessment_status_id);
  switch (id) {
    case 1:
      return 'status-pill--warning';
    case 2:
      return 'status-pill--success';
    case 3:
      return 'status-pill--info';
    case 4:
      return 'status-pill--return-ex';
    case 5:
      return 'status-pill--verification';
    default: {
      const label = (row.assessment_status_name || '').toLowerCase();
      if (label.includes('complete') || label.includes('done')) return 'status-pill--success';
      if (label.includes('progress') || label.includes('ongoing')) return 'status-pill--info';
      if (label.includes('return')) return 'status-pill--return-ex';
      if (label.includes('verif')) return 'status-pill--verification';
      return 'status-pill--neutral';
    }
  }
}

function formatActivityDate(row) {
  const raw = row.created_at || row.video_capture_date;
  if (!raw) return '—';
  const d = new Date(raw);
  if (Number.isNaN(d.getTime())) return String(raw);
  return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}

function AdminDashboard({ onOpenPendingActions, onOpenAssignedVideos }) {
  const [assessments, setAssessments] = useState([]);
  const [statuses, setStatuses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [trendGranularity, setTrendGranularity] = useState(TREND_GRANULARITY.MONTH);
  const [countries, setCountries] = useState([]);

  useEffect(() => {
    Promise.all([fetchAssessments(), fetchAssessmentStatuses(), fetchCountries()])
      .then(([aData, sData, cData]) => {
        setAssessments(aData);
        setStatuses(sData);
        setCountries(Array.isArray(cData) ? cData : []);
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  const statusMap = {};
  statuses.forEach((s) => {
    statusMap[s.assessment_status_id] =
      s.assessment_status_name ||
      s.status_name ||
      s.name ||
      `Status ${s.assessment_status_id}`;
  });

  const getStatusLabel = (id) => statusMap[id] || 'Unknown';

  const done = assessments.filter((a) => {
    const label = getStatusLabel(a.assessment_status_id).toLowerCase();
    return label.includes('complete') || label.includes('done');
  });
  const inProgress = assessments.filter((a) => {
    const label = getStatusLabel(a.assessment_status_id).toLowerCase();
    return label.includes('progress') || label.includes('ongoing');
  });
  const notStarted = assessments.filter((a) => {
    const label = getStatusLabel(a.assessment_status_id).toLowerCase();
    return label.includes('pending') || label.includes('not started') || a.assessment_status_id === 1;
  });

  const recentPending = notStarted.slice(0, 5);

  const activityListRows = useMemo(() => {
    return assessments
      .filter(isAssignedAssessment)
      .sort((a, b) => Number(b.assessment_id) - Number(a.assessment_id));
  }, [assessments]);

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

  const assignedForTrend = useMemo(
    () => assessments.filter(isAssignedAssessment),
    [assessments]
  );

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

  const openAssigned = typeof onOpenAssignedVideos === 'function' ? onOpenAssignedVideos : onOpenPendingActions;
  const openPending = onOpenPendingActions;
  const keyAction = (e, cb) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      cb();
    }
  };

  if (loading) {
    return (
      <main className="dashboard-main admin-dashboard admin-dashboard-v2">
        <p style={{ textAlign: 'center', padding: 40, color: 'var(--theme-gray-500)' }}>Loading dashboard...</p>
      </main>
    );
  }

  return (
    <main className="dashboard-main admin-dashboard admin-dashboard-v2">
      <header className="admin-page-header">
        <div>
          <div className="admin-page-badge">Admin workspace</div>
          <h1>Dashboard</h1>
          {error && <p style={{ color: 'var(--theme-red)', fontSize: 13 }}>{error}</p>}
        </div>
      </header>

      <section className="admin-kpi-grid">
        <article
          className="admin-kpi admin-kpi--green admin-kpi--clickable"
          onClick={openAssigned}
          onKeyDown={(e) => keyAction(e, openAssigned)}
          aria-label="Open assigned videos"
          role="button"
          tabIndex={0}
        >
          <div className="admin-kpi-add-btn">
            <AddToPersonalizedButton widgetId="raStatsCompleted" />
          </div>
          <div className="admin-kpi-content">
            <div className="admin-kpi-icon">
              <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>
            </div>
            <div className="admin-kpi-info">
              <div className="admin-kpi-label">Assessment done</div>
              <div className="admin-kpi-value">{done.length}</div>
              <div className="admin-kpi-note">Completed and verified</div>
            </div>
          </div>
        </article>

        <article
          className="admin-kpi admin-kpi--blue admin-kpi--clickable"
          onClick={openAssigned}
          onKeyDown={(e) => keyAction(e, openAssigned)}
          aria-label="Open assigned videos"
          role="button"
          tabIndex={0}
        >
          <div className="admin-kpi-add-btn">
            <AddToPersonalizedButton widgetId="raStatsInProgress" />
          </div>
          <div className="admin-kpi-content">
            <div className="admin-kpi-icon">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M12 6v6l4 2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <div className="admin-kpi-info">
              <div className="admin-kpi-label">Assessment in process</div>
              <div className="admin-kpi-value">{inProgress.length}</div>
              <div className="admin-kpi-note">Active assignments running</div>
            </div>
          </div>
        </article>

        <article
          className="admin-kpi admin-kpi--amber admin-kpi--clickable"
          onClick={openPending}
          onKeyDown={(e) => keyAction(e, openPending)}
          aria-label="Open Assign Videos"
          role="button"
          tabIndex={0}
        >
          <div className="admin-kpi-add-btn" onClick={(e) => e.stopPropagation()}>
            <AddToPersonalizedButton widgetId="raStatsNotStarted" />
          </div>
          <div className="admin-kpi-content">
            <div className="admin-kpi-icon">
              <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>
            </div>
            <div className="admin-kpi-info">
              <div className="admin-kpi-label">Assessment not started</div>
              <div className="admin-kpi-value">{notStarted.length}</div>
              <div className="admin-kpi-note">Click to assign videos</div>
            </div>
          </div>
        </article>

        <article
          className="admin-kpi admin-kpi--gray admin-kpi--clickable"
          onClick={openAssigned}
          onKeyDown={(e) => keyAction(e, openAssigned)}
          aria-label="Open assigned videos"
          role="button"
          tabIndex={0}
        >
          <div className="admin-kpi-add-btn">
            <AddToPersonalizedButton widgetId="raStatsTotal" />
          </div>
          <div className="admin-kpi-content">
            <div className="admin-kpi-icon">
              <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="8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <line x1="21" y1="21" x2="16.65" y2="16.65" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <div className="admin-kpi-info">
              <div className="admin-kpi-label">Total assessments</div>
              <div className="admin-kpi-value">{assessments.length}</div>
              <div className="admin-kpi-note">Across all locations</div>
            </div>
          </div>
        </article>
      </section>

      <section className="admin-dashboard-layout">
        <div className="dashboard-section admin-panel">
          <div className="dashboard-section-header">
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <div>
                <div className="dashboard-section-title">Assign videos</div>
                <div className="dashboard-section-subtitle">Items that need executor or verifier assignment</div>
              </div>
              <AddToPersonalizedButton widgetId="raRecentAssessments" />
            </div>
            <button type="button" className="admin-outline-button" onClick={onOpenPendingActions}>
              View all
            </button>
          </div>

          <div className="admin-compact-table-wrap">
            <table className="admin-compact-table">
              <thead>
                <tr>
                  <th>Video title</th>
                  <th>Status</th>
                  <th>Uploaded on</th>
                </tr>
              </thead>
              <tbody>
                {recentPending.length === 0 && (
                  <tr><td colSpan={3} style={{ textAlign: 'center', color: 'var(--theme-gray-400)' }}>No pending items</td></tr>
                )}
                {recentPending.map((row) => (
                  <tr key={row.assessment_id}>
                    <td>{row.video_title || '—'}</td>
                    <td>
                      <span className="status-pill status-pill--warning">
                        {getStatusLabel(row.assessment_status_id)}
                      </span>
                    </td>
                    <td>{row.video_capture_date || '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* <div className="admin-side-stack">
          <div className="dashboard-section admin-panel">
            <div className="dashboard-section-header">
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <div>
                  <div className="dashboard-section-title">Assessment breakdown</div>
                  <div className="dashboard-section-subtitle">By current status</div>
                </div>
                <AddToPersonalizedButton widgetId="raStatusBreakdown" />
              </div>
            </div>
            <div className="admin-workload-list">
              {Object.entries(statusMap).map(([id, name]) => {
                const count = assessments.filter((a) => String(a.assessment_status_id) === String(id)).length;
                return (
                  <div key={id} className="admin-workload-row">
                    <div className="admin-workload-role">{name}</div>
                    <div className="admin-workload-metrics">
                      <span>{count} assessments</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div> */}
      </section>

      <section className="admin-dashboard-trend-section" aria-label="Assessment trends">
        <div className="ex-dash admin-trend-chart-embed">
          <DashboardRoleTrendChart
            data={adminTrendData}
            role="admin"
            hasAssignments={assignedForTrend.length > 0}
            granularity={trendGranularity}
            onGranularityChange={setTrendGranularity}
            seriesLabels={{ assigned: 'Assigned', completed: 'Completed' }}
            addToPersonalizedWidgetId="raTrendChart"
            subtitle="Assigned and completed assessments over time"
          />
        </div>
      </section>

      <section className="dashboard-section admin-panel admin-drill-pie-section">
        <AdminLocationDrilldownPie assessments={assessments} countries={countries} />
      </section>

      <section className="dashboard-section admin-panel admin-dashboard-activity-section">
        <div className="dashboard-section-header">
          <div>
            <div className="dashboard-section-title">Activity list</div>
            <div className="dashboard-section-subtitle">
              Assessments you have assigned (executor or verifier set), newest first
            </div>
          </div>
          <button type="button" className="admin-outline-button" onClick={openAssigned}>
            View all assigned
          </button>
        </div>

        <div className="admin-compact-table-wrap">
          <table className="admin-compact-table">
            <thead>
              <tr>
                <th>Video title</th>
                <th>Executor</th>
                <th>Verifier</th>
                <th>Current status</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              {activityListRows.length === 0 && (
                <tr>
                  <td colSpan={5} style={{ textAlign: 'center', color: 'var(--theme-gray-400)' }}>
                    No assigned assessments yet. Assign executors or verifiers from pending actions.
                  </td>
                </tr>
              )}
              {activityListRows.map((row) => (
                <tr key={row.assessment_id}>
                  <td>{row.video_title || '—'}</td>
                  <td>{displayPersonName(row.executor_name, row.executor_id)}</td>
                  <td>{displayPersonName(row.verifier_name, row.verifier_id)}</td>
                  <td>
                    <span className={`status-pill ${adminActivityStatusPillClass(row)}`}>
                      {getAdminActivityStatusLabel(row)}
                    </span>
                  </td>
                  <td>{formatActivityDate(row)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </main>
  );
}

export default AdminDashboard;
