import {useEffect, useState, useRef} from "react";
import {Loading, CellGroup, Cell, Input, Form, Calendar} from '@nutui/nutui-react-taro'
import {Edit, Calendar as CalendarIcon} from '@nutui/icons-react-taro'
import Taro from '@tarojs/taro'
import {useRouter} from '@tarojs/taro'
import {View, Text} from '@tarojs/components'
import FixedButton from "@/components/FixedButton";
import {useUser} from "@/hooks/useUser";
import {ClinicPatientUser} from "@/api/clinic/clinicPatientUser/model";
import {
  addClinicPatientUser,
  getClinicPatientUser,
  updateClinicPatientUser
} from "@/api/clinic/clinicPatientUser";
import {
  formatDateForDatabase,
  extractDateForCalendar, formatDateForDisplay
} from "@/utils/dateUtils";

const AddPatient = () => {
  const {user} = useUser()
  const {params} = useRouter();
  const [loading, setLoading] = useState<boolean>(true)
  const [formData, setFormData] = useState<ClinicPatientUser>()
  const formRef = useRef<any>(null)
  const [isEditMode, setIsEditMode] = useState<boolean>(false)

  // 日期选择器状态
  const [showCreateTimePicker, setShowCreateTimePicker] = useState<boolean>(false)
  const [createTime, setCreateTime] = useState<string>('')

  console.log('AddPatient Component Rendered');

  // 处理创建时间选择
  const handleCreateTimeConfirm = (param: string) => {
    const selectedDate = param[3] // 选中的日期字符串 (YYYY-M-D)
    const formattedDate = formatDateForDatabase(selectedDate) // 转换为数据库格式
    setCreateTime(selectedDate) // 保存原始格式用于显示
    setShowCreateTimePicker(false)

    // 更新表单数据（使用数据库格式）
    if (formRef.current) {
      formRef.current.setFieldsValue({
        createTime: formattedDate
      })
    }
  }

  const reload = async () => {
    if (!params.id) {
      return false;
    }
    // 查询患者信息
    try {
      const patient = await getClinicPatientUser(Number(params.id));
      if (patient) {
        setFormData(patient)
        setIsEditMode(true);

        // 初始化日期数据（从数据库格式转换为Calendar组件格式）
        if (patient.createTime) {
          setCreateTime(extractDateForCalendar(patient.createTime))
        }

        Taro.setNavigationBarTitle({title: '编辑患者'})
      }
    } catch (error) {
      setLoading(true)
      console.error('查询患者信息失败:', error);
      setIsEditMode(false);
    }
  }

  // 提交表单
  const submitSucceed = async (values: any) => {
    try {
      // 验证必填字段
      if (!values.mobile || values.mobile.trim() === '') {
        Taro.showToast({
          title: '请填写联系方式',
          icon: 'error'
        });
        return;
      }

      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(values.mobile)) {
        Taro.showToast({
          title: '请填写正确的手机号',
          icon: 'error'
        });
        return;
      }

      // 准备提交的数据
      const submitData: ClinicPatientUser = {
        ...values,
        realName: values.realName || user?.nickname,
        mobile: values.mobile,
        // 确保日期数据正确提交（使用数据库格式）
        createTime: values.createTime || (createTime ? formatDateForDatabase(createTime) : new Date().toISOString().slice(0, 19).replace('T', ' '))
      };

      // 调试信息
      console.log('=== 提交数据调试 ===');
      console.log('是否编辑模式:', isEditMode);
      console.log('提交的数据:', submitData);
      console.log('==================');

      // 如果是编辑模式，添加现有患者的id
      if (isEditMode && formData?.id) {
        submitData.id = formData.id;
      }

      // 执行新增或更新操作
      if (isEditMode) {
        await updateClinicPatientUser(submitData);
      } else {
        await addClinicPatientUser(submitData);
      }

      Taro.showToast({
        title: `${isEditMode ? '更新' : '添加'}成功`,
        icon: 'success'
      });

      setTimeout(() => {
        Taro.navigateBack();
      }, 1000);

    } catch (error) {
      console.error('提交失败:', error);
      Taro.showToast({
        title: '提交失败，请重试',
        icon: 'error'
      });
    }
  }

  // 处理固定按钮点击事件
  const handleFixedButtonClick = () => {
    // 触发表单提交
    formRef.current?.submit();
  };

  const submitFailed = (error: any) => {
    console.log(error, 'err...')
  }

  useEffect(() => {
    reload().then(() => {
      setLoading(false)
    })
  }, []); // 依赖用户ID，当用户变化时重新加载

  if (loading) {
    return <Loading className={'px-2'}>加载中</Loading>
  }

  return (
    <>
      <Form
        ref={formRef}
        divider
        initialValues={formData}
        labelPosition="left"
        onFinish={(values) => submitSucceed(values)}
        onFinishFailed={(errors) => submitFailed(errors)}
      >
        <View className={'bg-gray-100 h-3'}></View>
        <CellGroup style={{padding: '4px 0'}}>
          <Form.Item name="realName" label="姓名" initialValue={formData?.realName} required>
            <Input placeholder="请输入患者姓名" />
          </Form.Item>
          <Form.Item name="mobile" label="联系方式" initialValue={formData?.mobile} required>
            <Input placeholder="请输入手机号" maxLength={11}/>
          </Form.Item>
          <Form.Item name="comments" label="备注" initialValue={formData?.comments}>
            <Input placeholder="请填写备注信息" />
          </Form.Item>
          <Form.Item name="createTime" label="创建时间" initialValue={formData?.createTime}>
            <View
              className="flex items-center justify-between py-2"
              onClick={() => setShowCreateTimePicker(true)}
            >
              <View className="flex items-center">
                <CalendarIcon size={16} color="#999" className="mr-2"/>
                <Text style={{color: createTime ? '#333' : '#999'}}>
                  {createTime ? formatDateForDisplay(createTime) : '请选择创建时间'}
                </Text>
              </View>
            </View>
          </Form.Item>
        </CellGroup>
      </Form>

      {/* 创建时间选择器 */}
      <Calendar
        visible={showCreateTimePicker}
        defaultValue={createTime}
        onClose={() => setShowCreateTimePicker(false)}
        onConfirm={handleCreateTimeConfirm}
      />

      {/* 底部浮动按钮 */}
      <FixedButton
        icon={<Edit/>}
        text={isEditMode ? '更新患者' : '添加患者'}
        onClick={handleFixedButtonClick}
      />

    </>
  );
};

export default AddPatient;