import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { PageHeader } from '@/components/layout/PageHeader';
import { Card } from '@/components/common/Card';
import { Button } from '@/components/common/Button';
import { PieChart } from '@/components/charts/PieChart';
import * as medicationService from '@/services/medication.service';
import type { Medication, MedicationAdherence } from '@/types';
import styles from './MedicationDetailPage.module.css';

export function MedicationDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [medications, setMedications] = useState<Medication[]>([]);
  const [adherence, setAdherence] = useState<MedicationAdherence | null>(null);

  useEffect(() => {
    medicationService.getMedications().then(setMedications);
    if (id) medicationService.getAdherence(id).then(setAdherence).catch(() => {});
  }, [id]);

  const med = medications.find((m) => m.id === id);

  if (!med) {
    return (
      <div className="page--no-tab">
        <PageHeader title="药品详情" />
        <div style={{ padding: 40, textAlign: 'center', color: '#9CA3AF' }}>药品不存在</div>
      </div>
    );
  }

  return (
    <div className="page--no-tab">
      <PageHeader title={med.drugName} />
      <Card className={styles.infoCard}>
        <div className={styles.infoTitle}>{med.drugName}</div>
        <div className={styles.infoRow}><span>剂量</span><span>{med.dosage}</span></div>
        <div className={styles.infoRow}><span>服用时间</span><span>{med.timeSlots.join(', ')}</span></div>
        <div className={styles.infoRow}><span>日期</span><span>{med.startDate} ~ {med.endDate || '长期'}</span></div>
        <div className={styles.infoRow}><span>状态</span><span className={med.status === 'active' ? styles.activeBadge : ''}>{med.status === 'active' ? '进行中' : '已结束'}</span></div>
        {med.notes && <div className={styles.infoRow}><span>备注</span><span>{med.notes}</span></div>}
      </Card>

      {adherence && (
        <Card className={styles.adherenceCard}>
          <div className={styles.adherenceTitle}>近30天依从性</div>
          <div className={styles.adherenceRate}>{adherence.rate}%</div>
          <PieChart
            data={[
              { name: '已服用', value: adherence.rate, color: '#10B981' },
              { name: '未服用', value: 100 - adherence.rate, color: '#EF4444' },
            ]}
          />
        </Card>
      )}
    </div>
  );
}
