import { useEffect, useMemo, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Input, Text, View } from '@tarojs/components';
import {
  loadScorelineFields,
  loadScorelineMajors,
  loadScorelineRecords,
  loadScorelineSchools,
  loadScorelineTrend,
  loadScorelineYears,
  type ScorelineField,
  type ScorelineMajor,
  type ScorelineRecord,
  type ScorelineSchool,
} from '@/services/catalog';
import { loadProfile, type StudentProfile } from '@/services/profile';
import '../student.css';

function valueText(value: unknown) {
  if (value === null || value === undefined || value === '') return '暂无';
  if (typeof value === 'boolean') return value ? '是' : '否';
  if (typeof value === 'object') return JSON.stringify(value);
  return String(value);
}

function fieldValue(record: ScorelineRecord, field: ScorelineField) {
  const value = record.fieldValues?.[field.fieldKey];
  const suffix = field.unit && value !== null && value !== undefined && value !== '' ? field.unit : '';
  return `${valueText(value)}${suffix}`;
}

function normalizeFieldType(field: ScorelineField) {
  return (field.fieldType || 'text').toLowerCase();
}

function fieldPlaceholder(field: ScorelineField) {
  if (field.placeholder) return field.placeholder;
  if (['number', 'integer', 'decimal', 'float'].includes(normalizeFieldType(field))) return `${field.fieldName}下限`;
  return field.fieldName;
}

function visibleFields(fields: ScorelineField[]) {
  return fields.filter(item => item.isVisible !== false).sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
}

function trendFields(fields: ScorelineField[]) {
  const marked = fields.filter(item => item.isTrend);
  return (marked.length ? marked : visibleFields(fields)).slice(0, 3);
}

function optionLabels(options: unknown) {
  if (!Array.isArray(options)) return [];
  return options
    .map(item => {
      if (typeof item === 'string' || typeof item === 'number') return { label: String(item), value: String(item) };
      if (item && typeof item === 'object') {
        const record = item as Record<string, unknown>;
        const value = record.value ?? record.label ?? record.name;
        const label = record.label ?? record.name ?? record.value;
        if (value !== undefined && label !== undefined) return { label: String(label), value: String(value) };
      }
      return null;
    })
    .filter((item): item is { label: string; value: string } => Boolean(item));
}

function recordTitle(item: ScorelineRecord) {
  return `${item.year} · ${item.schoolName || '院校'}${item.majorName ? ` · ${item.majorName}` : ''}`;
}

