/**
 * At a glance — the short version of every section below it. Copy verbatim
 * from the reviewed mockups. Report-card cells summarise by counting graded
 * areas (best first) and always NAME problem areas; safeguarding is a
 * separate line, never a count.
 */

'use client';

import {
  admissionsForPhase,
  latestValues,
  ofstedDisplay,
  summariseAdmissions,
  verdict,
  type ReportCardSummary,
} from '@/lib/compareLogic';
import type { Benchmarks, ComparisonData, NationalAverages, School } from '@/lib/types';
import { Cell, Chip, Measure, Section, SectionGrid, sectionStyles as s } from './sectionShared';

function ReportCardChips({ summary }: { summary: ReportCardSummary }) {
  return (
    <>
      <strong style={{ fontSize: '0.9rem' }}>Report card</strong>
      <span className={s.chipStack}>
        {summary.counts.map((c) => (
          <Chip key={c.label} tone={c.label === 'Expected standard' ? 'neutral' : 'good'}>
            {c.count} area{c.count === 1 ? '' : 's'} {c.label}
          </Chip>
        ))}
        {summary.problems.map((p) => (
          <Chip key={p.areaLabel} tone={p.label === 'Urgent improvement' ? 'bad' : 'warn'}>
            {p.areaLabel}: {p.label}
          </Chip>
        ))}
      </span>
      <span className={s.small}>
        {summary.allClear && 'No areas need attention · '}
        {summary.safeguarding === 'met' && 'Safeguarding met'}
        {summary.safeguarding === 'not_met' && 'Safeguarding not met'}
      </span>
    </>
  );
}

export function CompareAtAGlance({
  schools,
  data,
  nationalAverages,
  benchmarks,
  isSecondary: propIsSecondary,
}: {
  schools: School[];
  data: Record<string, ComparisonData>;
  nationalAverages?: NationalAverages;
  benchmarks?: Benchmarks;
  isSecondary?: boolean;
}) {
  const urns = schools.map((school) => school.urn);
  const isSecondary = propIsSecondary !== undefined ? propIsSecondary : schools.some(
    (school) => data[String(school.urn)]?.school_info?.attainment_8_score != null,
  );
  const headlineKey = isSecondary ? 'attainment_8_score' : 'rwm_expected_pct';
  const headlineValues = latestValues(data, urns, headlineKey);
  const anchor = isSecondary
    ? nationalAverages?.secondary?.attainment_8_score
    : nationalAverages?.primary?.rwm_expected_pct;
  const medianPupils = isSecondary
    ? benchmarks?.secondary?.median_pupils
    : benchmarks?.primary?.median_pupils;

  return (
    <Section title="At a glance" how="The short version — each row below is explained in its own section further down.">
      <SectionGrid schools={schools}>
        <Measure label="Latest Ofsted inspection">
        {schools.map((school, i) => {
          const display = ofstedDisplay(data[String(school.urn)]?.ofsted);
          return (
            <Cell key={school.urn} school={school} index={i}>
              {display.kind === 'report_card' && <ReportCardChips summary={display.summary} />}
              {(display.kind === 'graded' || display.kind === 'carried_forward') && (
                <>
                  <span className={`${s.badge} ${display.grade <= 2 ? s.badgeGood : display.grade === 3 ? s.badgeWarn : s.badgeBad}`}>
                    {display.gradeLabel}
                  </span>
                  {display.carriedForward && <span className={s.small}>Grade carried forward</span>}
                </>
              )}
              {display.kind === 'transitional' && (
                <>
                  <span className={s.badge} style={{ backgroundColor: 'var(--bg-secondary)', color: 'var(--text-secondary)' }}>
                    No overall grade
                  </span>
                  <span className={s.small}>Sub-judgements only</span>
                </>
              )}
              {display.kind === 'none' && <span className={s.small}>No inspection in our dataset</span>}
            </Cell>
          );
        })}
        </Measure>

        <Measure
          tip={
            isSecondary
              ? 'Average Attainment 8 score across GCSE subjects (latest year).'
              : '% of Year 6 pupils reaching the expected standard in reading, writing and maths (latest year).'
          }
          label={isSecondary ? 'Attainment 8 score' : 'Children reaching the expected standard'}
        >
        {schools.map((school, i) => {
          const value = headlineValues[i];
          return (
            <Cell key={school.urn} school={school} index={i}>
              {value != null ? (
                <>
                  <span className={s.big}>{isSecondary ? value.toFixed(1) : `${Math.round(value)}%`}</span>{' '}
                  {anchor != null && (
                    <Chip
                      tone={
                        verdict(value, anchor) === 'above'
                          ? 'good'
                          : verdict(value, anchor) === 'below'
                            ? 'warn'
                            : 'neutral'
                      }
                    >
                      {verdict(value, anchor) === 'above' && 'Above England average'}
                      {verdict(value, anchor) === 'close' && 'Close to England average'}
                      {verdict(value, anchor) === 'below' && 'Below England average'}
                    </Chip>
                  )}
                  {anchor != null && (
                    <span className={s.small}>
                      England average {isSecondary ? anchor.toFixed(1) : `${Math.round(anchor)}%`}
                    </span>
                  )}
                </>
              ) : (
                <span className={s.small}>No data</span>
              )}
            </Cell>
          );
        })}
        </Measure>

        <Measure label="Getting a place">
        {schools.map((school, i) => {
          // Phase-matched round only — an all-through school's Year 7 round
          // must not masquerade as Reception odds on the primary tab.
          const summary = summariseAdmissions(
            admissionsForPhase(data[String(school.urn)], isSecondary),
          );
          return (
            <Cell key={school.urn} school={school} index={i}>
              {summary.chip ? (
                <>
                  <Chip tone={summary.chip.tone}>{summary.chip.text}</Chip>
                  {summary.interest && <span className={s.small}>{summary.interest}</span>}
                </>
              ) : (
                <span className={s.small}>No admissions data</span>
              )}
            </Cell>
          );
        })}
        </Measure>

        <Measure label="Size">
        {schools.map((school, i) => {
          const census = data[String(school.urn)]?.census;
          const pupils = census?.total_pupils ?? school.total_pupils ?? null;
          // An all-through school's roll covers every age group, so judging
          // it against the single-phase median ("Much larger than average")
          // is meaningless — label the roll honestly instead.
          const isAllThrough = /all.?through/i.test(school.phase ?? '');
          let sizeNote: string | null = null;
          if (isAllThrough) {
            sizeNote = 'Whole-school roll (all-through, all ages)';
          } else if (pupils != null && medianPupils != null) {
            if (pupils >= medianPupils * 1.5) sizeNote = 'Much larger than average';
            else if (pupils >= medianPupils * 1.1) sizeNote = 'Larger than average';
            else if (pupils <= medianPupils * 0.66) sizeNote = 'Much smaller than average';
            else if (pupils <= medianPupils * 0.9) sizeNote = 'Smaller than average';
            else sizeNote = 'About average size';
          }
          return (
            <Cell key={school.urn} school={school} index={i}>
              {pupils != null ? (
                <>
                  {pupils.toLocaleString('en-GB')} pupils
                  {sizeNote && <span className={s.small}>{sizeNote}</span>}
                </>
              ) : (
                <span className={s.small}>No data</span>
              )}
            </Cell>
          );
        })}
        </Measure>
      </SectionGrid>
    </Section>
  );
}
