/**
 * 通知管理页面
 *
 * 功能：
 * - 通知列表：展示所有通知，支持按类型筛选 + 分页
 * - 新建/编辑通知：Dialog 表单，支持标题、内容、类型、优先级、
 *   目标类型（全部/指定用户）、图片URL、链接URL、强制弹窗、发布/过期时间
 * - 删除通知：确认对话框
 *
 * 数据流：
 * notificationsApi (axios) → useNotifications (react-query) → 本页面渲染
 */
'use client';

import { useState } from 'react';
import { PageHeader } from '@/components/layout/page-header';
import {
  useNotifications,
  useCreateNotification,
  useUpdateNotification,
  useDeleteNotification,
} from '@/features/notifications/hooks/use-notifications';
import type {
  NotificationItem,
  NotificationType,
  NotificationPriority,
  TargetType,
  CreateNotificationDto,
} from '@/features/notifications/api/notifications.api';
import { Card, CardContent } from '@/components/ui/card';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { ChevronLeft, ChevronRight, Plus, Pencil, Trash2 } from 'lucide-react';
import { formatDateTime } from '@/lib/utils/date';

// ==================== 常量映射 ====================

/** 通知类型标签与样式 */
const typeLabels: Record<NotificationType, { label: string; className: string }> = {
  SYSTEM: { label: '系统', className: 'bg-blue-100 text-blue-700' },
  ACTIVITY: { label: '活动', className: 'bg-green-100 text-green-700' },
  REWARD: { label: '收益', className: 'bg-yellow-100 text-yellow-700' },
  UPGRADE: { label: '升级', className: 'bg-purple-100 text-purple-700' },
  ANNOUNCEMENT: { label: '公告', className: 'bg-orange-100 text-orange-700' },
};

/** 优先级标签与样式 */
const priorityLabels: Record<NotificationPriority, { label: string; className: string }> = {
  LOW: { label: '低', className: 'bg-gray-100 text-gray-600' },
  NORMAL: { label: '普通', className: 'bg-blue-100 text-blue-600' },
  HIGH: { label: '高', className: 'bg-orange-100 text-orange-700' },
  URGENT: { label: '紧急', className: 'bg-red-100 text-red-700' },
};

/** 目标类型标签 */
const targetLabels: Record<TargetType, string> = {
  ALL: '全部用户',
  SPECIFIC: '指定用户',
};

// ==================== 表单初始值 ====================

const emptyForm: CreateNotificationDto = {
  title: '',
  content: '',
  type: 'SYSTEM',
  priority: 'NORMAL',
  targetType: 'ALL',
  targetAccountSequences: [],
  imageUrl: '',
  linkUrl: '',
  isEnabled: true,
  requiresForceRead: false,
  publishedAt: '',
  expiresAt: '',
};

// ==================== 主页面组件 ====================