export default function StudentScorelinePage() {
  const [profile, setProfile] = useState<StudentProfile | null>(null);
  const [fields, setFields] = useState<ScorelineField[]>([]);
  const [schools, setSchools] = useState<ScorelineSchool[]>([]);
  const [majors, setMajors] = useState<ScorelineMajor[]>([]);
  const [years, setYears] = useState<number[]>([]);
  const [records, setRecords] = useState<ScorelineRecord[]>([]);
  const [trend, setTrend] = useState<ScorelineRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [selectedSchoolId, setSelectedSchoolId] = useState('');
  const [selectedMajorId, setSelectedMajorId] = useState('');
  const [selectedYear, setSelectedYear] = useState(0);
  const [filterValues, setFilterValues] = useState<Record<string, string>>({});
  const [refreshNonce, setRefreshNonce] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const regionId = profile?.target?.regionId || undefined;
  const currentSchool = useMemo(() => schools.find(item => item.id === selectedSchoolId) || null, [schools, selectedSchoolId]);
  const currentMajor = useMemo(() => majors.find(item => item.id === selectedMajorId) || null, [majors, selectedMajorId]);
  const shownFields = useMemo(() => visibleFields(fields), [fields]);
  const filterFields = useMemo(() => fields.filter(item => item.isFilter).slice(0, 8), [fields]);
  const trendMetricFields = useMemo(() => trendFields(fields), [fields]);

  useEffect(() => {
    loadProfile()
      .then(payload => {
        const item = payload.item || null;
        setProfile(item);
        setSelectedSchoolId(item?.target?.schoolId || '');
        setSelectedMajorId(item?.target?.majorId || '');
      })
      .catch(() => setProfile(null));
  }, []);

  useEffect(() => {
    Promise.all([
      loadScorelineFields(regionId).catch(() => ({ items: [] })),
      loadScorelineSchools({ regionId, limit: 80 }).catch(() => ({ items: [] })),
      loadScorelineYears(regionId).catch(() => ({ items: [] })),
    ])
      .then(([fieldPayload, schoolPayload, yearPayload]) => {
        setFields(fieldPayload.items || []);
        setSchools(schoolPayload.items || []);
        setYears(yearPayload.items || []);
      })
      .catch(nextError => setError(nextError instanceof Error ? nextError.message : '分数线配置加载失败'));
  }, [regionId]);

  useEffect(() => {
    setSelectedMajorId(previous => (selectedSchoolId ? previous : ''));
    loadScorelineMajors({ regionId, schoolId: selectedSchoolId || undefined, limit: 200 })
      .then(payload => setMajors(payload.items || []))
      .catch(() => setMajors([]));
  }, [regionId, selectedSchoolId]);

  function loadRecords() {
    setLoading(true);
    setError('');
    const dynamicMinFilters: Record<string, string> = {};
    const dynamicFilters: Record<string, string> = {};
    filterFields.forEach(field => {
      const value = (filterValues[field.fieldKey] || '').trim();
      if (!value) return;
      if (['number', 'integer', 'decimal', 'float'].includes(normalizeFieldType(field))) {
        dynamicMinFilters[field.fieldKey] = value;
      } else {
        dynamicFilters[field.fieldKey] = value;
      }
    });

    Promise.all([
      loadScorelineRecords({
        regionId,
        schoolId: selectedSchoolId || undefined,
        majorId: selectedMajorId || undefined,
        year: selectedYear || undefined,
        pageSize: 50,
        dynamicFilters,
        dynamicMinFilters,
      }),
      loadScorelineTrend({
        regionId,
        schoolId: selectedSchoolId || undefined,
        majorId: selectedMajorId || undefined,
        limit: 20,
      }).catch(() => ({ items: [] })),
    ])
      .then(([recordPayload, trendPayload]) => {
        setRecords(recordPayload.items || []);
        setTotal(recordPayload.total || 0);
        setTrend(trendPayload.items || []);
      })
      .catch(nextError => setError(nextError instanceof Error ? nextError.message : '分数线加载失败'))
      .finally(() => setLoading(false));
  }

  useEffect(() => {
    loadRecords();
  }, [regionId, selectedSchoolId, selectedMajorId, selectedYear, refreshNonce]);

  function selectSchool(item: ScorelineSchool) {
    setSelectedSchoolId(previous => (previous === item.id ? '' : item.id));
    setSelectedMajorId('');
  }

  function selectMajor(item: ScorelineMajor) {
    setSelectedMajorId(previous => (previous === item.id ? '' : item.id));
  }

  function updateFilter(fieldKey: string, value: string) {
    setFilterValues(previous => ({ ...previous, [fieldKey]: value }));
  }

  function clearFilters() {
    setSelectedSchoolId('');
    setSelectedMajorId('');
    setSelectedYear(0);
    setFilterValues({});
    setRefreshNonce(value => value + 1);
  }

  return (
    <View className='student-page scoreline-page'>
      <View className='student-topbar'>
        <View className='student-title-block'>
          <Text className='student-kicker'>Scoreline</Text>
          <Text className='student-title'>历年分数线</Text>
          <Text className='student-subtitle'>
            {profile?.target?.regionName ? `${profile.target.regionName} · ${currentSchool?.name || profile.target.schoolName || '全部院校'}` : '按租户可见地区展示'}
          </Text>
        </View>
        <Button className='secondary-button' onClick={() => Taro.navigateTo({ url: '/pages/student/region/index' })}>地区</Button>
      </View>

      <View className='scoreline-filter-panel'>
        <View className='amount-row'>
          <View>
            <Text className='section-heading'>筛选</Text>
            <Text className='row-meta'>{currentMajor?.name || profile?.target?.majorName || '全部专业'} · {selectedYear || '全部年份'}</Text>
          </View>
          <Button className='secondary-button' onClick={clearFilters}>重置</Button>
        </View>

        <View className='scoreline-filter-group'>
          <Text className='scoreline-filter-label'>院校</Text>
          <View className='scoreline-chip-row'>
            {schools.slice(0, 12).map(item => (
              <View className={`scoreline-chip ${selectedSchoolId === item.id ? 'active' : ''}`} key={item.id} onClick={() => selectSchool(item)}>
                <Text className='scoreline-chip-text'>{item.shortName || item.name}{item.isHot ? ' · 热' : ''}</Text>
              </View>
            ))}
          </View>
        </View>

        {majors.length ? (
          <View className='scoreline-filter-group'>
            <Text className='scoreline-filter-label'>专业</Text>
            <View className='scoreline-chip-row'>
              {majors.slice(0, 16).map(item => (
                <View className={`scoreline-chip ${selectedMajorId === item.id ? 'active' : ''} ${item.hasRestriction ? 'warn' : ''}`} key={item.id} onClick={() => selectMajor(item)}>
                  <Text className='scoreline-chip-text'>{item.name}</Text>
                </View>
              ))}
            </View>
          </View>
        ) : null}

        {years.length ? (
          <View className='scoreline-filter-group'>
            <Text className='scoreline-filter-label'>年份</Text>
            <View className='scoreline-chip-row'>
              <View className={`scoreline-chip ${selectedYear === 0 ? 'active' : ''}`} onClick={() => setSelectedYear(0)}>
                <Text className='scoreline-chip-text'>全部</Text>
              </View>
              {years.slice(0, 8).map(item => (
                <View className={`scoreline-chip ${selectedYear === item ? 'active' : ''}`} key={item} onClick={() => setSelectedYear(item)}>
                  <Text className='scoreline-chip-text'>{item}</Text>
                </View>
              ))}
            </View>
          </View>
        ) : null}

        {filterFields.length ? (
          <View className='scoreline-field-grid'>
            {filterFields.map(field => {
              const options = optionLabels(field.options);
              return (
                <View className='scoreline-field-filter' key={field.id}>
                  <Text className='scoreline-filter-label'>{field.fieldName}</Text>
                  {options.length ? (
                    <View className='scoreline-chip-row compact'>
                      {options.slice(0, 8).map(option => (
                        <View
                          className={`scoreline-chip small ${filterValues[field.fieldKey] === option.value ? 'active' : ''}`}
                          key={option.value}
                          onClick={() => updateFilter(field.fieldKey, filterValues[field.fieldKey] === option.value ? '' : option.value)}
                        >
                          <Text className='scoreline-chip-text'>{option.label}</Text>
                        </View>
                      ))}
                    </View>
                  ) : (
                    <Input
                      className='input scoreline-input'
                      value={filterValues[field.fieldKey] || ''}
                      type={['number', 'integer', 'decimal', 'float'].includes(normalizeFieldType(field)) ? 'number' : 'text'}
                      placeholder={fieldPlaceholder(field)}
                      onInput={event => updateFilter(field.fieldKey, String(event.detail.value || ''))}
                    />
                  )}
                </View>
              );
            })}
          </View>
        ) : null}

        <Button className='primary-button scoreline-search-button' loading={loading} onClick={loadRecords}>查询</Button>
      </View>

      <View className='grid-two section-block'>
        <View className='metric compact-metric'>
          <Text className='metric-value'>{String(total)}</Text>
          <Text className='metric-label'>匹配记录</Text>
        </View>
        <View className='metric compact-metric'>
          <Text className='metric-value'>{String(trend.length)}</Text>
          <Text className='metric-label'>趋势样本</Text>
        </View>
      </View>

      {trend.length ? (
        <View className='section-block'>
          <Text className='section-heading'>趋势</Text>
          <View className='scoreline-trend-strip'>
            {trend.slice(0, 10).map(item => (
              <View className='scoreline-trend-item' key={item.id}>
                <Text className='scoreline-trend-year'>{item.year}</Text>
                <Text className='scoreline-trend-value'>
                  {trendMetricFields.map(field => `${field.fieldName}${fieldValue(item, field)}`).join(' · ')}
                </Text>
              </View>
            ))}
          </View>
        </View>
      ) : null}

      <View className='section-block'>
        <Text className='section-heading'>结果</Text>
        <View className='list-stack'>
          {records.map(item => (
            <View className='list-row' key={item.id}>
              <Text className='row-main'>{recordTitle(item)}</Text>
              <View className='scoreline-field-chip-grid'>
                {shownFields.slice(0, 8).map(field => (
                  <View className='scoreline-field-chip' key={`${item.id}:${field.fieldKey}`}>
                    <Text className='scoreline-field-name'>{field.fieldName}</Text>
                    <Text className='scoreline-field-value'>{fieldValue(item, field)}</Text>
                  </View>
                ))}
              </View>
            </View>
          ))}
        </View>
      </View>

      {!records.length && !loading ? <View className='empty-state'>暂无匹配分数线数据。</View> : null}
      {error ? <Text className='error-text'>{error}</Text> : null}
    </View>
  );
}
