import { useState, useEffect } from 'react';
import { View, Text, Input, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import './index.scss';

export default function PatientList() {
  const [patients, setPatients] = useState<doctorApi.PatientItem[]>([]);
  const [tags, setTags] = useState<doctorApi.PatientTag[]>([]);
  const [activeTag, setActiveTag] = useState<string>('');
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);

  useEffect(() => {
    loadTags();
  }, []);

  useEffect(() => {
    loadPatients();
  }, [page, activeTag]);

  const loadTags = async () => {
    try {
      const res = await doctorApi.listPatientTags();
      setTags(res.data || []);
    } catch { /* ignore */ }
  };

  const loadPatients = async () => {
    setLoading(true);
    try {
      const res = await doctorApi.listPatients({
        page,
        page_size: 20,
        search: search || undefined,
        tag_id: activeTag || undefined,
      });
      setPatients(res.data || []);
      setTotal(res.total || 0);
    } catch {
      Taro.showToast({ title: '加载失败', icon: 'none' });
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    setPage(1);
    loadPatients();
  };

  const handleTagFilter = (tagId: string) => {
    setActiveTag(tagId === activeTag ? '' : tagId);
    setPage(1);
  };

  const getGenderLabel = (gender?: string) => {
    if (!gender) return '';
    return gender === 'male' ? '男' : gender === 'female' ? '女' : gender;
  };

  const calcAge = (birthDate?: string) => {
    if (!birthDate) return '';
    const birth = new Date(birthDate);
    const now = new Date();
    let age = now.getFullYear() - birth.getFullYear();
    if (now.getMonth() < birth.getMonth() ||
      (now.getMonth() === birth.getMonth() && now.getDate() < birth.getDate())) {
      age--;
    }
    return `${age}岁`;
  };

  if (loading && patients.length === 0) return <Loading />;

  return (
    <ScrollView scrollY className='patient-list-page'>
      <View className='search-bar'>
        <Input
          className='search-input'
          placeholder='搜索患者姓名/手机号'
          value={search}
          onInput={(e) => setSearch(e.detail.value)}
          confirmType='search'
          onConfirm={handleSearch}
        />
      </View>

      {tags.length > 0 && (
        <ScrollView scrollX className='tag-filter'>
          <View
            className={`tag-chip ${!activeTag ? 'active' : ''}`}
            onClick={() => handleTagFilter('')}
          >
            <Text>全部</Text>
          </View>
          {tags.map((tag) => (
            <View
              key={tag.id}
              className={`tag-chip ${activeTag === tag.id ? 'active' : ''}`}
              style={activeTag === tag.id && tag.color ? `background: ${tag.color}; color: #fff` : ''}
              onClick={() => handleTagFilter(tag.id)}
            >
              <Text>{tag.name}</Text>
            </View>
          ))}
        </ScrollView>
      )}

      <View className='patient-count'>
        <Text>共 {total} 位患者</Text>
      </View>

      {patients.length === 0 ? (
        <EmptyState text='暂无患者数据' />
      ) : (
        <View className='patient-cards'>
          {patients.map((p) => (
            <View
              key={p.id}
              className='patient-card'
              onClick={() => Taro.navigateTo({ url: `/pages/doctor/patients/detail/index?id=${p.id}` })}
            >
              <View className='patient-card__header'>
                <Text className='patient-card__name'>{p.name}</Text>
                <Text className='patient-card__meta'>
                  {getGenderLabel(p.gender)} {calcAge(p.birth_date)}
                </Text>
              </View>
              {p.tags && p.tags.length > 0 && (
                <View className='patient-card__tags'>
                  {p.tags.map((t) => (
                    <View
                      key={t.id}
                      className='patient-tag'
                      style={t.color ? `background: ${t.color}20; color: ${t.color}` : ''}
                    >
                      <Text className='patient-tag__text'>{t.name}</Text>
                    </View>
                  ))}
                </View>
              )}
              {p.status && (
                <Text className={`patient-card__status patient-card__status--${p.status}`}>
                  {p.status === 'active' ? '活跃' : p.status === 'inactive' ? '非活跃' : p.status}
                </Text>
              )}
            </View>
          ))}
        </View>
      )}

      {total > 20 && (
        <View className='pagination'>
          <Text
            className={`pagination__btn ${page <= 1 ? 'disabled' : ''}`}
            onClick={() => page > 1 && setPage(page - 1)}
          >
            上一页
          </Text>
          <Text className='pagination__info'>{page} / {Math.ceil(total / 20)}</Text>
          <Text
            className={`pagination__btn ${page >= Math.ceil(total / 20) ? 'disabled' : ''}`}
            onClick={() => page < Math.ceil(total / 20) && setPage(page + 1)}
          >
            下一页
          </Text>
        </View>
      )}
    </ScrollView>
  );
}
