import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowRight, Check } from 'lucide-react';
import { GlassCard, GlassInput, GlassTextarea, GlassButton, GlassSelect } from '../components/ui';
import { PromptTagGroup } from '../components/PromptTag';
import useStore from '../store/useStore';
import { inspirationClusters } from '../utils/constants';
import * as dictionaryService from '../services/dictionary';
import * as lifeEventService from '../services/lifeEvent';

/**
 * OnboardingPage 组件
 * 5步入站流程页面
 */
const OnboardingPage = () => {
  const navigate = useNavigate();
  const { 
    currentStep, 
    setCurrentStep, 
    registrationData, 
    updateRegistration,
    saveUserProfile,
    setView,
    loading
  } = useStore();

  const [formData, setFormData] = useState(registrationData);
  const [isSaving, setIsSaving] = useState(false);
  
  // 字典数据状态
  const [zodiacOptions, setZodiacOptions] = useState([]);
  const [mbtiOptions, setMbtiOptions] = useState([]);
  const [genderOptions, setGenderOptions] = useState([]);

  useEffect(() => {
    setFormData(registrationData);
  }, [registrationData]);

  // 加载字典数据
  useEffect(() => {
    const loadDictionaries = async () => {
      try {
        const [zodiacList, mbtiList, genderList] = await Promise.all([
          dictionaryService.getZodiacList(),
          dictionaryService.getMbtiList(),
          dictionaryService.getGenderList()
        ]);
        setZodiacOptions([{ value: '', label: '请选择星座' }, ...dictionaryService.transformToOptions(zodiacList)]);
        setMbtiOptions([{ value: '', label: '请选择MBTI' }, ...dictionaryService.transformToOptions(mbtiList)]);
        setGenderOptions([{ value: '', label: '请选择性别' }, ...dictionaryService.transformToOptions(genderList)]);
      } catch (error) {
        console.error('加载字典数据失败:', error);
        // 使用默认选项
        setZodiacOptions([{ value: '', label: '请选择星座' }]);
        setMbtiOptions([{ value: '', label: '请选择MBTI' }]);
        setGenderOptions([{ value: '', label: '请选择性别' }]);
      }
    };
    loadDictionaries();
  }, []);

  const updateField = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const updateNestedField = (parent, field, value) => {
    setFormData(prev => ({
      ...prev,
      [parent]: { ...prev[parent], [field]: value }
    }));
  };

  const handleTagClick = (type, text) => {
    const currentText = formData[type]?.text || '';
    updateNestedField(type, 'text', currentText + text);
  };

  const saveStepData = () => {
    // 保存时将兴趣爱好字符串转换为数组
    const dataToSave = { ...formData };
    if (typeof dataToSave.hobbies === 'string') {
      dataToSave.hobbies = dataToSave.hobbies.split(/[,，]/).map(s => s.trim()).filter(s => s);
    }
    updateRegistration(dataToSave);
  };

  /**
   * 保存生命事件到后端
   * @param {Object} eventData - 事件数据 { date, text }
   * @param {string} eventType - 事件类型标识
   * @param {string} title - 事件标题
   */
  const saveLifeEvent = async (eventData, eventType, title) => {
    if (!eventData?.date || !eventData?.text) return;
    
    try {
      await lifeEventService.createEvent({
        title,
        time: eventData.date,
        content: eventData.text,
        eventType: 'milestone',
        tags: [eventType]
      });
    } catch (error) {
      console.error(`保存${title}失败:`, error);
    }
  };

  const handleNext = async () => {
    saveStepData();
    if (currentStep < 5) {
      setCurrentStep(currentStep + 1);
    } else {
      setIsSaving(true);
      try {
        // 保存用户档案
        await saveUserProfile();
        
        // 保存生命事件（童年记忆、开心经历、低谷时期）
        const eventsToSave = [
          { data: formData.childhood, type: 'childhood', title: '童年记忆' },
          { data: formData.joy, type: 'joy', title: '光芒闪耀的时刻' },
          { data: formData.low, type: 'low', title: '在暗夜中潜行' }
        ];
        
        await Promise.all(
          eventsToSave.map(({ data, type, title }) => saveLifeEvent(data, type, title))
        );
      } catch (error) {
        console.error('保存档案失败:', error);
      } finally {
        setIsSaving(false);
        setView('dashboard');
        navigate('/dashboard');
      }
    }
  };

  const handlePrev = () => {
    saveStepData();
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const renderStep1 = () => (
    <div className="animate-fade-in space-y-8">
      <div className="mb-6">
        <h2 className="text-4xl font-serif mb-3">你是谁？</h2>
        <p className="text-white/40 italic text-sm">定义你生命坐标的初始属性。</p>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-2">
        <GlassInput label="称呼" placeholder="例如：林中鹿" value={formData.nickname} onChange={(v) => updateField('nickname', v)} />
        <GlassSelect label="性别" options={genderOptions} value={formData.gender} onChange={(v) => updateField('gender', v)} />
        <GlassSelect label="MBTI" options={mbtiOptions} value={formData.mbti} onChange={(v) => updateField('mbti', v)} />
        <GlassSelect label="星座" options={zodiacOptions} value={formData.zodiac} onChange={(v) => updateField('zodiac', v)} />
      </div>
      <GlassInput
        label="兴趣爱好"
        placeholder="用逗号分隔你的热爱，如：阅读，旅行，摄影"
        value={Array.isArray(formData.hobbies) ? formData.hobbies.join('，') : (formData.hobbies || '')}
        onChange={(v) => updateField('hobbies', v)}
      />
    </div>
  );

  const renderMemoryStep = (type, title, label) => (
    <div className="animate-fade-in space-y-6">
      <div>
        <h2 className="text-4xl font-serif mb-3">{title}</h2>
        <p className="text-white/40 italic text-sm">回望足迹，这些瞬间如何塑造了此时的你。</p>
      </div>
      <div className="space-y-4">
        <GlassInput label={`${label}的日期`} type="date" value={formData[type]?.date || ''} onChange={(v) => updateNestedField(type, 'date', v)} className="max-w-xs" />
        <GlassTextarea label="详细描述" placeholder="描述那段时光发生的点滴..." value={formData[type]?.text || ''} onChange={(v) => updateNestedField(type, 'text', v)} rows={5} />
        <PromptTagGroup tags={inspirationClusters[type]} onTagClick={(text) => handleTagClick(type, text)} />
      </div>
    </div>
  );

  const renderStep5 = () => (
    <div className="animate-fade-in space-y-8">
      <div className="mb-6">
        <h2 className="text-4xl font-serif mb-3">未来想成为谁？</h2>
        <p className="text-white/40 italic text-sm">勾勒你对理想生活的全部向往。</p>
      </div>
      <GlassTextarea label="对未来的憧憬" placeholder="你想成为一个什么样的人？" value={formData.future?.vision || ''} onChange={(v) => updateNestedField('future', 'vision', v)} rows={4} />
      <GlassTextarea label="理想生活状态" placeholder="你的理想清晨与傍晚是怎样的？" value={formData.future?.ideal || ''} onChange={(v) => updateNestedField('future', 'ideal', v)} rows={4} />
    </div>
  );

  const renderStepContent = () => {
    switch (currentStep) {
      case 1: return renderStep1();
      case 2: return renderMemoryStep('childhood', '那段纯真的时光', '童年记忆');
      case 3: return renderMemoryStep('joy', '光芒闪耀的时刻', '开心的经历');
      case 4: return renderMemoryStep('low', '在暗夜中潜行', '沮丧与低谷');
      case 5: return renderStep5();
      default: return null;
    }
  };

  return (
    <GlassCard className="w-full h-full flex flex-col justify-between overflow-hidden relative" padding="lg">
      <div className="flex-1 flex flex-col justify-center max-w-2xl mx-auto w-full overflow-y-auto custom-scrollbar">
        {renderStepContent()}
      </div>
      <div className="flex items-center justify-between mt-10 max-w-2xl mx-auto w-full border-t border-white/5 pt-8">
        <div className="flex gap-2">
          {[1, 2, 3, 4, 5].map((step) => (
            <div key={step} className={`h-1 rounded-full transition-all duration-500 ${step === currentStep ? 'w-8 bg-orange-200' : 'w-3 bg-white/10'}`} />
          ))}
        </div>
        <div className="flex gap-4">
          {currentStep > 1 && (
            <button onClick={handlePrev} className="text-white/40 px-6 py-2 text-sm hover:text-white transition-colors">返回</button>
          )}
          <GlassButton onClick={handleNext} loading={isSaving || loading} className="px-8 py-3 rounded-full text-orange-200 font-bold tracking-widest text-sm shadow-xl shadow-orange-900/10">
            {currentStep === 5 ? (<>开启人生 <Check className="w-4 h-4 ml-2" /></>) : (<>继续 <ArrowRight className="w-4 h-4 ml-2" /></>)}
          </GlassButton>
        </div>
      </div>
    </GlassCard>
  );
};

export default OnboardingPage;
