import {useState, useEffect, useCallback} from 'react'
import {View, Text} from '@tarojs/components'
import Taro, {useDidShow} from '@tarojs/taro'
import {Loading, InfiniteLoading, Empty, Space, Button, SearchBar} from '@nutui/nutui-react-taro'
import {Phone} from '@nutui/icons-react-taro'
import type {ClinicPatientUser as PatientUserType} from "@/api/clinic/clinicPatientUser/model";
import FixedButton from "@/components/FixedButton";
import navTo from "@/utils/common";
import {
  pageClinicPatientUser,
  removeClinicPatientUser,
  updateClinicPatientUser
} from "@/api/clinic/clinicPatientUser";

// 扩展患者类型
interface PatientUser extends PatientUserType {
}

const PatientIndex = () => {
  const [list, setList] = useState<PatientUser[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [searchValue, setSearchValue] = useState<string>('')
  const [displaySearchValue, setDisplaySearchValue] = useState<string>('')
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)

  // 复制手机号
  const copyPhone = (phone: string) => {
    Taro.setClipboardData({
      data: phone,
      success: () => {
        Taro.showToast({
          title: '手机号已复制',
          icon: 'success',
          duration: 1500
        });
      }
    });
  };

  // 一键拨打
  const makePhoneCall = (phone: string) => {
    Taro.makePhoneCall({
      phoneNumber: phone,
      fail: () => {
        Taro.showToast({
          title: '拨打取消',
          icon: 'error'
        });
      }
    });
  };

  // 编辑备注
  const editComments = (patient: PatientUser) => {
    Taro.showModal({
      title: '编辑备注',
      // @ts-ignore
      editable: true,
      placeholderText: '请输入备注信息',
      content: patient.comments || '',
      success: async (res) => {
        // @ts-ignore
        if (res.confirm && res.content !== undefined) {
          try {
            // 更新备注
            await updateClinicPatientUser({
              ...patient,
              // @ts-ignore
              comments: res.content.trim()
            });

            Taro.showToast({
              title: '更新成功',
              icon: 'success'
            });

            // 刷新列表
            setList([]);
            setPage(1);
            setHasMore(true);
            fetchPatientData(true);
          } catch (error) {
            console.error('更新备注失败:', error);
            Taro.showToast({
              title: '更新失败，请重试',
              icon: 'error'
            });
          }
        }
      }
    });
  };

  // 获取患者数据
  const fetchPatientData = useCallback(async (resetPage = false, targetPage?: number) => {
    setLoading(true);
    try {
      const currentPage = resetPage ? 1 : (targetPage || page);

      // 构建API参数
      const params: any = {
        page: currentPage
      };

      // 添加搜索关键词
      if (displaySearchValue.trim()) {
        params.keywords = displaySearchValue.trim();
      }

      const res = await pageClinicPatientUser(params);

      if (res?.list && res.list.length > 0) {
        // 如果是重置页面或第一页，直接设置新数据；否则追加数据
        if (resetPage || currentPage === 1) {
          setList(res.list);
        } else {
          setList(prevList => prevList.concat(res.list));
        }

        // 正确判断是否还有更多数据
        const hasMoreData = res.list.length >= 10; // 假设每页10条数据
        setHasMore(hasMoreData);
      } else {
        if (resetPage || currentPage === 1) {
          setList([]);
        }
        setHasMore(false);
      }

      setPage(currentPage);
    } catch (error) {
      console.error('获取患者数据失败:', error);
      Taro.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setLoading(false);
    }
  }, [page, displaySearchValue]);

  const reloadMore = async () => {
    if (loading || !hasMore) return; // 防止重复加载
    const nextPage = page + 1;
    await fetchPatientData(false, nextPage);
  }

  // 防抖搜索功能
  useEffect(() => {
    const timer = setTimeout(() => {
      setDisplaySearchValue(searchValue);
    }, 300); // 300ms 防抖

    return () => clearTimeout(timer);
  }, [searchValue]);

  // 删除患者
  const handleDelete = (patient: PatientUser) => {
    removeClinicPatientUser(patient.id).then(() => {
      Taro.showToast({
        title: '删除成功',
        icon: 'success'
      });
      // 刷新数据
      setList([]);
      setPage(1);
      setHasMore(true);
      fetchPatientData(true).then();
    })
  }

  // 初始化数据
  useEffect(() => {
    fetchPatientData(true).then();
  }, [displaySearchValue]);

  // 监听页面显示，当从其他页面返回时刷新数据
  useDidShow(() => {
    // 刷新数据
    setList([]);
    setPage(1);
    setHasMore(true);
    fetchPatientData(true);
  });

  // 渲染患者项
  const renderPatientItem = (patient: PatientUser) => (
    <View key={patient.id} className="bg-white rounded-lg p-4 mb-3 shadow-sm">
      <View className="flex items-center mb-3">
        <View className="flex-1">
          <View className="flex items-center mb-1">
            <Space>
              <Text className="font-semibold text-gray-800 mr-2">
                {patient.realName || '未命名'}
              </Text>
              <Text className={'text-gray-400 font-normal'}>{patient.age}岁</Text>
              <Text className={'text-gray-400 font-normal'}>{patient.sex == '1' ? '男' : ''}{patient.sex == '2' ? '女' : ''}</Text>
            </Space>
          </View>
          <View className="flex items-center mb-1">
            <Space direction="vertical">
              <View className="flex items-center">
                <Text className="text-xs text-gray-500" onClick={(e) => {
                  e.stopPropagation();
                  makePhoneCall(patient.phone || '');
                }}>联系电话：{patient.phone || '未提供'}</Text>
                <View className="flex items-center ml-2">
                  <Phone
                    size={12}
                    className="text-green-500 mr-2"
                    onClick={(e) => {
                      e.stopPropagation();
                      makePhoneCall(patient.phone || '');
                    }}
                  />
                  <Text
                    className="text-xs text-blue-500 cursor-pointer"
                    onClick={(e) => {
                      e.stopPropagation();
                      copyPhone(patient.phone || '');
                    }}
                  >
                    复制
                  </Text>
                </View>
              </View>
              <Text className="text-xs text-gray-500">
                添加时间：{patient.createTime || '未知'}
              </Text>
            </Space>
          </View>

          {/* 显示 comments 字段 */}
          <Space className="flex items-center">
            <Text className="text-xs text-gray-500">备注：{patient.comments || '暂无'}</Text>
            <Text
              className="text-xs text-blue-500 cursor-pointer"
              onClick={(e) => {
                e.stopPropagation();
                editComments(patient);
              }}
            >
              编辑
            </Text>
          </Space>
        </View>
      </View>

      {/* 操作按钮 */}
      <Space className="flex justify-end">
        <Button
          size="small"
          onClick={() => navTo(`/doctor/orders/add?id=${patient.userId}`, true)}
          style={{marginRight: '8px', backgroundColor: '#ff4d4f', color: 'white'}}
        >
          开方
        </Button>
        <Button
          size="small"
          onClick={() => navTo(`/doctor/customer/add?id=${patient.id}`, true)}
          style={{marginRight: '8px', backgroundColor: '#1890ff', color: 'white'}}
        >
          详情
        </Button>
        <Button
          size="small"
          onClick={() => handleDelete(patient)}
          style={{backgroundColor: '#ff4d4f', color: 'white'}}
        >
          删除
        </Button>
      </Space>
    </View>
  );

  // 渲染患者列表
  const renderPatientList = () => {
    const isSearching = displaySearchValue.trim().length > 0;

    return (
      <View className="flex-1">
        {/* 搜索结果统计 */}
        {isSearching && (
          <View className="bg-white px-4 py-2 border-b border-gray-100">
            <Text className="text-sm text-gray-600">
              搜索 "{displaySearchValue}" 的结果，共找到 {list.length} 条记录
            </Text>
          </View>
        )}

        <View className="p-4" style={{
          height: isSearching ? 'calc(90vh - 40px)' : '90vh',
          overflowY: 'auto',
          overflowX: 'hidden'
        }}>
          <InfiniteLoading
            target="scroll"
            hasMore={hasMore}
            onLoadMore={reloadMore}
            onScroll={() => {
              // 滚动事件处理
            }}
            onScrollToUpper={() => {
              // 滚动到顶部事件处理
            }}
            loadingText={
              <>
                加载中...
              </>
            }
            loadMoreText={
              list.length === 0 ? (
                <Empty
                  style={{backgroundColor: 'transparent'}}
                  description={loading ? "加载中..." : "暂无患者数据"}
                />
              ) : (
                <View className={'h-3 flex items-center justify-center'}>
                  <Text className="text-gray-500 text-sm">没有更多了</Text>
                </View>
              )
            }
          >
            {loading && list.length === 0 ? (
              <View className="flex items-center justify-center py-8">
                <Loading/>
                <Text className="text-gray-500 mt-2 ml-2">加载中...</Text>
              </View>
            ) : (
              list.map(renderPatientItem)
            )}
          </InfiniteLoading>
        </View>
      </View>
    );
  };

  return (
    <View className="min-h-screen bg-gray-50">
      {/* 搜索栏 */}
      <View className="bg-white py-2 border-b border-gray-100">
        <SearchBar
          value={searchValue}
          placeholder="搜索患者姓名、手机号"
          onChange={(value) => setSearchValue(value)}
          onClear={() => {
            setSearchValue('');
            setDisplaySearchValue('');
          }}
          clearable
        />
      </View>

      {/* 患者列表 */}
      {renderPatientList()}

      <FixedButton text={'添加患者'} onClick={() => Taro.navigateTo({url: '/doctor/customer/add'})}/>
    </View>
  );
};

export default PatientIndex;
