import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Input, Picker, Text, Textarea, View } from '@tarojs/components';
import {
  exportSchoolRecommendationReport,
  generateSchoolRecommendation,
  loadSchoolRecommendationReports,
  type SchoolRecommendationReport,
} from '@/services/ai';
import { loadProfile, type StudentProfile } from '@/services/profile';
import '../student.css';

const riskOptions = [
  { label: '均衡', value: 'balanced' },
  { label: '稳妥', value: 'safe' },
  { label: '冲刺', value: 'sprint' },
] as const;

function riskLabel(value?: string) {
  return riskOptions.find(item => item.value === value)?.label || '未知';
}

function recommendationRows(report: SchoolRecommendationReport | null) {
  return report?.resultPayload?.recommendedSchools || [];
}

function saveExportFile(fileName: string, content: string, mimeType: string) {
  if (process.env.TARO_ENV === 'h5' && typeof window !== 'undefined' && typeof document !== 'undefined') {
    const blob = new Blob([content], { type: mimeType });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    link.rel = 'noopener noreferrer';
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);
    return;
  }
  Taro.setClipboardData({ data: content });
  Taro.showToast({ title: '报告内容已复制', icon: 'none' });
}

export default function StudentAiSchoolPage() {
  const [profile, setProfile] = useState<StudentProfile | null>(null);
  const [reports, setReports] = useState<SchoolRecommendationReport[]>([]);
  const [current, setCurrent] = useState<SchoolRecommendationReport | null>(null);
  const [estimatedScore, setEstimatedScore] = useState('');
  const [constraints, setConstraints] = useState('');
  const [riskIndex, setRiskIndex] = useState(0);
  const [loading, setLoading] = useState(false);
  const [exporting, setExporting] = useState('');
  const [error, setError] = useState('');

  useEffect(() => {
    loadProfile().then(payload => setProfile(payload.item || null)).catch(() => setProfile(null));
    loadSchoolRecommendationReports({ limit: 5 })
      .then(payload => {
        const items = payload.items || [];
        setReports(items);
        setCurrent(items[0] || null);
      })
      .catch(() => setReports([]));
  }, []);

  async function handleGenerate() {
    setLoading(true);
    setError('');
    try {
      const payload = await generateSchoolRecommendation({
        regionId: profile?.target?.regionId || undefined,
        estimatedScore: estimatedScore ? Number(estimatedScore) : undefined,
        riskPreference: riskOptions[riskIndex].value,
        constraints: constraints || undefined,
        recommendationLimit: 5,
      });
      if (payload.item) {
        setCurrent(payload.item);
        setReports(previous => [payload.item!, ...previous.filter(item => item.id !== payload.item!.id)].slice(0, 5));
      }
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '生成失败');
    } finally {
      setLoading(false);
    }
  }

  async function handleExport(format: 'markdown' | 'html') {
    if (!current?.id) return;
    setExporting(format);
    setError('');
    try {
      const payload = await exportSchoolRecommendationReport(current.id, format);
      if (!payload.item?.contentText) throw new Error('后端未返回报告内容');
      saveExportFile(payload.item.fileName, payload.item.contentText, payload.item.mimeType);
      if (process.env.TARO_ENV === 'h5') Taro.showToast({ title: '报告已导出', icon: 'success' });
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '导出失败');
    } finally {
      setExporting('');
    }
  }

  const rows = recommendationRows(current);

  return (
    <View className='student-page'>
      <View className='student-topbar'>
        <View className='student-title-block'>
          <Text className='student-kicker'>AI Advisor</Text>
          <Text className='student-title'>AI择校推荐</Text>
          <Text className='student-subtitle'>
            {profile?.target?.regionName ? `${profile.target.regionName} · ${profile.membership?.isSvip ? 'SVIP' : '需SVIP'}` : '先在个人中心选择目标地区'}
          </Text>
        </View>
      </View>

      <View className='section'>
        <Text className='section-title'>生成报告</Text>
        <View className='list-stack'>
          <View className='list-row'>
            <Text className='row-meta'>预估分</Text>
            <Input
              type='number'
              value={estimatedScore}
              placeholder='例如 210'
              onInput={event => setEstimatedScore(String(event.detail.value || ''))}
            />
          </View>
          <View className='list-row'>
            <Text className='row-meta'>偏好</Text>
            <Picker
              mode='selector'
              range={riskOptions.map(item => item.label)}
              value={riskIndex}
              onChange={event => setRiskIndex(Number(event.detail.value || 0))}
            >
              <Text className='row-main'>{riskOptions[riskIndex].label}</Text>
            </Picker>
          </View>
          <View className='list-row'>
            <Text className='row-meta'>限制条件</Text>
            <Textarea
              value={constraints}
              placeholder='例如城市、专业限制、跨考顾虑'
              maxlength={500}
              onInput={event => setConstraints(String(event.detail.value || ''))}
            />
          </View>
        </View>
        <Button className='primary-button' loading={loading} onClick={handleGenerate}>生成推荐</Button>
        {error ? <Text className='error-text'>{error}</Text> : null}
      </View>

      {current ? (
        <View className='section'>
          <Text className='section-title'>推荐结果</Text>
          <View className='hero-band'>
            <Text className='hero-title'>{riskLabel(current.resultPayload.riskLevel)}方案</Text>
            <Text className='hero-copy'>{current.resultPayload.summary}</Text>
          </View>
          <View className='toolbar wrap compact-toolbar'>
            <Button className='secondary-button' loading={exporting === 'markdown'} onClick={() => handleExport('markdown')}>导出MD</Button>
            <Button className='secondary-button' loading={exporting === 'html'} onClick={() => handleExport('html')}>导出HTML</Button>
          </View>
          <View className='list-stack'>
            {rows.map(item => (
              <View className='list-row' key={`${item.schoolId || item.schoolName}:${item.majorId || item.majorName || ''}`}>
                <Text className='row-main'>{item.schoolName}{item.majorName ? ` · ${item.majorName}` : ''}</Text>
                <Text className='row-meta'>
                  {riskLabel(item.riskLevel)} · 置信度 {Math.round((item.confidence || 0) * 100)}% · 差值 {item.scoreGap ?? '未知'} 分
                </Text>
                <Text className='row-meta'>{item.reason}</Text>
              </View>
            ))}
          </View>
        </View>
      ) : null}

      <View className='section'>
        <Text className='section-title'>历史报告</Text>
        <View className='list-stack'>
          {reports.map(item => (
            <View className='list-row' key={item.id} onClick={() => setCurrent(item)}>
              <Text className='row-main'>{item.resultPayload?.summary || '择校推荐报告'}</Text>
              <Text className='row-meta'>{item.generatedAt || item.createdAt}</Text>
            </View>
          ))}
        </View>
        {!reports.length ? <View className='empty-state'>暂无历史报告。</View> : null}
      </View>
    </View>
  );
}
