'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Bell,
  Plus,
  RefreshCw,
  Pencil,
  Trash2,
  ToggleLeft,
  ToggleRight,
  X,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import {
  NotificationItem,
  NotificationType,
  NotificationPriority,
  TargetType,
  TagLogic,
  CreateNotificationPayload,
  NOTIFICATION_TYPE_OPTIONS,
  NOTIFICATION_PRIORITY_OPTIONS,
  TARGET_TYPE_OPTIONS,
  PLAN_OPTIONS,
  STATUS_OPTIONS,
} from '@/domain/entities/notification';
import {
  listAdminNotifications,
  createNotification,
  updateNotification,
  deleteNotification,
  toggleNotification,
} from '@/infrastructure/repositories/api-notification.repository';
import { listTenantTags } from '@/infrastructure/repositories/api-tenant-tag.repository';
import { TenantTag } from '@/domain/entities/tenant-tag';

/* ---------- helpers ---------- */

function typeBadge(type: NotificationType) {
  const opt = NOTIFICATION_TYPE_OPTIONS.find((o) => o.value === type);
  return (
    <span className={cn('inline-flex items-center px-2 py-0.5 rounded text-xs font-medium', opt?.color ?? 'bg-gray-100 text-gray-700')}>
      {opt?.label ?? type}
    </span>
  );
}

function targetLabel(item: NotificationItem) {
  switch (item.targetType) {
    case 'ALL': return '全部租户';
    case 'SPECIFIC_TENANTS': return `指定租户 (${item.tenantIds?.length ?? 0})`;
    case 'SPECIFIC_USERS': return `指定用户 (${item.userIds?.length ?? 0})`;
    case 'BY_TENANT_TAG': return `按标签 (${item.targetTagIds?.length ?? 0})`;
    case 'BY_PLAN': return `套餐: ${item.targetPlans?.join(', ') ?? '—'}`;
    case 'BY_TENANT_STATUS': return `状态: ${item.targetStatuses?.join(', ') ?? '—'}`;
    case 'BY_SEGMENT': return `人群包: ${item.targetSegment ?? '—'}`;
    default: return item.targetType;
  }
}

function priorityLabel(p: NotificationPriority) {
  const map: Record<NotificationPriority, string> = {
    LOW: '低', NORMAL: '普通', HIGH: '高', URGENT: '紧急',
  };
  return map[p] ?? p;
}

function formatDate(s: string | null) {
  if (!s) return '—';
  return new Date(s).toLocaleString('zh-CN', { dateStyle: 'short', timeStyle: 'short' });
}

/* ---------- form defaults ---------- */

const EMPTY_FORM: CreateNotificationPayload = {
  title: '',
  content: '',
  type: 'ANNOUNCEMENT',
  priority: 'NORMAL',
  targetType: 'ALL',
  tenantIds: [],
  userIds: [],
  targetTagIds: [],
  targetTagLogic: 'ANY',
  targetPlans: [],
  targetStatuses: [],
  targetSegment: null,
  channelKey: null,
  imageUrl: null,
  linkUrl: null,
  requiresForceRead: false,
  isEnabled: true,
  publishedAt: null,
  expiresAt: null,
};

/* ---------- Modal ---------- */

