import React, { useState, useEffect } from 'react';
import { View, Text, Input, Picker } from '@tarojs/components';
import Taro from '@tarojs/taro';
import EmptyState from '../../../components/EmptyState';
import './index.scss';

interface MedicationReminder {
  id: string;
  name: string;
  dosage: string;
  time: string;
  enabled: boolean;
}

const STORAGE_KEY = 'medication_reminders';

function loadReminders(): MedicationReminder[] {
  return Taro.getStorageSync(STORAGE_KEY) || [];
}

function saveReminders(reminders: MedicationReminder[]) {
  Taro.setStorageSync(STORAGE_KEY, reminders);
}

export default function MedicationReminder() {
  const [reminders, setReminders] = useState<MedicationReminder[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [formName, setFormName] = useState('');
  const [formDosage, setFormDosage] = useState('');
  const [formTime, setFormTime] = useState('08:00');

  useEffect(() => {
    setReminders(loadReminders());
  }, []);

  const updateReminders = (updated: MedicationReminder[]) => {
    setReminders(updated);
    saveReminders(updated);
  };

  const handleToggle = (id: string) => {
    const updated = reminders.map((r) =>
      r.id === id ? { ...r, enabled: !r.enabled } : r
    );
    updateReminders(updated);
  };

  const handleDelete = (id: string) => {
    Taro.showModal({
      title: '确认删除',
      content: '确定要删除这个提醒吗？',
    }).then((res) => {
      if (res.confirm) {
        updateReminders(reminders.filter((r) => r.id !== id));
      }
    });
  };

  const handleAdd = () => {
    if (!formName.trim()) {
      Taro.showToast({ title: '请输入药品名称', icon: 'none' });
      return;
    }
    const newReminder: MedicationReminder = {
      id: Date.now().toString(),
      name: formName.trim(),
      dosage: formDosage.trim(),
      time: formTime,
      enabled: true,
    };
    updateReminders([...reminders, newReminder]);
    setFormName('');
    setFormDosage('');
    setFormTime('08:00');
    setShowForm(false);
    Taro.showToast({ title: '添加成功', icon: 'success' });
  };

  return (
    <View className='medication-page'>
      <View className='reminder-list'>
        {reminders.map((r) => (
          <View className='reminder-card' key={r.id}>
            <View className='reminder-left'>
              <Text className='reminder-name'>{r.name}</Text>
              <Text className='reminder-dosage'>
                {r.dosage} | {r.time}
              </Text>
            </View>
            <View className='reminder-actions'>
              <View
                className={`toggle ${r.enabled ? 'on' : 'off'}`}
                onClick={() => handleToggle(r.id)}
              >
                <View className='toggle-dot' />
              </View>
              <Text
                className='delete-btn'
                onClick={() => handleDelete(r.id)}
              >
                删除
              </Text>
            </View>
          </View>
        ))}
      </View>

      {reminders.length === 0 && (
        <EmptyState text='暂无用药提醒' />
      )}

      {/* 添加表单 */}
      {showForm && (
        <View className='form-card'>
          <View className='form-item'>
            <Text className='form-label'>药品名称</Text>
            <Input
              className='form-input'
              placeholder='请输入药品名称'
              value={formName}
              onInput={(e) => setFormName(e.detail.value)}
            />
          </View>
          <View className='form-item'>
            <Text className='form-label'>剂量</Text>
            <Input
              className='form-input'
              placeholder='如：1片、10ml'
              value={formDosage}
              onInput={(e) => setFormDosage(e.detail.value)}
            />
          </View>
          <View className='form-item'>
            <Text className='form-label'>提醒时间</Text>
            <Picker
              mode='time'
              value={formTime}
              onChange={(e) => setFormTime(e.detail.value)}
            >
              <View className='time-picker-wrap'>
                <Text className='time-value'>{formTime}</Text>
                <Text className='time-arrow'>修改</Text>
              </View>
            </Picker>
          </View>
          <View className='form-actions'>
            <View className='form-cancel' onClick={() => setShowForm(false)}>
              <Text className='form-cancel-text'>取消</Text>
            </View>
            <View className='form-confirm' onClick={handleAdd}>
              <Text className='form-confirm-text'>确认</Text>
            </View>
          </View>
        </View>
      )}

      {!showForm && (
        <View className='add-btn' onClick={() => setShowForm(true)}>
          <Text className='add-text'>+ 添加提醒</Text>
        </View>
      )}
    </View>
  );
}
