import { useMemo, useState } from 'react';
import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from 'recharts';
import { isReturnByVerifier } from '../executor/executorAssignmentCategories.js';
import AddToPersonalizedButton from '../common/AddToPersonalizedButton';
import './AdminLocationDrilldownPie.css';

const FILL = {
  pipeline: '#f36f2a',
  completion: '#189e52',
  return: '#c02626'
};

function isCompleteRow(row) {
  const id = Number(row?.assessment_status_id);
  if (id === 2) return true;
  const l = String(row?.assessment_status_name || '').toLowerCase();
  return l.includes('complete') || l.includes('done');
}

function isReturnRow(row) {
  if (Number(row?.assessment_status_id) === 4) return true;
  return isReturnByVerifier(row);
}

/** Pipeline = not complete and not returned (still open). */
function partitionPipelineCompletionReturn(rows) {
  let pipeline = 0;
  let completion = 0;
  let ret = 0;
  for (const row of rows) {
    if (isCompleteRow(row)) completion += 1;
    else if (isReturnRow(row)) ret += 1;
    else pipeline += 1;
  }
  return { pipeline, completion, return: ret };
}

function filterAssessments(assessments, countryId, locationId, departmentId) {
  return assessments.filter((a) => {
    if (countryId !== '' && countryId != null && String(a.country_id) !== String(countryId)) return false;
    if (locationId !== '' && locationId != null && String(a.location_id) !== String(locationId)) return false;
    if (departmentId !== '' && departmentId != null && String(a.department_id) !== String(departmentId))
      return false;
    return true;
  });
}

function DrillTooltip({ active, payload, total }) {
  if (!active || !payload?.length) return null;
  const item = payload[0];
  const p = item?.payload ?? item;
  const name = p?.name ?? item?.name;
  const value = p?.value ?? item?.value;
  if (value == null) return null;
  const pct = total > 0 ? Math.round((value / total) * 100) : 0;
  return (
    <div className="admin-drill-pie-tooltip">
      <strong>{name}</strong>
      <span className="admin-drill-pie-tooltip-num">
        {value} <span className="admin-drill-pie-tooltip-pct">({pct}%)</span>
      </span>
    </div>
  );
}

/**
 * @param {object} props
 * @param {object[]} props.assessments
 * @param {{ country_id?: number, country_name?: string }[]} props.countries — lookup for country names
 */