export default function NotificationsPage() {
  // ---- 列表状态 ----
  const [filterType, setFilterType] = useState<string>('ALL');
  const [page, setPage] = useState(0);
  const pageSize = 20;

  // ---- 查询通知列表 ----
  const { data, isLoading } = useNotifications({
    type: filterType === 'ALL' ? undefined : (filterType as NotificationType),
    limit: pageSize,
    offset: page * pageSize,
  });

  // ---- CRUD mutations ----
  const createMutation = useCreateNotification();
  const updateMutation = useUpdateNotification();
  const deleteMutation = useDeleteNotification();

  // ---- 编辑 Dialog 状态 ----
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<CreateNotificationDto>({ ...emptyForm });
  /** 指定用户的文本输入（逗号/换行分隔） */
  const [targetUsersText, setTargetUsersText] = useState('');

  // ---- 删除确认 Dialog 状态 ----
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  // ---- 打开新建 Dialog ----
  const handleCreate = () => {
    setEditingId(null);
    setForm({ ...emptyForm });
    setTargetUsersText('');
    setDialogOpen(true);
  };

  // ---- 打开编辑 Dialog ----
  const handleEdit = (item: NotificationItem) => {
    setEditingId(item.id);
    setForm({
      title: item.title,
      content: item.content,
      type: item.type,
      priority: item.priority,
      targetType: item.targetType,
      targetAccountSequences: item.targetConfig?.accountSequences || [],
      imageUrl: item.imageUrl || '',
      linkUrl: item.linkUrl || '',
      isEnabled: item.isEnabled,
      requiresForceRead: item.requiresForceRead,
      publishedAt: item.publishedAt ? item.publishedAt.slice(0, 16) : '', // datetime-local 格式
      expiresAt: item.expiresAt ? item.expiresAt.slice(0, 16) : '',
    });
    setTargetUsersText(
      item.targetConfig?.accountSequences?.join('\n') || ''
    );
    setDialogOpen(true);
  };

  // ---- 提交表单（创建 or 更新） ----
  const handleSubmit = () => {
    // 解析指定用户文本 → 账号数组（去空行去空格）
    const targetAccountSequences =
      form.targetType === 'SPECIFIC'
        ? targetUsersText
            .split(/[,\n]/)
            .map((s) => s.trim())
            .filter(Boolean)
        : [];

    const payload: CreateNotificationDto = {
      ...form,
      targetAccountSequences,
      // 空字符串转 undefined，避免后端报错
      imageUrl: form.imageUrl || undefined,
      linkUrl: form.linkUrl || undefined,
      publishedAt: form.publishedAt ? new Date(form.publishedAt).toISOString() : undefined,
      expiresAt: form.expiresAt ? new Date(form.expiresAt).toISOString() : undefined,
    };

    if (editingId) {
      updateMutation.mutate(
        { id: editingId, dto: payload },
        { onSuccess: () => setDialogOpen(false) }
      );
    } else {
      createMutation.mutate(payload, {
        onSuccess: () => setDialogOpen(false),
      });
    }
  };

  // ---- 删除确认 ----
  const handleDelete = (id: string) => {
    setDeletingId(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    if (deletingId) {
      deleteMutation.mutate(deletingId, {
        onSuccess: () => setDeleteDialogOpen(false),
      });
    }
  };

  // ---- 渲染 Badge ----
  const renderBadge = (text: string, className: string) => (
    <span className={`inline-flex items-center px-2 py-1 rounded text-xs font-medium ${className}`}>
      {text}
    </span>
  );

  // ---- 骨架行 ----
  const renderSkeletonRows = () =>
    [...Array(5)].map((_, i) => (
      <TableRow key={i}>
        {[...Array(8)].map((_, j) => (
          <TableCell key={j}><Skeleton className="h-4 w-full" /></TableCell>
        ))}
      </TableRow>
    ));

  // ---- 分页计算 ----
  const total = data?.total || 0;
  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className="space-y-6">
      {/* 页头 + 新建按钮 */}
      <PageHeader
        title="通知管理"
        description="管理系统通知，支持全部推送和指定用户推送"
        actions={
          <Button onClick={handleCreate}>
            <Plus className="h-4 w-4 mr-2" />
            新建通知
          </Button>
        }
      />

      {/* 类型筛选 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex gap-3">
            <Select value={filterType} onValueChange={(v) => { setFilterType(v); setPage(0); }}>
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="通知类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部类型</SelectItem>
                <SelectItem value="SYSTEM">系统</SelectItem>
                <SelectItem value="ACTIVITY">活动</SelectItem>
                <SelectItem value="REWARD">收益</SelectItem>
                <SelectItem value="UPGRADE">升级</SelectItem>
                <SelectItem value="ANNOUNCEMENT">公告</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* 通知列表表格 */}
      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>标题</TableHead>
                <TableHead>类型</TableHead>
                <TableHead>优先级</TableHead>
                <TableHead>目标</TableHead>
                <TableHead>强制弹窗</TableHead>
                <TableHead>启用</TableHead>
                <TableHead>发布时间</TableHead>
                <TableHead className="text-right">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                renderSkeletonRows()
              ) : !data?.items?.length ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                    暂无通知
                  </TableCell>
                </TableRow>
              ) : (
                data.items.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell className="max-w-[200px] truncate font-medium">
                      {item.title}
                    </TableCell>
                    <TableCell>
                      {renderBadge(
                        typeLabels[item.type]?.label || item.type,
                        typeLabels[item.type]?.className || ''
                      )}
                    </TableCell>
                    <TableCell>
                      {renderBadge(
                        priorityLabels[item.priority]?.label || item.priority,
                        priorityLabels[item.priority]?.className || ''
                      )}
                    </TableCell>
                    <TableCell>
                      {renderBadge(
                        targetLabels[item.targetType] || item.targetType,
                        item.targetType === 'ALL'
                          ? 'bg-green-100 text-green-700'
                          : 'bg-yellow-100 text-yellow-700'
                      )}
                    </TableCell>
                    <TableCell>
                      {item.requiresForceRead ? (
                        <span className="text-red-600 font-medium">是</span>
                      ) : (
                        <span className="text-muted-foreground">否</span>
                      )}
                    </TableCell>
                    <TableCell>
                      {item.isEnabled ? (
                        <span className="text-green-600 font-medium">启用</span>
                      ) : (
                        <span className="text-muted-foreground">禁用</span>
                      )}
                    </TableCell>
                    <TableCell>{formatDateTime(item.publishedAt)}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8"
                          onClick={() => handleEdit(item)}
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-destructive"
                          onClick={() => handleDelete(item.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>

          {/* 分页 */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between p-4 border-t">
              <p className="text-sm text-muted-foreground">
                共 {total} 条，第 {page + 1} / {totalPages} 页
              </p>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPage(page - 1)}
                  disabled={page <= 0}
                >
                  <ChevronLeft className="h-4 w-4" />
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPage(page + 1)}
                  disabled={page + 1 >= totalPages}
                >
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* ==================== 新建/编辑 Dialog ==================== */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingId ? '编辑通知' : '新建通知'}</DialogTitle>
            <DialogDescription>
              {editingId ? '修改通知内容，保存后立即生效' : '创建新的系统通知，可推送给全部或指定用户'}
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-4 py-4">
            {/* 标题 */}
            <div className="grid gap-2">
              <Label htmlFor="title">标题 *</Label>
              <Input
                id="title"
                value={form.title}
                onChange={(e) => setForm({ ...form, title: e.target.value })}
                placeholder="输入通知标题"
              />
            </div>

            {/* 内容 */}
            <div className="grid gap-2">
              <Label htmlFor="content">内容 *</Label>
              <Textarea
                id="content"
                value={form.content}
                onChange={(e) => setForm({ ...form, content: e.target.value })}
                placeholder="输入通知内容"
                rows={4}
              />
            </div>

            {/* 类型 + 优先级（同行） */}
            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label>类型</Label>
                <Select
                  value={form.type}
                  onValueChange={(v) => setForm({ ...form, type: v as NotificationType })}
                >
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="SYSTEM">系统</SelectItem>
                    <SelectItem value="ACTIVITY">活动</SelectItem>
                    <SelectItem value="REWARD">收益</SelectItem>
                    <SelectItem value="UPGRADE">升级</SelectItem>
                    <SelectItem value="ANNOUNCEMENT">公告</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2">
                <Label>优先级</Label>
                <Select
                  value={form.priority}
                  onValueChange={(v) => setForm({ ...form, priority: v as NotificationPriority })}
                >
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="LOW">低</SelectItem>
                    <SelectItem value="NORMAL">普通</SelectItem>
                    <SelectItem value="HIGH">高</SelectItem>
                    <SelectItem value="URGENT">紧急</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 目标类型 */}
            <div className="grid gap-2">
              <Label>推送目标</Label>
              <Select
                value={form.targetType}
                onValueChange={(v) => setForm({ ...form, targetType: v as TargetType })}
              >
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="ALL">全部用户</SelectItem>
                  <SelectItem value="SPECIFIC">指定用户</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 指定用户输入（targetType=SPECIFIC 时显示） */}
            {form.targetType === 'SPECIFIC' && (
              <div className="grid gap-2">
                <Label htmlFor="targetUsers">指定用户账号（每行一个或逗号分隔）</Label>
                <Textarea
                  id="targetUsers"
                  value={targetUsersText}
                  onChange={(e) => setTargetUsersText(e.target.value)}
                  placeholder="D25121400001&#10;D25121400002"
                  rows={3}
                />
              </div>
            )}

            {/* 图片URL + 链接URL */}
            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="imageUrl">图片 URL（可选）</Label>
                <Input
                  id="imageUrl"
                  value={form.imageUrl || ''}
                  onChange={(e) => setForm({ ...form, imageUrl: e.target.value })}
                  placeholder="https://..."
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="linkUrl">链接 URL（可选）</Label>
                <Input
                  id="linkUrl"
                  value={form.linkUrl || ''}
                  onChange={(e) => setForm({ ...form, linkUrl: e.target.value })}
                  placeholder="https://..."
                />
              </div>
            </div>

            {/* 发布时间 + 过期时间 */}
            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="publishedAt">发布时间（可选，不填则立即发布）</Label>
                <Input
                  id="publishedAt"
                  type="datetime-local"
                  value={form.publishedAt || ''}
                  onChange={(e) => setForm({ ...form, publishedAt: e.target.value })}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="expiresAt">过期时间（可选）</Label>
                <Input
                  id="expiresAt"
                  type="datetime-local"
                  value={form.expiresAt || ''}
                  onChange={(e) => setForm({ ...form, expiresAt: e.target.value })}
                />
              </div>
            </div>

            {/* 复选框：强制弹窗 + 启用 */}
            <div className="flex items-center gap-6">
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id="requiresForceRead"
                  checked={form.requiresForceRead}
                  onChange={(e) =>
                    setForm({ ...form, requiresForceRead: e.target.checked })
                  }
                  className="h-4 w-4 rounded border-gray-300"
                />
                <Label htmlFor="requiresForceRead" className="text-sm">
                  强制弹窗阅读（用户打开APP时必须查看）
                </Label>
              </div>
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id="isEnabled"
                  checked={form.isEnabled}
                  onChange={(e) =>
                    setForm({ ...form, isEnabled: e.target.checked })
                  }
                  className="h-4 w-4 rounded border-gray-300"
                />
                <Label htmlFor="isEnabled" className="text-sm">启用</Label>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>
              取消
            </Button>
            <Button
              onClick={handleSubmit}
              disabled={
                !form.title?.trim() ||
                !form.content?.trim() ||
                createMutation.isPending ||
                updateMutation.isPending
              }
            >
              {createMutation.isPending || updateMutation.isPending ? '提交中...' : '保存'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ==================== 删除确认 Dialog ==================== */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              删除后无法恢复，确定要删除这条通知吗？
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
              取消
            </Button>
            <Button
              variant="destructive"
              onClick={confirmDelete}
              disabled={deleteMutation.isPending}
            >
              {deleteMutation.isPending ? '删除中...' : '确认删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
