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 {ShopUser} from "@/api/shop/shopUser/model";
import {useUser} from "@/hooks/useUser";
import {useDoctorUser} from "@/hooks/useDoctorUser";
import {ClinicDoctorUser} from "@/api/clinic/clinicDoctorUser/model";
import {ClinicPatientUser} from "@/api/clinic/clinicPatientUser/model";
import {pageClinicDoctorUser} from "@/api/clinic/clinicDoctorUser";

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


  const {user} = useUser();

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

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

      const res = await pageClinicDoctorUser(params);

      if (res?.list && res.list.length > 0) {
        const mappedList = res.list.map(item => ({
          ...item
        }));

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

        // 正确判断是否还有更多数据
        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);
    }
  }, [activeTab, page]);

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


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

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

  // 根据搜索条件筛选数据（状态筛选已在API层面处理）
  const getFilteredList = () => {
    let filteredList = list;

    // 按搜索关键词筛选
    if (displaySearchValue.trim()) {
      const keyword = displaySearchValue.trim().toLowerCase();
      filteredList = filteredList.filter(item =>
        (item.realName && item.realName.toLowerCase().includes(keyword)) ||
        (item.dealerName && item.dealerName.toLowerCase().includes(keyword)) ||
        (item.dealerCode && item.dealerCode.toLowerCase().includes(keyword)) ||
        (item.mobile && item.mobile.includes(keyword)) ||
        (item.userId && item.userId.toString().includes(keyword))
      );
    }

    return filteredList;
  };

  // 初始化数据
  useEffect(() => {
    fetchDoctorUsers( true).then();

  }, []);

  // 当activeTab变化时重新获取数据
  useEffect(() => {
    setList([]); // 清空列表
    setPage(1); // 重置页码
    setHasMore(true); // 重置加载状态
    fetchDoctorUsers(true);
  }, [activeTab]);

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

  // 渲染医师项
  const renderDoctorItem = (item: ShopUser) => (
    <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">咨询医生</Button>
        </View>
      </View>
    </View>
  );

  // 渲染患者项
  const renderPatientUserItem = (item: ShopUser) => (
    <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} {item.sex} {item.age}岁
              </Text>
              <View className={'my-1'}>
                <Text className={'text-gray-400 text-xs'}>头晕</Text>
                <Divider direction="vertical"/>
                <Text className={'text-gray-400 text-xs'}>呕吐</Text>
              </View>
            </View>
          </View>
          <Button type="warning">开方</Button>
        </View>
      </View>
    </View>
  );

  // 渲染患者列表
  const renderPatientUserList = () => {
    const filteredList = getFilteredList();
    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)' : '84vh',
          overflowY: 'auto',
          overflowX: 'hidden'
        }}>
          <InfiniteLoading
            target="scroll"
            hasMore={hasMore}
            onLoadMore={reloadMore}
            onScroll={() => {
              // 滚动事件处理
            }}
            onScrollToUpper={() => {
              // 滚动到顶部事件处理
            }}
            loadingText={
              <>
                加载中...
              </>
            }
            loadMoreText={
              filteredList.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 && filteredList.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(renderPatientUserItem)
            )}
          </InfiniteLoading>
        </View>
      </View>
    );
  };

  // 渲染医生列表
  const renderDoctorList = () => {
    const filteredList = getFilteredList();
    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}" 的结果，共找到 {filteredList.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={
              filteredList.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 && filteredList.length === 0 ? (
              <View className="flex items-center justify-center py-8">
                <Loading/>
                <Text className="text-gray-500 mt-2 ml-2">加载中...</Text>
              </View>
            ) : (
              filteredList.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>

      {/* 患者列表 */}
      {!user?.certification && (renderPatientUserList())}
      {/* 医生列表 */}
      {user?.certification && (renderDoctorList())}


    </View>
  );
};

export default CustomerIndex;
