import React, { useState, useCallback } from 'react';
import { View, Text } from '@tarojs/components';
import Taro, { useReachBottom } from '@tarojs/taro';
import { usePageData } from '@/hooks/usePageData';
import { getCachedPatientId } from '@/services/request';
import { listDialysisPrescriptions } from '@/services/dialysis';
import type { DialysisPrescription } from '@/services/dialysis';
import EmptyState from '@/components/EmptyState';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../hooks/useElderClass';
import PageShell from '@/components/ui/PageShell';
import './index.scss';

const STATUS_MAP: Record<string, { label: string; cls: string }> = {
  active: { label: '生效中', cls: 'active' },
  inactive: { label: '已停用', cls: 'inactive' },
  expired: { label: '已过期', cls: 'expired' },
};

export default function DialysisPrescriptionList() {
  const modeClass = useElderClass();
  const [prescriptions, setPrescriptions] = useState<DialysisPrescription[]>([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [hasPatient, setHasPatient] = useState(true);

  const fetchData = useCallback(async (p: number, append = false) => {
    const patientId = getCachedPatientId();
    if (!patientId) {
      setPrescriptions([]);
      setHasPatient(false);
      return;
    }
    setHasPatient(true);
    setLoading(true);
    try {
      const res = await listDialysisPrescriptions({ patient_id: patientId, page: p, page_size: 20 });
      const list = res.data || [];
      setPrescriptions(append ? (prev) => [...prev, ...list] : list);
      setTotal(res.total);
      setPage(p);
    } catch {
      Taro.showToast({ title: '加载失败', icon: 'none' });
    } finally {
      setLoading(false);
    }
  }, []);

  usePageData(async () => { await fetchData(1); }, { throttleMs: 10000, enablePullDown: true });

  useReachBottom(() => {
    if (!loading && prescriptions.length < total) {
      fetchData(page + 1, true);
    }
  });

  const statusInfo = (s: string) => STATUS_MAP[s] || { label: s, cls: '' };

  return (
    <PageShell className={modeClass}>
      <Text className='page-title'>透析处方</Text>

      <View className='prescription-list'>
        {prescriptions.map((p) => {
          const si = statusInfo(p.status);
          return (
            <View
              className='prescription-card'
              key={p.id}
              onClick={() => Taro.navigateTo({ url: `/pages/pkg-profile/dialysis-prescriptions/detail/index?id=${p.id}` })}
            >
              <View className='prescription-card-top'>
                <Text className='prescription-model'>{p.dialyzer_model || '未指定型号'}</Text>
                <Text className={`status-tag ${si.cls}`}>{si.label}</Text>
              </View>
              <View className='prescription-meta'>
                {p.frequency_per_week != null && (
                  <Text className='meta-item'>{p.frequency_per_week}次/周</Text>
                )}
                {p.duration_minutes != null && (
                  <Text className='meta-item'>每次{p.duration_minutes}分钟</Text>
                )}
              </View>
              {(p.effective_from || p.effective_to) && (
                <Text className='prescription-date'>
                  {p.effective_from || '...'} ~ {p.effective_to || '...'}
                </Text>
              )}
            </View>
          );
        })}
      </View>

      {prescriptions.length === 0 && !loading && (
        <EmptyState text={hasPatient ? '暂无透析处方' : '请先在就诊人管理中选择就诊人'} />
      )}

      {loading && <Loading />}
    </PageShell>
  );
}