function NotificationModal({
  initial,
  allTags,
  onSave,
  onClose,
}: {
  initial: Partial<CreateNotificationPayload> & { id?: string };
  allTags: TenantTag[];
  onSave: (payload: CreateNotificationPayload, id?: string) => Promise<void>;
  onClose: () => void;
}) {
  const [form, setForm] = useState<CreateNotificationPayload>({
    ...EMPTY_FORM,
    ...initial,
  });
  const [tenantIdsRaw, setTenantIdsRaw] = useState((initial.tenantIds ?? []).join('\n'));
  const [userIdsRaw, setUserIdsRaw] = useState((initial.userIds ?? []).join('\n'));
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const set = <K extends keyof CreateNotificationPayload>(k: K, v: CreateNotificationPayload[K]) =>
    setForm((f) => ({ ...f, [k]: v }));

  const togglePlan = (plan: string) => {
    const cur = form.targetPlans ?? [];
    set('targetPlans', cur.includes(plan) ? cur.filter((p) => p !== plan) : [...cur, plan]);
  };

  const toggleStatus = (status: string) => {
    const cur = form.targetStatuses ?? [];
    set('targetStatuses', cur.includes(status) ? cur.filter((s) => s !== status) : [...cur, status]);
  };

  const toggleTag = (tagId: string) => {
    const cur = form.targetTagIds ?? [];
    set('targetTagIds', cur.includes(tagId) ? cur.filter((t) => t !== tagId) : [...cur, tagId]);
  };

  const handleSubmit = async () => {
    if (!form.title.trim()) { setError('标题不能为空'); return; }
    if (!form.content.trim()) { setError('内容不能为空'); return; }
    setSaving(true);
    setError('');
    try {
      const tenantIds = tenantIdsRaw.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean);
      const userIds = userIdsRaw.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean);
      await onSave({ ...form, tenantIds, userIds }, initial.id);
      onClose();
    } catch (e: any) {
      setError(e.message ?? '保存失败');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="bg-card w-full max-w-2xl rounded-xl shadow-xl border flex flex-col max-h-[90vh]">
        {/* header */}
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="text-base font-semibold">{initial.id ? '编辑通知' : '新建通知'}</h2>
          <button onClick={onClose} className="text-muted-foreground hover:text-foreground">
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* body */}
        <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
          {error && <p className="text-sm text-red-500">{error}</p>}

          {/* title */}
          <div>
            <label className="block text-xs font-medium mb-1">标题 *</label>
            <input
              className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary"
              value={form.title}
              onChange={(e) => set('title', e.target.value)}
              maxLength={200}
              placeholder="通知标题"
            />
          </div>

          {/* content */}
          <div>
            <label className="block text-xs font-medium mb-1">内容 *</label>
            <textarea
              className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary resize-none"
              rows={5}
              value={form.content}
              onChange={(e) => set('content', e.target.value)}
              placeholder="通知正文内容"
            />
          </div>

          {/* type + priority */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium mb-1">类型</label>
              <select
                className="w-full rounded-md border bg-background px-3 py-2 text-sm"
                value={form.type}
                onChange={(e) => set('type', e.target.value as NotificationType)}
              >
                {NOTIFICATION_TYPE_OPTIONS.map((o) => (
                  <option key={o.value} value={o.value}>{o.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium mb-1">优先级</label>
              <select
                className="w-full rounded-md border bg-background px-3 py-2 text-sm"
                value={form.priority}
                onChange={(e) => set('priority', e.target.value as NotificationPriority)}
              >
                {NOTIFICATION_PRIORITY_OPTIONS.map((o) => (
                  <option key={o.value} value={o.value}>{o.label}</option>
                ))}
              </select>
            </div>
          </div>

          {/* target type */}
          <div>
            <label className="block text-xs font-medium mb-1">推送对象</label>
            <select
              className="w-full rounded-md border bg-background px-3 py-2 text-sm"
              value={form.targetType}
              onChange={(e) => set('targetType', e.target.value as TargetType)}
            >
              {TARGET_TYPE_OPTIONS.map((o) => (
                <option key={o.value} value={o.value}>{o.label} — {o.desc}</option>
              ))}
            </select>
          </div>

          {/* SPECIFIC_TENANTS */}
          {form.targetType === 'SPECIFIC_TENANTS' && (
            <div>
              <label className="block text-xs font-medium mb-1">指定租户 ID（每行一个）</label>
              <textarea
                className="w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-primary resize-none"
                rows={4}
                value={tenantIdsRaw}
                onChange={(e) => setTenantIdsRaw(e.target.value)}
                placeholder="tenant-uuid-1&#10;tenant-uuid-2"
              />
            </div>
          )}

          {/* SPECIFIC_USERS */}
          {form.targetType === 'SPECIFIC_USERS' && (
            <div>
              <label className="block text-xs font-medium mb-1">指定用户 ID（每行一个）</label>
              <textarea
                className="w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-primary resize-none"
                rows={4}
                value={userIdsRaw}
                onChange={(e) => setUserIdsRaw(e.target.value)}
                placeholder="user-uuid-1&#10;user-uuid-2"
              />
            </div>
          )}

          {/* BY_TENANT_TAG */}
          {form.targetType === 'BY_TENANT_TAG' && (
            <div className="space-y-2">
              <div>
                <label className="block text-xs font-medium mb-1">标签逻辑</label>
                <div className="flex gap-4">
                  {(['ANY', 'ALL'] as TagLogic[]).map((logic) => (
                    <label key={logic} className="flex items-center gap-2 cursor-pointer text-sm">
                      <input
                        type="radio"
                        value={logic}
                        checked={form.targetTagLogic === logic}
                        onChange={() => set('targetTagLogic', logic)}
                      />
                      {logic === 'ANY' ? '任一标签（OR）' : '全部标签（AND）'}
                    </label>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-xs font-medium mb-1">选择标签</label>
                {allTags.length === 0 ? (
                  <p className="text-xs text-muted-foreground">暂无标签，请先在「租户标签」页面创建。</p>
                ) : (
                  <div className="flex flex-wrap gap-2">
                    {allTags.map((tag) => {
                      const selected = (form.targetTagIds ?? []).includes(tag.id);
                      return (
                        <button
                          key={tag.id}
                          type="button"
                          onClick={() => toggleTag(tag.id)}
                          className={cn(
                            'px-3 py-1 rounded-full text-xs font-medium border transition-colors',
                            selected ? 'border-primary bg-primary text-primary-foreground' : 'border-border hover:border-primary',
                          )}
                          style={!selected ? { borderColor: tag.color, color: tag.color } : {}}
                        >
                          {tag.name}
                        </button>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>
          )}

          {/* BY_PLAN */}
          {form.targetType === 'BY_PLAN' && (
            <div>
              <label className="block text-xs font-medium mb-1">选择套餐</label>
              <div className="flex flex-wrap gap-2">
                {PLAN_OPTIONS.map((plan) => {
                  const selected = (form.targetPlans ?? []).includes(plan);
                  return (
                    <button
                      key={plan}
                      type="button"
                      onClick={() => togglePlan(plan)}
                      className={cn(
                        'px-3 py-1 rounded-full text-xs font-medium border transition-colors',
                        selected ? 'border-primary bg-primary text-primary-foreground' : 'border-border hover:border-primary',
                      )}
                    >
                      {plan}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* BY_TENANT_STATUS */}
          {form.targetType === 'BY_TENANT_STATUS' && (
            <div>
              <label className="block text-xs font-medium mb-1">选择租户状态</label>
              <div className="flex flex-wrap gap-2">
                {STATUS_OPTIONS.map((status) => {
                  const selected = (form.targetStatuses ?? []).includes(status);
                  return (
                    <button
                      key={status}
                      type="button"
                      onClick={() => toggleStatus(status)}
                      className={cn(
                        'px-3 py-1 rounded-full text-xs font-medium border transition-colors',
                        selected ? 'border-primary bg-primary text-primary-foreground' : 'border-border hover:border-primary',
                      )}
                    >
                      {status}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* BY_SEGMENT */}
          {form.targetType === 'BY_SEGMENT' && (
            <div>
              <label className="block text-xs font-medium mb-1">人群包 Key</label>
              <input
                className="w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary"
                value={form.targetSegment ?? ''}
                onChange={(e) => set('targetSegment', e.target.value || null)}
                placeholder="例如: trial_ending_soon"
              />
            </div>
          )}

          {/* image / link */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium mb-1">图片链接（可选）</label>
              <input
                className="w-full rounded-md border bg-background px-3 py-2 text-sm"
                value={form.imageUrl ?? ''}
                onChange={(e) => set('imageUrl', e.target.value || null)}
                placeholder="https://..."
              />
            </div>
            <div>
              <label className="block text-xs font-medium mb-1">跳转链接（可选）</label>
              <input
                className="w-full rounded-md border bg-background px-3 py-2 text-sm"
                value={form.linkUrl ?? ''}
                onChange={(e) => set('linkUrl', e.target.value || null)}
                placeholder="https://..."
              />
            </div>
          </div>

          {/* published / expires */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium mb-1">发布时间（空=立即）</label>
              <input
                type="datetime-local"
                className="w-full rounded-md border bg-background px-3 py-2 text-sm"
                value={form.publishedAt ? form.publishedAt.slice(0, 16) : ''}
                onChange={(e) => set('publishedAt', e.target.value ? new Date(e.target.value).toISOString() : null)}
              />
            </div>
            <div>
              <label className="block text-xs font-medium mb-1">过期时间（空=永不）</label>
              <input
                type="datetime-local"
                className="w-full rounded-md border bg-background px-3 py-2 text-sm"
                value={form.expiresAt ? form.expiresAt.slice(0, 16) : ''}
                onChange={(e) => set('expiresAt', e.target.value ? new Date(e.target.value).toISOString() : null)}
              />
            </div>
          </div>

          {/* toggles */}
          <div className="flex items-center gap-6">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={form.requiresForceRead}
                onChange={(e) => set('requiresForceRead', e.target.checked)}
                className="rounded"
              />
              <span className="text-sm">强制阅读（用户打开 App 必须确认）</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={form.isEnabled}
                onChange={(e) => set('isEnabled', e.target.checked)}
                className="rounded"
              />
              <span className="text-sm">立即启用</span>
            </label>
          </div>
        </div>

        {/* footer */}
        <div className="flex justify-end gap-2 px-6 py-4 border-t">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border hover:bg-accent transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleSubmit}
            disabled={saving}
            className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
          >
            {saving ? '保存中…' : '保存'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Main page ---------- */

export default function NotificationsPage() {
  const [items, setItems] = useState<NotificationItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [filterType, setFilterType] = useState('');
  const [filterTarget, setFilterTarget] = useState('');
  const [offset, setOffset] = useState(0);
  const limit = 20;
  const [allTags, setAllTags] = useState<TenantTag[]>([]);

  const [modal, setModal] = useState<
    { mode: 'create' } | { mode: 'edit'; item: NotificationItem } | null
  >(null);
  const [deleting, setDeleting] = useState<string | null>(null);

  useEffect(() => {
    listTenantTags().then(setAllTags).catch(console.error);
  }, []);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const result = await listAdminNotifications({
        type: filterType || undefined,
        targetType: filterTarget || undefined,
        limit,
        offset,
      });
      setItems(result.items);
      setTotal(result.total);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, [filterType, filterTarget, offset]);

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

  const handleSave = async (payload: CreateNotificationPayload, id?: string) => {
    if (id) {
      await updateNotification(id, payload);
    } else {
      await createNotification(payload);
    }
    await load();
  };

  const handleToggle = async (item: NotificationItem) => {
    await toggleNotification(item.id, !item.isEnabled);
    await load();
  };

  const handleDelete = async (id: string) => {
    if (!confirm('确认删除该通知？')) return;
    setDeleting(id);
    try {
      await deleteNotification(id);
      await load();
    } finally {
      setDeleting(null);
    }
  };

  return (
    <div className="flex-1 flex flex-col min-h-0 p-6">
      {/* header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2">
          <Bell className="h-5 w-5 text-primary" />
          <h1 className="text-xl font-semibold">站内消息管理</h1>
          <span className="text-xs text-muted-foreground ml-1">（仅平台管理员可见）</span>
        </div>
        <div className="flex items-center gap-2">
          <select
            className="rounded-md border bg-background px-3 py-1.5 text-sm"
            value={filterType}
            onChange={(e) => { setFilterType(e.target.value); setOffset(0); }}
          >
            <option value="">全部类型</option>
            {NOTIFICATION_TYPE_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>{o.label}</option>
            ))}
          </select>
          <select
            className="rounded-md border bg-background px-3 py-1.5 text-sm"
            value={filterTarget}
            onChange={(e) => { setFilterTarget(e.target.value); setOffset(0); }}
          >
            <option value="">全部对象</option>
            {TARGET_TYPE_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>{o.label}</option>
            ))}
          </select>
          <button
            onClick={load}
            disabled={loading}
            className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md border hover:bg-accent transition-colors"
          >
            <RefreshCw className={cn('h-3.5 w-3.5', loading && 'animate-spin')} />
            刷新
          </button>
          <button
            onClick={() => setModal({ mode: 'create' })}
            className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
          >
            <Plus className="h-3.5 w-3.5" />
            新建通知
          </button>
        </div>
      </div>

      {/* table */}
      <div className="flex-1 min-h-0 overflow-auto rounded-lg border bg-card">
        <table className="w-full text-sm">
          <thead className="bg-muted/50 sticky top-0">
            <tr>
              <th className="text-left px-4 py-3 font-medium text-muted-foreground w-48">标题</th>
              <th className="text-left px-4 py-3 font-medium text-muted-foreground">类型</th>
              <th className="text-left px-4 py-3 font-medium text-muted-foreground">优先级</th>
              <th className="text-left px-4 py-3 font-medium text-muted-foreground">推送对象</th>
              <th className="text-left px-4 py-3 font-medium text-muted-foreground">标记</th>
              <th className="text-left px-4 py-3 font-medium text-muted-foreground">发布时间</th>
              <th className="text-left px-4 py-3 font-medium text-muted-foreground">过期时间</th>
              <th className="text-left px-4 py-3 font-medium text-muted-foreground">状态</th>
              <th className="text-right px-4 py-3 font-medium text-muted-foreground">操作</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {loading && items.length === 0 && (
              <tr>
                <td colSpan={9} className="text-center py-12 text-muted-foreground">加载中…</td>
              </tr>
            )}
            {!loading && items.length === 0 && (
              <tr>
                <td colSpan={9} className="text-center py-12 text-muted-foreground">暂无通知</td>
              </tr>
            )}
            {items.map((item) => (
              <tr key={item.id} className="hover:bg-muted/30 transition-colors">
                <td className="px-4 py-3 max-w-[12rem] truncate font-medium" title={item.title}>
                  {item.title}
                </td>
                <td className="px-4 py-3">{typeBadge(item.type)}</td>
                <td className="px-4 py-3 text-muted-foreground text-xs">{priorityLabel(item.priority)}</td>
                <td className="px-4 py-3 text-muted-foreground text-xs">{targetLabel(item)}</td>
                <td className="px-4 py-3">
                  <div className="flex flex-wrap gap-1">
                    {item.requiresForceRead && (
                      <span className="px-1.5 py-0.5 rounded text-[11px] bg-red-100 text-red-700 font-medium">
                        强制阅读
                      </span>
                    )}
                  </div>
                </td>
                <td className="px-4 py-3 text-xs text-muted-foreground">{formatDate(item.publishedAt)}</td>
                <td className="px-4 py-3 text-xs text-muted-foreground">{formatDate(item.expiresAt)}</td>
                <td className="px-4 py-3">
                  <span
                    className={cn(
                      'px-2 py-0.5 rounded text-xs font-medium',
                      item.isEnabled
                        ? 'bg-green-100 text-green-700'
                        : 'bg-gray-100 text-gray-500',
                    )}
                  >
                    {item.isEnabled ? '已启用' : '已禁用'}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <div className="flex items-center justify-end gap-1">
                    <button
                      onClick={() => handleToggle(item)}
                      title={item.isEnabled ? '禁用' : '启用'}
                      className="p-1.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
                    >
                      {item.isEnabled
                        ? <ToggleRight className="h-4 w-4 text-green-600" />
                        : <ToggleLeft className="h-4 w-4" />}
                    </button>
                    <button
                      onClick={() => setModal({ mode: 'edit', item })}
                      className="p-1.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
                    >
                      <Pencil className="h-4 w-4" />
                    </button>
                    <button
                      onClick={() => handleDelete(item.id)}
                      disabled={deleting === item.id}
                      className="p-1.5 rounded hover:bg-red-50 text-muted-foreground hover:text-red-600 transition-colors disabled:opacity-50"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* pagination */}
      {total > limit && (
        <div className="flex items-center justify-between mt-4 text-sm text-muted-foreground">
          <span>共 {total} 条</span>
          <div className="flex gap-2">
            <button
              disabled={offset === 0}
              onClick={() => setOffset(Math.max(0, offset - limit))}
              className="px-3 py-1.5 rounded border hover:bg-accent disabled:opacity-40 transition-colors"
            >
              上一页
            </button>
            <button
              disabled={offset + limit >= total}
              onClick={() => setOffset(offset + limit)}
              className="px-3 py-1.5 rounded border hover:bg-accent disabled:opacity-40 transition-colors"
            >
              下一页
            </button>
          </div>
        </div>
      )}

      {/* modal */}
      {modal && (
        <NotificationModal
          initial={
            (modal.mode === 'edit'
              ? { ...modal.item, id: modal.item.id }
              : {}) as Partial<CreateNotificationPayload> & { id?: string }
          }
          allTags={allTags}
          onSave={handleSave}
          onClose={() => setModal(null)}
        />
      )}
    </div>
  );
}
