import {useState, useEffect, useCallback} from 'react'
import {View, Text} from '@tarojs/components'
import Taro, {useDidShow} from '@tarojs/taro'
import {
  Loading,
  InfiniteLoading,
  Empty,
  Avatar,
  Tag,
  Divider,
  Button,
  SearchBar
} from '@nutui/nutui-react-taro'
import {pageClinicDoctorUser} from "@/api/clinic/clinicDoctorUser";
import {ClinicDoctorUser} from "@/api/clinic/clinicDoctorUser/model";
import {ClinicPatientUser} from "@/api/clinic/clinicPatientUser/model";
import {pageClinicPatientUser} from "@/api/clinic/clinicPatientUser";
import navTo from "@/utils/common";

const CustomerIndex = () => {
  const [isDoctor, setIsDoctor] = useState<boolean>(false)
  const [doctors, setDoctors] = useState<ClinicDoctorUser[]>([])
  const [patientUsers, setPatientUsers] = useState<ClinicPatientUser[]>([])
  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 fetchData = useCallback(async (resetPage = false, targetPage?: number) => {
    setLoading(true);
    if (Taro.getStorageSync('Doctor')) {
      setIsDoctor(true)
    }
    try {
      const currentPage = resetPage ? 1 : (targetPage || page);

      // 构建API参数，根据状态筛选
      const params: any = {
        page: currentPage
      };

      console.log(isDoctor, 'isDoctor>>>>')
      // 获取患者数据
      if (isDoctor || Taro.getStorageSync('Doctor')) {
        console.log('获取患者数据')
        const res = await pageClinicPatientUser(params);
        if (res?.list && res.list.length > 0) {
          const mappedList = res.list.map(item => ({
            ...item
          }));

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

          // 正确判断是否还有更多数据
        }
      } else {
        // 获取医师数据
        console.log('获取医师数据')
        const res = await pageClinicDoctorUser(params);
        if (res?.list && res.list.length > 0) {
          const mappedList = res.list.map(item => ({
            ...item
          }));

          console.log(mappedList, 'mappedList')
          // 如果是重置页面或第一页，直接设置新数据；否则追加数据
          if (resetPage || currentPage === 1) {
            console.log('设置新数据')
            setDoctors(mappedList);
          } else {
            console.log('追加数据')
            setDoctors(prevList => prevList.concat(mappedList));
          }
          console.log(doctors, 'doctors1')
          // 正确判断是否还有更多数据
          const hasMoreData = res.list.length >= 10; // 假设每页10条数据
          setHasMore(hasMoreData);
          console.log(doctors, 'doctors2')
        } else {
          if (resetPage || currentPage === 1) {
            console.log('设置新数据222')
            setDoctors([]);
          }
          setHasMore(false);
        }
      }

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

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

  const getSexName = (sex: any) => {
    if (sex === '1') {
      return '男'
    }
    if (sex === '2') {
      return '女'
    }
    return '未知'
  }


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

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

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

  // useEffect(() => {
  //   setPage(1); // 重置页码
  //   setHasMore(true); // 重置加载状态
  //   fetchData(true);
  // }, []);

  // 监听页面显示，当从其他页面返回时刷新数据
  useDidShow(() => {
    // 刷新当前tab的数据和统计信息
    setPatientUsers([]);
    setDoctors([])
    setPage(1);
    setHasMore(true);
    fetchData(true).then();
  });

  // 渲染医师项
  const renderDoctorItem = (item: ClinicDoctorUser) => (
    <View key={item.userId} className="bg-white rounded-lg p-4 mb-3 shadow-sm">
      <View className="flex items-center">
        <View className="flex-1 flex justify-between items-center">
          <View className="flex justify-between">
            <Avatar src={item.avatar} size={'large'}/>
            <View className={'flex flex-col mx-3'}>
              <Text className="font-semibold text-gray-800 mr-2">
                {item.realName} 医师
              </Text>
              <View>
                <Tag background="#f3f3f3" color="#999999">中医内科</Tag>
              </View>
              <View className={'my-1'}>
                <Text className={'text-gray-400 text-xs'}>问诊 1 次</Text>
                <Divider direction="vertical"/>
                <Text className={'text-gray-400 text-xs'}>开方 3 次</Text>
              </View>
            </View>
          </View>
          <Button type="warning" onClick={() => navTo(`/chat/doctor/index?id=${item.userId}`)}>咨询医生</Button>
        </View>
      </View>
    </View>
  );

  // 渲染患者项
  const renderPatientUserItem = (item: ClinicPatientUser) => (
    <View key={item.userId} className="bg-white rounded-lg p-4 mb-3 shadow-sm">
      <View className="flex items-center">
        <View className="flex-1 flex justify-between items-center">
          <View className="flex justify-between">
            <Avatar src={item.avatar} size={'large'}/>
            <View className={'flex flex-col mx-3'}>
              <Text className="font-semibold text-gray-800 mr-2">
                {item.realName}
              </Text>
              <View>
                {
                  <Text
                    className={'text-gray-400 text-xs'}>{getSexName(item.sex)}</Text>
                }
                {
                  item.age && (
                    <>
                      <Divider direction="vertical"/>
                      <Text className={'text-gray-400 text-xs'}>{item.age}岁</Text>
                    </>
                  )
                }
                {
                  item.weight && (
                    <>
                      <Divider direction="vertical"/>
                      <Text className={'text-gray-400 text-xs'}>{item.weight}</Text>
                    </>
                  )
                }
              </View>
              <View>
                <Text className={'text-gray-400 text-xs'}>{item.allergyHistory}</Text>
              </View>
            </View>
          </View>
          <Button type="warning" onClick={() => navTo(`/doctor/orders/add?id=${item.userId}`)}>开方</Button>
        </View>
      </View>
    </View>
  );

  // 渲染患者列表
  const renderPatientUserList = () => {
    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}" 的结果，共找到 {patientUsers.length} 条记录
            </Text>
          </View>
        )}

        <View className="p-4" style={{
          height: isSearching ? 'calc(90vh - 40px)' : '84vh',
          overflowY: 'auto',
          overflowX: 'hidden'
        }}>
          <InfiniteLoading
            target="scroll"
            hasMore={hasMore}
            onLoadMore={reloadMore}
            onScroll={() => {
              // 滚动事件处理
            }}
            onScrollToUpper={() => {
              // 滚动到顶部事件处理
            }}
            loadingText={
              <>
                加载中...
              </>
            }
            loadMoreText={
              patientUsers.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 && patientUsers.length === 0 ? (
              <View className="flex items-center justify-center py-8">
                <Loading/>
                <Text className="text-gray-500 mt-2 ml-2">加载中...</Text>
              </View>
            ) : (
              patientUsers.map(renderPatientUserItem)
            )}
          </InfiniteLoading>
        </View>
      </View>
    );
  };

  // 渲染医生列表
  const renderDoctorList = () => {
    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}" 的结果，共找到 {doctors.length} 条记录
            </Text>
          </View>
        )}

        <View className="p-4" style={{
          height: isSearching ? 'calc(90vh - 40px)' : '84vh',
          overflowY: 'auto',
          overflowX: 'hidden'
        }}>
          <InfiniteLoading
            target="scroll"
            hasMore={hasMore}
            onLoadMore={reloadMore}
            onScroll={() => {
              // 滚动事件处理
            }}
            onScrollToUpper={() => {
              // 滚动到顶部事件处理
            }}
            loadingText={
              <>
                加载中...
              </>
            }
            loadMoreText={
              doctors.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 && doctors.length === 0 ? (
              <View className="flex items-center justify-center py-8">
                <Loading/>
                <Text className="text-gray-500 mt-2 ml-2">加载中...</Text>
              </View>
            ) : (
              doctors.map(renderDoctorItem)
            )}
          </InfiniteLoading>
        </View>
      </View>
    );
  };

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

      {/* 患者列表 */}
      {isDoctor && (renderPatientUserList())}
      {/* 医生列表 */}
      {!isDoctor && (renderDoctorList())}

    </View>
  );
};

export default CustomerIndex;
