import { useState, useEffect, useCallback } from 'react';
import {
  listReminders,
  createReminder,
  cancelReminder,
  deleteReminder,
  type Reminder,
} from '@/api/reminders';

interface ReminderPanelProps {
  /** 从 Header 传入用户 ID */
  userId: string;
  /** 关闭面板 */
  onClose: () => void;
}

/** 状态标签颜色映射 */
const STATUS_STYLES: Record<string, string> = {
  pending: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400',
  completed: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
  cancelled: 'bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400',
};

/** 状态中文映射 */
const STATUS_LABELS: Record<string, string> = {
  pending: '待提醒',
  completed: '已完成',
  cancelled: '已取消',
};

/** 重复类型中文映射 */
const REPEAT_LABELS: Record<string, string> = {
  none: '不重复',
  daily: '每天',
  weekly: '每周',
  monthly: '每月',
};

/** 格式化时间 */
function formatDateTime(ts: string): string {
  try {
    const d = new Date(ts);
    return d.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  } catch {
    return ts;
  }
}

/** 转换为 datetime-local 输入框的格式 */
function toDatetimeLocal(isoStr: string): string {
  try {
    const d = new Date(isoStr);
    const pad = (n: number) => String(n).padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
  } catch {
    return '';
  }
}

export function ReminderPanel({ userId, onClose }: ReminderPanelProps) {
  const [activeTab, setActiveTab] = useState<'list' | 'create'>('list');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [reminders, setReminders] = useState<Reminder[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // 创建表单
  const [formTitle, setFormTitle] = useState('');
  const [formDesc, setFormDesc] = useState('');
  const [formTime, setFormTime] = useState('');
  const [formRepeat, setFormRepeat] = useState('none');
  const [submitting, setSubmitting] = useState(false);

  const fetchReminders = useCallback(async () => {
    setLoading(true);
    setError('');
    const resp = await listReminders(userId, statusFilter || undefined, 50);
    if (resp.error) {
      setError(resp.error);
      setReminders([]);
    } else {
      setReminders(resp.data?.reminders ?? []);
    }
    setLoading(false);
  }, [userId, statusFilter]);

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

  const handleCreate = async () => {
    if (!formTitle.trim()) return;
    if (!formTime) return;

    setSubmitting(true);
    const remindAt = new Date(formTime).toISOString();
    const resp = await createReminder({
      title: formTitle.trim(),
      description: formDesc.trim(),
      remind_at: remindAt,
      repeat_type: formRepeat,
    });

    if (resp.error) {
      setError(resp.error);
    } else {
      setFormTitle('');
      setFormDesc('');
      setFormTime('');
      setFormRepeat('none');
      setActiveTab('list');
      fetchReminders();
    }
    setSubmitting(false);
  };

  const handleCancel = async (id: string) => {
    await cancelReminder(id);
    fetchReminders();
  };

  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除这条提醒吗？')) return;
    await deleteReminder(id);
    fetchReminders();
  };

  return (
    <div className="w-full max-h-full flex flex-col">
      {/* Tab 切换 */}
      <div className="flex items-center border-b border-gray-100 dark:border-gray-700">
        <button
          onClick={() => setActiveTab('list')}
          className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
            activeTab === 'list'
              ? 'text-pink-500 border-b-2 border-pink-500'
              : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
          }`}
        >
          我的提醒
        </button>
        <button
          onClick={() => setActiveTab('create')}
          className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
            activeTab === 'create'
              ? 'text-pink-500 border-b-2 border-pink-500'
              : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
          }`}
        >
          + 新建
        </button>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="px-3 py-2 text-xs text-red-500 bg-red-50 dark:bg-red-900/20">
          ⚠️ {error}
          <button
            onClick={() => setError('')}
            className="ml-2 underline hover:no-underline"
          >
            关闭
          </button>
        </div>
      )}

      {/* 创建表单 */}
      {activeTab === 'create' && (
        <div className="p-3 space-y-3">
          <div>
            <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">
              标题 *
            </label>
            <input
              type="text"
              value={formTitle}
              onChange={(e) => setFormTitle(e.target.value)}
              placeholder="例如：喝水提醒"
              maxLength={200}
              className="w-full px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400"
            />
          </div>

          <div>
            <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">
              描述
            </label>
            <textarea
              value={formDesc}
              onChange={(e) => setFormDesc(e.target.value)}
              placeholder="提醒详情 (可选)"
              rows={2}
              maxLength={500}
              className="w-full px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400 resize-none"
            />
          </div>

          <div>
            <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">
              提醒时间 *
            </label>
            <input
              type="datetime-local"
              value={formTime}
              onChange={(e) => setFormTime(e.target.value)}
              className="w-full px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400"
            />
          </div>

          <div>
            <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">
              重复
            </label>
            <select
              value={formRepeat}
              onChange={(e) => setFormRepeat(e.target.value)}
              className="w-full px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400"
            >
              <option value="none">不重复</option>
              <option value="daily">每天</option>
              <option value="weekly">每周</option>
              <option value="monthly">每月</option>
            </select>
          </div>

          <div className="flex gap-2">
            <button
              onClick={() => {
                setActiveTab('list');
                setError('');
              }}
              className="flex-1 py-1.5 text-xs border border-gray-200 dark:border-gray-600 rounded-lg text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
            >
              取消
            </button>
            <button
              onClick={handleCreate}
              disabled={submitting || !formTitle.trim() || !formTime}
              className="flex-1 py-1.5 text-xs bg-pink-500 text-white rounded-lg hover:bg-pink-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {submitting ? '创建中...' : '创建提醒'}
            </button>
          </div>
        </div>
      )}

      {/* 提醒列表 */}
      {activeTab === 'list' && (
        <>
          {/* 状态筛选 */}
          <div className="flex gap-1 px-3 py-2 border-b border-gray-50 dark:border-gray-700">
            {['', 'pending', 'completed', 'cancelled'].map((s) => (
              <button
                key={s}
                onClick={() => setStatusFilter(s)}
                className={`px-2.5 py-1 text-[11px] rounded-full transition-colors ${
                  statusFilter === s
                    ? 'bg-pink-100 text-pink-600 dark:bg-pink-900/40 dark:text-pink-400'
                    : 'text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700'
                }`}
              >
                {s === '' ? '全部' : STATUS_LABELS[s]}
              </button>
            ))}
          </div>

          {/* 列表内容 */}
          <div className="overflow-y-auto max-h-72">
            {loading ? (
              <div className="px-4 py-8 text-center text-sm text-gray-400">
                ⏳ 加载中...
              </div>
            ) : reminders.length === 0 ? (
              <div className="px-4 py-8 text-center text-sm text-gray-400">
                🔔 暂无提醒，点击「+ 新建」创建
              </div>
            ) : (
              <div className="divide-y divide-gray-50 dark:divide-gray-700">
                {reminders.map((r) => (
                  <div
                    key={r.id}
                    className="px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors"
                  >
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="text-sm text-gray-800 dark:text-gray-200 truncate">
                            {r.title}
                          </span>
                          <span
                            className={`text-[10px] px-1.5 py-0.5 rounded-full flex-shrink-0 ${
                              STATUS_STYLES[r.status] || STATUS_STYLES.pending
                            }`}
                          >
                            {STATUS_LABELS[r.status] || r.status}
                          </span>
                        </div>
                        {r.description && (
                          <p className="text-xs text-gray-400 dark:text-gray-500 truncate mt-0.5">
                            {r.description}
                          </p>
                        )}
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-[10px] text-gray-400">
                            ⏰ {formatDateTime(r.remind_at)}
                          </span>
                          {r.repeat_type && r.repeat_type !== 'none' && (
                            <span className="text-[10px] text-pink-400">
                              🔄 {REPEAT_LABELS[r.repeat_type] || r.repeat_type}
                            </span>
                          )}
                        </div>
                      </div>

                      {/* 操作按钮 */}
                      <div className="flex items-center gap-1 flex-shrink-0">
                        {r.status === 'pending' && (
                          <button
                            onClick={() => handleCancel(r.id)}
                            title="取消提醒"
                            className="p-0.5 text-gray-300 hover:text-yellow-500 transition-colors"
                          >
                            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                          </button>
                        )}
                        <button
                          onClick={() => handleDelete(r.id)}
                          title="删除"
                          className="p-0.5 text-gray-300 hover:text-red-500 transition-colors"
                        >
                          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}
