// ===================================================================
// ADMIN NOTIFICATION MANAGEMENT PAGE
// Enterprise FinTech Platform
// ===================================================================

'use client';

import { useState } from 'react';
import {
  Bell,
  Send,
  Trash2,
  Filter,
  Search,
  ChevronLeft,
  ChevronRight,
  Megaphone,
  Eye,
  Clock,
  Users,
  CheckCircle2,
  XCircle,
  AlertTriangle,
} from 'lucide-react';
import { notificationService } from '@/services/notification.service';
import type {
  Notification,
  NotificationLog,
  NotificationType,
  NotificationPriority,
  BroadcastNotificationPayload,
} from '@/types/notification.types';
import { NOTIFICATION_TYPE_LABELS } from '@/types/notification.types';

const NOTIFICATION_TYPES = Object.entries(NOTIFICATION_TYPE_LABELS).map(
  ([value, label]) => ({ value: value as NotificationType, label }),
);

export default function AdminNotificationsPage() {
  const [activeTab, setActiveTab] = useState<
    'broadcast' | 'logs' | 'templates'
  >('broadcast');
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [logs, setLogs] = useState<NotificationLog[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  // Broadcast form
  const [broadcastForm, setBroadcastForm] =
    useState<BroadcastNotificationPayload>({
      type: 'SYSTEM',
      title: '',
      body: '',
      priority: 'NORMAL',
      target: {},
    });
  const [broadcasting, setBroadcasting] = useState(false);
  const [broadcastResult, setBroadcastResult] = useState<{
    success: boolean;
    message: string;
  } | null>(null);

  const handleBroadcast = async () => {
    if (!broadcastForm.title || !broadcastForm.body) return;
    setBroadcasting(true);
    setBroadcastResult(null);
    try {
      const result = await notificationService.broadcast(broadcastForm);
      setBroadcastResult({
        success: true,
        message: `Broadcast sent to ${result.totalTargeted} users (${result.successCount} succeeded, ${result.failCount} failed)`,
      });
      setBroadcastForm({
        type: 'SYSTEM',
        title: '',
        body: '',
        priority: 'NORMAL',
        target: {},
      });
    } catch (error: any) {
      setBroadcastResult({
        success: false,
        message: error?.response?.data?.message ?? 'Failed to send broadcast',
      });
    } finally {
      setBroadcasting(false);
    }
  };

  const fetchLogs = async (p = 1) => {
    setLoading(true);
    try {
      const result = await notificationService.getLogs(p, 20);
      setLogs(result.data);
      setTotalPages(result.meta?.totalPages ?? 1);
    } catch (error) {
      console.error('Failed to fetch logs:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteNotification = async (id: string) => {
    try {
      await notificationService.adminDelete(id);
      setNotifications((prev) => prev.filter((n) => n.id !== id));
    } catch (error) {
      console.error('Failed to delete notification:', error);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-slate-100">
          Notification Management
        </h1>
        <p className="mt-1 text-sm text-slate-400">
          Broadcast notifications, view logs, and manage templates
        </p>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 rounded-xl border border-white/10 bg-slate-900/50 p-1">
        {[
          { id: 'broadcast', label: 'Broadcast', icon: Send },
          { id: 'logs', label: 'Notification Logs', icon: Clock },
          { id: 'templates', label: 'Templates', icon: Megaphone },
        ].map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id as any)}
            className={`flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors ${
              activeTab === tab.id
                ? 'bg-cyan-500/10 text-cyan-400'
                : 'text-slate-400 hover:text-slate-200'
            }`}
          >
            <tab.icon className="h-4 w-4" />
            {tab.label}
          </button>
        ))}
      </div>

      {/* Broadcast Tab */}
      {activeTab === 'broadcast' && (
        <div className="rounded-xl border border-white/10 bg-slate-900/50 p-6">
          <h2 className="text-lg font-semibold text-slate-100">
            Send Broadcast
          </h2>
          <p className="mt-1 text-sm text-slate-400">
            Send a notification to all users or a specific group
          </p>

          <div className="mt-6 space-y-4">
            {/* Type & Priority */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="mb-1 block text-xs font-medium text-slate-400">
                  Type
                </label>
                <select
                  value={broadcastForm.type}
                  onChange={(e) =>
                    setBroadcastForm((prev) => ({
                      ...prev,
                      type: e.target.value as NotificationType,
                    }))
                  }
                  className="w-full rounded-lg border border-white/10 bg-slate-800 px-3 py-2 text-sm text-slate-200 outline-none focus:border-cyan-500"
                >
                  {NOTIFICATION_TYPES.map((t) => (
                    <option key={t.value} value={t.value}>
                      {t.label}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="mb-1 block text-xs font-medium text-slate-400">
                  Priority
                </label>
                <select
                  value={broadcastForm.priority}
                  onChange={(e) =>
                    setBroadcastForm((prev) => ({
                      ...prev,
                      priority: e.target.value as NotificationPriority,
                    }))
                  }
                  className="w-full rounded-lg border border-white/10 bg-slate-800 px-3 py-2 text-sm text-slate-200 outline-none focus:border-cyan-500"
                >
                  {['LOW', 'NORMAL', 'HIGH', 'URGENT'].map((p) => (
                    <option key={p} value={p}>
                      {p}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Title */}
            <div>
              <label className="mb-1 block text-xs font-medium text-slate-400">
                Title
              </label>
              <input
                type="text"
                value={broadcastForm.title}
                onChange={(e) =>
                  setBroadcastForm((prev) => ({
                    ...prev,
                    title: e.target.value,
                  }))
                }
                placeholder="Notification title"
                className="w-full rounded-lg border border-white/10 bg-slate-800 px-3 py-2 text-sm text-slate-200 outline-none placeholder:text-slate-500 focus:border-cyan-500"
              />
            </div>

            {/* Body */}
            <div>
              <label className="mb-1 block text-xs font-medium text-slate-400">
                Body
              </label>
              <textarea
                value={broadcastForm.body}
                onChange={(e) =>
                  setBroadcastForm((prev) => ({
                    ...prev,
                    body: e.target.value,
                  }))
                }
                placeholder="Notification message"
                rows={4}
                className="w-full rounded-lg border border-white/10 bg-slate-800 px-3 py-2 text-sm text-slate-200 outline-none placeholder:text-slate-500 focus:border-cyan-500 resize-none"
              />
            </div>

            {/* Target */}
            <div>
              <label className="mb-1 block text-xs font-medium text-slate-400">
                Target
              </label>
              <select
                value={broadcastForm.target?.role ?? 'all'}
                onChange={(e) =>
                  setBroadcastForm((prev) => ({
                    ...prev,
                    target: { role: e.target.value === 'all' ? undefined : e.target.value },
                  }))
                }
                className="w-full rounded-lg border border-white/10 bg-slate-800 px-3 py-2 text-sm text-slate-200 outline-none focus:border-cyan-500"
              >
                <option value="all">All Users</option>
                <option value="USER">Users Only</option>
                <option value="ADMIN">Admins Only</option>
                <option value="SUPER_ADMIN">Super Admins Only</option>
                <option value="VERIFIED_USERS">Verified Users</option>
              </select>
            </div>

            {/* Result */}
            {broadcastResult && (
              <div
                className={`flex items-center gap-2 rounded-lg p-3 text-sm ${
                  broadcastResult.success
                    ? 'bg-green-500/10 text-green-400'
                    : 'bg-red-500/10 text-red-400'
                }`}
              >
                {broadcastResult.success ? (
                  <CheckCircle2 className="h-4 w-4" />
                ) : (
                  <XCircle className="h-4 w-4" />
                )}
                {broadcastResult.message}
              </div>
            )}

            {/* Submit */}
            <button
              onClick={handleBroadcast}
              disabled={broadcasting || !broadcastForm.title || !broadcastForm.body}
              className="flex items-center gap-2 rounded-lg bg-cyan-500 px-4 py-2 text-sm font-medium text-white hover:bg-cyan-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {broadcasting ? (
                <div className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
              ) : (
                <Send className="h-4 w-4" />
              )}
              Send Broadcast
            </button>
          </div>
        </div>
      )}

      {/* Logs Tab */}
      {activeTab === 'logs' && (
        <div className="rounded-xl border border-white/10 bg-slate-900/50">
          <div className="border-b border-white/10 px-6 py-4">
            <h2 className="text-lg font-semibold text-slate-100">
              Notification Logs
            </h2>
          </div>
          {logs.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-20">
              <Clock className="mb-4 h-12 w-12 text-slate-600" />
              <p className="text-sm text-slate-400">
                No notification logs yet
              </p>
              <button
                onClick={() => fetchLogs()}
                className="mt-4 text-sm text-cyan-400 hover:text-cyan-300"
              >
                Load logs
              </button>
            </div>
          ) : (
            <div className="divide-y divide-white/5">
              {logs.map((log) => (
                <div
                  key={log.id}
                  className="flex items-start gap-4 px-6 py-4"
                >
                  <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-white/5 text-slate-500">
                    <Clock className="h-4 w-4" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-slate-200">
                        {log.action}
                      </span>
                      <span className="text-xs text-slate-500">
                        {log.channel}
                      </span>
                    </div>
                    <p className="mt-0.5 text-xs text-slate-400">
                      User: {log.user?.email ?? log.userId}
                    </p>
                    <p className="mt-1 text-xs text-slate-500">
                      {new Date(log.createdAt).toLocaleString()}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          )}
          {totalPages > 1 && (
            <div className="flex items-center justify-between border-t border-white/10 px-6 py-3">
              <button
                onClick={() => {
                  setPage((p) => Math.max(1, p - 1));
                  fetchLogs(page - 1);
                }}
                disabled={page <= 1}
                className="flex items-center gap-1 text-sm text-slate-400 hover:text-slate-200 disabled:opacity-50"
              >
                <ChevronLeft className="h-4 w-4" />
                Previous
              </button>
              <span className="text-sm text-slate-500">
                Page {page} of {totalPages}
              </span>
              <button
                onClick={() => {
                  setPage((p) => p + 1);
                  fetchLogs(page + 1);
                }}
                disabled={page >= totalPages}
                className="flex items-center gap-1 text-sm text-slate-400 hover:text-slate-200 disabled:opacity-50"
              >
                Next
                <ChevronRight className="h-4 w-4" />
              </button>
            </div>
          )}
        </div>
      )}

      {/* Templates Tab */}
      {activeTab === 'templates' && (
        <div className="rounded-xl border border-white/10 bg-slate-900/50 p-6">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-lg font-semibold text-slate-100">
                Notification Templates
              </h2>
              <p className="mt-1 text-sm text-slate-400">
                Manage reusable notification templates
              </p>
            </div>
            <button className="flex items-center gap-2 rounded-lg bg-cyan-500 px-4 py-2 text-sm font-medium text-white hover:bg-cyan-400 transition-colors">
              <Megaphone className="h-4 w-4" />
              Create Template
            </button>
          </div>
          <p className="mt-6 text-center text-sm text-slate-500">
            Template management will be available in the next update. Use the
            API endpoints to manage templates.
          </p>
        </div>
      )}
    </div>
  );
}
