/**
 * SchoolRow Component
 * Four-line row for primary school search results
 *
 * Line 1: School name · Ofsted badge
 * Line 2: School type · Age range · Denomination · Gender
 * Line 3: R,W&M %  ·  Progress score  ·  Pupil count
 * Line 4: Local authority  ·  Distance
 */

import type { School } from '@/lib/types';
import { formatPercentage, formatProgress, calculateTrend, getPhaseStyle, schoolUrl } from '@/lib/utils';
import { progressBand } from '@/lib/metrics';
import styles from './SchoolRow.module.css';

const OFSTED_LABELS: Record<number, string> = {
  1: 'Outstanding',
  2: 'Good',
  3: 'Req. Improvement',
  4: 'Inadequate',
};

interface SchoolRowProps {
  school: School;
  isLocationSearch?: boolean;
  isInCompare?: boolean;
  onAddToCompare?: (school: School) => void;
  onRemoveFromCompare?: (urn: number) => void;
}

export function SchoolRow({
  school,
  isLocationSearch,
  isInCompare = false,
  onAddToCompare,
  onRemoveFromCompare,
}: SchoolRowProps) {
  const trend = calculateTrend(school.rwm_expected_pct, school.prev_rwm_expected_pct);
  const phase = getPhaseStyle(school.phase);

  // Use reading progress as representative; fall back to writing, then maths
  const progressScore =
    school.reading_progress ?? school.writing_progress ?? school.maths_progress ?? null;

  const handleCompareClick = () => {
    if (isInCompare) {
      onRemoveFromCompare?.(school.urn);
    } else {
      onAddToCompare?.(school);
    }
  };

  const showGender = school.gender && school.gender.toLowerCase() !== 'mixed';
  const showDenomination =
    school.religious_denomination &&
    school.religious_denomination !== 'Does not apply';

  return (
    <div className={`${styles.row} ${phase.key ? styles[`phase${phase.key}`] : ''} ${isInCompare ? styles.rowInCompare : ''}`}>
      {/* Left: four content lines */}
      <div className={styles.rowContent}>

        {/* Line 1: School name + Ofsted badge */}
        <div className={styles.line1}>
          <a href={schoolUrl(school.urn, school.school_name)} className={styles.schoolName}>
            {school.school_name}
          </a>
          {school.ofsted_grade && (
            <span className={`${styles.ofstedBadge} ${styles[`ofsted${school.ofsted_grade}`]}`}>
              {OFSTED_LABELS[school.ofsted_grade]}
              {school.ofsted_date && (
                <span className={styles.ofstedDate}>
                  {' '}({new Date(school.ofsted_date).getFullYear()})
                </span>
              )}
            </span>
          )}
        </div>

        {/* Line 2: Context tags */}
        <div className={styles.line2}>
          {phase.label && (
            <span className={`${styles.phaseLabel} ${styles[`phaseLabel${phase.key}`]}`}>
              {phase.label}
            </span>
          )}
          {school.school_type && <span>{school.school_type}</span>}
          {school.age_range && <span>{school.age_range}</span>}
          {showDenomination && <span>{school.religious_denomination}</span>}
          {showGender && <span>{school.gender}</span>}
        </div>

        {/* Line 3: Key stats */}
        <div className={styles.line3}>
          {school.rwm_expected_pct != null ? (
            <span className={styles.stat}>
              <strong className={styles.statValue}>
                {formatPercentage(school.rwm_expected_pct, 0)}
              </strong>
              {school.prev_rwm_expected_pct != null && (
                <span
                  className={`${styles.trend} ${styles[`trend${trend.charAt(0).toUpperCase() + trend.slice(1)}`]}`}
                  title={`Previous year: ${formatPercentage(school.prev_rwm_expected_pct)}`}
                >
                  {trend === 'up' && (
                    <svg viewBox="0 0 16 16" fill="none" width="9" height="9" aria-label="Trend up">
                      <path d="M8 3L14 10H2L8 3Z" fill="currentColor" />
                    </svg>
                  )}
                  {trend === 'down' && (
                    <svg viewBox="0 0 16 16" fill="none" width="9" height="9" aria-label="Trend down">
                      <path d="M8 13L2 6H14L8 13Z" fill="currentColor" />
                    </svg>
                  )}
                  {trend === 'stable' && (
                    <svg viewBox="0 0 16 16" fill="none" width="9" height="9" aria-label="Trend stable">
                      <rect x="2" y="7" width="12" height="2" rx="1" fill="currentColor" />
                    </svg>
                  )}
                </span>
              )}
              <span className={styles.statLabel}>R, W &amp; M</span>
            </span>
          ) : (
            <span className={styles.stat}>
              <strong className={styles.statValue}>—</strong>
              <span className={styles.statLabel}>R, W &amp; M</span>
            </span>
          )}

          {progressScore != null && (
            <span className={styles.stat}>
              <strong className={styles.statValue}>{formatProgress(progressScore)}</strong>
              <span className={styles.statLabel}>
                progress · {progressBand(progressScore)}
              </span>
            </span>
          )}

          {school.total_pupils != null && (
            <span className={styles.stat}>
              <strong className={styles.statValue}>{school.total_pupils.toLocaleString()}</strong>
              <span className={styles.statLabel}>pupils</span>
            </span>
          )}
        </div>

        {/* Line 4: Location + distance */}
        <div className={styles.line4}>
          {school.local_authority && (
            <span>{school.local_authority}</span>
          )}
          {isLocationSearch && school.distance != null && (
            <span className={styles.distanceBadge}>
              {school.distance.toFixed(1)} mi
            </span>
          )}
        </div>

      </div>

      {/* Right: actions, vertically centred */}
      <div className={styles.rowActions}>
        <a href={schoolUrl(school.urn, school.school_name)} className="btn btn-tertiary btn-sm">
          View
        </a>
        {(onAddToCompare || onRemoveFromCompare) && (
          <button
            onClick={handleCompareClick}
            className={isInCompare ? 'btn btn-active btn-sm' : 'btn btn-secondary btn-sm'}
          >
            {isInCompare ? '✓ Comparing' : '+ Compare'}
          </button>
        )}
      </div>
    </div>
  );
}
