import { useState, useEffect } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import { useElderClass } from '../../../hooks/useElderClass';
import { getStatusInlineStyle, getStatusLabel } from '@/utils/statusTag';
import './index.scss';

const TABS = [
  { key: '', label: '全部' },
  { key: 'pending', label: '待处理' },
  { key: 'in_progress', label: '进行中' },
  { key: 'completed', label: '已完成' },
  { key: 'overdue', label: '已逾期' },
];

export default function FollowUpList() {
  const router = useRouter();
  const patientId = router.params.patientId || '';
  const modeClass = useElderClass();
  const [tasks, setTasks] = useState<doctorApi.FollowUpTask[]>([]);
  const [activeTab, setActiveTab] = useState('');
  const [loading, setLoading] = useState(true);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    loadTasks();
  }, [activeTab, patientId]);

  const loadTasks = async () => {
    setLoading(true);
    try {
      const res = await doctorApi.listFollowUpTasks({
        page: 1,
        page_size: 50,
        status: activeTab || undefined,
        patient_id: patientId || undefined,
      });
      setTasks(res.data || []);
      setTotal(res.total || 0);
    } catch {
      Taro.showToast({ title: '加载失败', icon: 'none' });
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' });
  };

  const getTypeLabel = (type: string) => {
    const map: Record<string, string> = {
      phone: '电话随访',
      visit: '门诊随访',
      online: '线上随访',
      home: '家访',
    };
    return map[type] || type;
  };

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

  return (
    <ScrollView scrollY className={`followup-page ${modeClass}`}>
      <View className='tabs'>
        {TABS.map((t) => (
          <View
            key={t.key}
            className={`tab ${activeTab === t.key ? 'tab--active' : ''}`}
            onClick={() => setActiveTab(t.key)}
          >
            <Text>{t.label}</Text>
          </View>
        ))}
      </View>

      <View className='task-count'>
        <Text>共 {total} 项任务</Text>
      </View>

      {tasks.length === 0 ? (
        <EmptyState text='暂无随访任务' />
      ) : (
        <View className='task-list'>
          {tasks.map((task) => {
            return (
              <View
                key={task.id}
                className='task-card'
                onClick={() => Taro.navigateTo({ url: `/pages/doctor/followup/detail/index?id=${task.id}` })}
              >
                <View className='task-card__header'>
                  <Text className='task-card__type'>{getTypeLabel(task.follow_up_type)}</Text>
                  <View className='task-card__status' style={getStatusInlineStyle(task.status)}>
                    <Text>{getStatusLabel(task.status)}</Text>
                  </View>
                </View>
                <Text className='task-card__patient'>{task.patient_name || '未知患者'}</Text>
                <View className='task-card__footer'>
                  <Text className='task-card__date'>计划日期: {formatDate(task.planned_date)}</Text>
                </View>
              </View>
            );
          })}
        </View>
      )}
    </ScrollView>
  );
}
