/**
 * SecondarySchoolRow Component
 * Three-line row for secondary school search results
 *
 * Line 1: School name · School type · Ofsted badge
 * Line 2: Attainment 8 (large) · ±LA avg delta · Eng & Maths 4+ · Pupils
 * Line 3: LA name · gender tag · sixth form tag · admissions tag · distance
 */

'use client';

import type { School } from '@/lib/types';

import styles from './SecondarySchoolRow.module.css';

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

function detectAdmissionsTag(school: School): string | null {
  const policy = school.admissions_policy?.toLowerCase() ?? '';
  if (policy.includes('selective')) return 'Selective';
  const denom = school.religious_denomination ?? '';
  if (denom && denom !== 'Does not apply') return 'Faith priority';
  return null;
}

function hasSixthForm(school: School): boolean {
  return school.age_range?.includes('18') ?? false;
}

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

export function SecondarySchoolRow({
  school,
  isLocationSearch,
  isInCompare = false,
  onAddToCompare,
  onRemoveFromCompare,
  laAvgAttainment8,
}: SecondarySchoolRowProps) {
  const handleCompareClick = () => {
    if (isInCompare) {
      onRemoveFromCompare?.(school.urn);
    } else {
      onAddToCompare?.(school);
    }
  };

  const att8 = school.attainment_8_score ?? null;
  const laDelta =
    att8 != null && laAvgAttainment8 != null ? att8 - laAvgAttainment8 : null;

  const admissionsTag = detectAdmissionsTag(school);
  const sixthForm = hasSixthForm(school);
  const showGender = school.gender && school.gender.toLowerCase() !== 'mixed';

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

        {/* Line 1: School name + type + Ofsted badge */}
        <div className={styles.line1}>
          <a href={`/school/${school.urn}`} className={styles.schoolName}>
            {school.school_name}
          </a>
          {school.school_type && (
            <span className={styles.schoolType}>{school.school_type}</span>
          )}
          {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: KS4 stats */}
        <div className={styles.line2}>
          <span className={styles.stat}>
            <strong className={styles.statValueLarge}>
              {att8 != null ? att8.toFixed(1) : '—'}
            </strong>
            <span className={styles.statLabel}>Attainment 8</span>
          </span>

          {laDelta != null && (
            <span className={`${styles.delta} ${laDelta >= 0 ? styles.deltaPositive : styles.deltaNegative}`}>
              {laDelta >= 0 ? '+' : ''}{laDelta.toFixed(1)} vs LA avg
            </span>
          )}

          {school.english_maths_standard_pass_pct != null && (
            <span className={styles.stat}>
              <strong className={styles.statValue}>
                {school.english_maths_standard_pass_pct.toFixed(0)}%
              </strong>
              <span className={styles.statLabel}>Eng &amp; Maths 4+</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 3: Location + tags */}
        <div className={styles.line3}>
          {school.local_authority && (
            <span>{school.local_authority}</span>
          )}
          {showGender && (
            <span className={styles.provisionTag}>{school.gender}</span>
          )}
          {sixthForm && (
            <span className={styles.provisionTag}>Sixth form</span>
          )}
          {admissionsTag && (
            <span className={`${styles.provisionTag} ${admissionsTag === 'Selective' ? styles.selectiveTag : ''}`}>
              {admissionsTag}
            </span>
          )}
          {isLocationSearch && school.distance != null && (
            <span className={styles.distanceBadge}>
              {school.distance.toFixed(1)} mi
            </span>
          )}
        </div>

      </div>

      {/* Right: actions */}
      <div className={styles.rowActions}>
        <a href={`/school/${school.urn}`} 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>
  );
}
