import React, { useState, useEffect } from 'react';
import { View, Text, Input, Picker } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { createPatient, updatePatient, Patient } from '../../../services/patient';
import { useElderClass } from '../../../hooks/useElderClass';
import { useSafeTimeout } from '@/hooks/useSafeTimeout';
import PageShell from '@/components/ui/PageShell';
import './index.scss';

const RELATION_OPTIONS = ['本人', '配偶', '父母', '子女', '其他'];
const GENDER_OPTIONS = ['男', '女'];

export default function FamilyAdd() {
  const modeClass = useElderClass();
  const router = useRouter();
  const editId = router.params.id || '';
  const editData = Taro.getStorageSync('edit_patient') as Patient | null;

  const [name, setName] = useState(editData?.name || '');
  const [relationIdx, setRelationIdx] = useState(
    editData?.relation ? RELATION_OPTIONS.indexOf(editData.relation) : 0
  );
  const [genderIdx, setGenderIdx] = useState(
    editData?.gender === 'female' ? 1 : 0
  );
  const [birthDate, setBirthDate] = useState(editData?.birth_date || '');
  const [submitting, setSubmitting] = useState(false);
  const { safeSetTimeout } = useSafeTimeout();

  useEffect(() => {
    return () => { Taro.removeStorageSync('edit_patient'); };
  }, []);

  const handleSubmit = async () => {
    if (!name.trim()) {
      Taro.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    setSubmitting(true);
    Taro.showLoading({ title: '提交中...' });
    try {
      if (editId && editData) {
        await updatePatient(editId, {
          name: name.trim(),
          gender: GENDER_OPTIONS[genderIdx] === '男' ? 'male' : 'female',
          birth_date: birthDate || undefined,
          relation: RELATION_OPTIONS[relationIdx],
        }, editData.version);
        Taro.hideLoading();
        Taro.showToast({ title: '修改成功', icon: 'success' });
      } else {
        await createPatient({
          name: name.trim(),
          gender: GENDER_OPTIONS[genderIdx] === '男' ? 'male' : 'female',
          birth_date: birthDate || undefined,
        });
        Taro.hideLoading();
        Taro.showToast({ title: '添加成功', icon: 'success' });
      }
      safeSetTimeout(() => Taro.navigateBack(), 1000);
    } catch {
      Taro.hideLoading();
      Taro.showToast({ title: editId ? '修改失败' : '添加失败', icon: 'none' });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <PageShell padding="md" safeBottom={false} scroll={false} className={`family-add-page ${modeClass}`}>
      <Text className='family-add-title'>{editId ? '编辑就诊人' : '添加就诊人'}</Text>

      {/* 提示卡片 */}
      <View className='family-add-tip'>
        <Text className='family-add-tip-title'>完善个人信息</Text>
        <Text className='family-add-tip-desc'>
          完善信息后即可使用积分商城、签到等功能。请填写真实信息。
        </Text>
      </View>

      {/* 表单 */}
      <View className='form-card'>
        <View className='form-item'>
          <Text className='form-label'>姓名<Text className='form-required'>*</Text></Text>
          <View className='form-input-wrap'>
            <Input
              className='form-input'
              placeholder='请输入真实姓名'
              placeholderClass='form-placeholder'
              value={name}
              onInput={(e) => setName(e.detail.value)}
            />
          </View>
        </View>

        <View className='form-item'>
          <Text className='form-label'>关系<Text className='form-required'>*</Text></Text>
          <Picker
            mode='selector'
            range={RELATION_OPTIONS}
            value={relationIdx}
            onChange={(e) => setRelationIdx(Number(e.detail.value))}
          >
            <View className='form-picker-wrap'>
              <Text className='form-picker-text'>{RELATION_OPTIONS[relationIdx]}</Text>
              <Text className='form-picker-arrow'>›</Text>
            </View>
          </Picker>
        </View>

        <View className='form-item'>
          <Text className='form-label'>性别<Text className='form-required'>*</Text></Text>
          <Picker
            mode='selector'
            range={GENDER_OPTIONS}
            value={genderIdx}
            onChange={(e) => setGenderIdx(Number(e.detail.value))}
          >
            <View className='form-picker-wrap'>
              <Text className='form-picker-text'>{GENDER_OPTIONS[genderIdx]}</Text>
              <Text className='form-picker-arrow'>›</Text>
            </View>
          </Picker>
        </View>

        <View className='form-item'>
          <Text className='form-label'>出生日期<Text className='form-required'>*</Text></Text>
          <Picker
            mode='date'
            value={birthDate || '2000-01-01'}
            onChange={(e) => setBirthDate(e.detail.value)}
          >
            <View className='form-picker-wrap'>
              <Text className={`form-picker-text ${!birthDate ? 'placeholder' : ''}`}>
                {birthDate || '请选择'}
              </Text>
              <Text className='form-picker-arrow'>›</Text>
            </View>
          </Picker>
        </View>

        <View className='form-item'>
          <Text className='form-label'>手机号</Text>
          <View className='form-input-wrap'>
            <Input
              className='form-input'
              placeholder='选填，用于接收通知'
              placeholderClass='form-placeholder'
              type='number'
              maxlength={11}
            />
          </View>
        </View>

        <View className='form-item'>
          <Text className='form-label'>身份证号</Text>
          <View className='form-input-wrap'>
            <Input
              className='form-input'
              placeholder='选填，用于医保对接'
              placeholderClass='form-placeholder'
              maxlength={18}
            />
          </View>
        </View>
      </View>

      <View
        className={`submit-btn ${submitting ? 'disabled' : ''}`}
        onClick={submitting ? undefined : handleSubmit}
      >
        <Text className='submit-text'>{submitting ? '提交中...' : editId ? '保存修改' : '确认添加'}</Text>
      </View>
    </PageShell>
  );
}