export default function AdminLocationDrilldownPie({ assessments, countries = [] }) {
  const [countryId, setCountryId] = useState('');
  const [locationId, setLocationId] = useState('');
  const [departmentId, setDepartmentId] = useState('');

  const countryNameById = useMemo(() => {
    const m = new Map();
    for (const c of countries) {
      if (c?.country_id != null) m.set(String(c.country_id), c.country_name || `Country ${c.country_id}`);
    }
    return m;
  }, [countries]);

  const countryOptions = useMemo(() => {
    const map = new Map();
    for (const a of assessments) {
      if (a.country_id == null || a.country_id === '') continue;
      const id = String(a.country_id);
      if (!map.has(id)) {
        map.set(id, countryNameById.get(id) || `Country ${id}`);
      }
    }
    return [...map.entries()].sort((a, b) => a[1].localeCompare(b[1], undefined, { sensitivity: 'base' }));
  }, [assessments, countryNameById]);

  const locationOptions = useMemo(() => {
    const base = assessments.filter((a) => !countryId || String(a.country_id) === String(countryId));
    const map = new Map();
    for (const a of base) {
      if (a.location_id == null || a.location_id === '') continue;
      const id = String(a.location_id);
      if (!map.has(id)) map.set(id, a.location_name || `Location ${id}`);
    }
    return [...map.entries()].sort((a, b) => a[1].localeCompare(b[1], undefined, { sensitivity: 'base' }));
  }, [assessments, countryId]);

  const departmentOptions = useMemo(() => {
    let base = assessments;
    if (countryId) base = base.filter((a) => String(a.country_id) === String(countryId));
    if (locationId) base = base.filter((a) => String(a.location_id) === String(locationId));
    const map = new Map();
    for (const a of base) {
      if (a.department_id == null || a.department_id === '') continue;
      const id = String(a.department_id);
      if (!map.has(id)) map.set(id, a.department_name || `Work area ${id}`);
    }
    return [...map.entries()].sort((a, b) => a[1].localeCompare(b[1], undefined, { sensitivity: 'base' }));
  }, [assessments, countryId, locationId]);

  const scoped = useMemo(
    () => filterAssessments(assessments, countryId, locationId, departmentId),
    [assessments, countryId, locationId, departmentId]
  );

  const counts = useMemo(() => partitionPipelineCompletionReturn(scoped), [scoped]);

  const pieData = useMemo(() => {
    const segments = [
      {
        key: 'pipeline',
        name: 'In progress / open',
        value: counts.pipeline,
        fill: FILL.pipeline
      },
      { key: 'completion', name: 'Completion', value: counts.completion, fill: FILL.completion },
      { key: 'return', name: 'Return', value: counts.return, fill: FILL.return }
    ];
    return segments.filter((s) => s.value > 0);
  }, [counts]);

  const total = scoped.length;

  const rate = (n) => (total > 0 ? Math.round((n / total) * 1000) / 10 : 0);

  const roleStats = useMemo(() => {
    /** Single role: count each person once whether they appear as executor or verifier. */
    const executorVerifier = new Set();
    const activeUsers = new Set();
    for (const r of scoped) {
      if (r.executor_id != null && r.executor_id !== '') {
        const id = String(r.executor_id);
        executorVerifier.add(id);
        activeUsers.add(id);
      }
      if (r.verifier_id != null && r.verifier_id !== '') {
        const id = String(r.verifier_id);
        executorVerifier.add(id);
        activeUsers.add(id);
      }
      if (r.uploader_user_id != null && r.uploader_user_id !== '') {
        activeUsers.add(String(r.uploader_user_id));
      }
    }
    return {
      executorVerifier: executorVerifier.size,
      activeUsers: activeUsers.size
    };
  }, [scoped]);

  const breadcrumbParts = [];
  if (countryId) {
    breadcrumbParts.push(countryOptions.find(([id]) => id === countryId)?.[1] || `Country ${countryId}`);
  }
  if (locationId) {
    breadcrumbParts.push(locationOptions.find(([id]) => id === locationId)?.[1] || `Location ${locationId}`);
  }
  if (departmentId) {
    breadcrumbParts.push(
      departmentOptions.find(([id]) => id === departmentId)?.[1] || `Work area ${departmentId}`
    );
  }

  const clearFilters = () => {
    setCountryId('');
    setLocationId('');
    setDepartmentId('');
  };

  return (
    <div className="admin-drill-pie">
      <div className="admin-drill-pie-head">
        <div>
          <h2 className="admin-drill-pie-title">Location breakdown</h2>
          <p className="admin-drill-pie-lede">
            Drill down by country, then location, then department/work area. The pie shows completion, return, and
            everything still in progress (open).
          </p>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <AddToPersonalizedButton widgetId="raLocationDrilldown" />
          <button type="button" className="admin-outline-button admin-drill-pie-clear" onClick={clearFilters}>
            Clear filters
          </button>
        </div>
      </div>

      <div className="admin-drill-pie-filters" role="group" aria-label="Geographic filters">
        <div className="admin-drill-pie-field">
          <label htmlFor="admin-drill-country">Country</label>
          <select
            id="admin-drill-country"
            className="admin-drill-pie-select"
            value={countryId}
            onChange={(e) => {
              setCountryId(e.target.value);
              setLocationId('');
              setDepartmentId('');
            }}
          >
            <option value="">All countries</option>
            {countryOptions.map(([id, label]) => (
              <option key={id} value={id}>
                {label}
              </option>
            ))}
          </select>
        </div>
        <div className="admin-drill-pie-field">
          <label htmlFor="admin-drill-location">Location</label>
          <select
            id="admin-drill-location"
            className="admin-drill-pie-select"
            value={locationId}
            onChange={(e) => {
              setLocationId(e.target.value);
              setDepartmentId('');
            }}
          >
            <option value="">All locations {countryId ? '(in country)' : ''}</option>
            {locationOptions.map(([id, label]) => (
              <option key={id} value={id}>
                {label}
              </option>
            ))}
          </select>
        </div>
        <div className="admin-drill-pie-field">
          <label htmlFor="admin-drill-dept">Department / work area</label>
          <select
            id="admin-drill-dept"
            className="admin-drill-pie-select"
            value={departmentId}
            onChange={(e) => setDepartmentId(e.target.value)}
          >
            <option value="">All departments {locationId ? '(in location)' : countryId ? '(in country)' : ''}</option>
            {departmentOptions.map(([id, label]) => (
              <option key={id} value={id}>
                {label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {breadcrumbParts.length > 0 ? (
        <p className="admin-drill-pie-crumb" aria-live="polite">
          Scope: <span>{breadcrumbParts.join(' → ')}</span>
        </p>
      ) : (
        <p className="admin-drill-pie-crumb admin-drill-pie-crumb--muted">Scope: all assessments</p>
      )}

      <div className="admin-drill-pie-body">
        <div className={`admin-drill-pie-chart-wrap${total === 0 ? ' admin-drill-pie-chart-wrap--empty' : ''}`}>
          {total === 0 ? (
            <p className="admin-drill-pie-empty">No assessments match the current filters.</p>
          ) : (
            <ResponsiveContainer width="100%" height={280}>
              <PieChart margin={{ top: 8, right: 8, bottom: 8, left: 8 }}>
                <Pie
                  data={pieData}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="50%"
                  innerRadius="54%"
                  outerRadius="88%"
                  paddingAngle={pieData.length > 1 ? 2 : 0}
                  cornerRadius={5}
                  stroke="#fff"
                  strokeWidth={2}
                  label={false}
                >
                  {pieData.map((entry) => (
                    <Cell key={entry.key} fill={entry.fill} />
                  ))}
                </Pie>
                <Tooltip content={(tipProps) => <DrillTooltip {...tipProps} total={total} />} />
              </PieChart>
            </ResponsiveContainer>
          )}
        </div>

        <div className="admin-drill-pie-side">
          <div className="admin-drill-pie-rates">
            <div className="admin-drill-pie-rate">
              <span className="admin-drill-pie-rate-dot" style={{ background: FILL.completion }} />
              <span className="admin-drill-pie-rate-label">Completion rate</span>
              <strong>{rate(counts.completion)}%</strong>
              <span className="admin-drill-pie-rate-n">({counts.completion})</span>
            </div>
            <div className="admin-drill-pie-rate">
              <span className="admin-drill-pie-rate-dot" style={{ background: FILL.return }} />
              <span className="admin-drill-pie-rate-label">Return rate</span>
              <strong>{rate(counts.return)}%</strong>
              <span className="admin-drill-pie-rate-n">({counts.return})</span>
            </div>
            <div className="admin-drill-pie-rate">
              <span className="admin-drill-pie-rate-dot" style={{ background: FILL.pipeline }} />
              <span className="admin-drill-pie-rate-label">In progress / open rate</span>
              <strong>{rate(counts.pipeline)}%</strong>
              <span className="admin-drill-pie-rate-n">({counts.pipeline})</span>
            </div>
          </div>

          <div className="admin-drill-pie-stat-cards" aria-label="People in scope">
            <div className="admin-drill-pie-stat-card">
              <p className="admin-drill-pie-stat-card-title">Executor / verifier</p>
              <p className="admin-drill-pie-stat-card-big">{roleStats.executorVerifier}</p>
              <p className="admin-drill-pie-stat-card-hint">
                Distinct people in this role (executor or verifier) on assessments in this scope
              </p>
            </div>
            <div className="admin-drill-pie-stat-card">
              <p className="admin-drill-pie-stat-card-title">Active users</p>
              <p className="admin-drill-pie-stat-card-big">{roleStats.activeUsers}</p>
              <p className="admin-drill-pie-stat-card-hint">Unique uploaders, executors and verifiers</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
