'use client';

import { useState, useEffect } from 'react';
import { notificationApi } from '@/lib/api';
import { Notification } from '@/types';
import { formatDate } from '@/lib/utils';
import { motion } from 'framer-motion';
import { Bell, CheckCheck, Loader2 } from 'lucide-react';
import toast from 'react-hot-toast';

const typeIcons: Record<string, string> = {
  approval: '🔄',
  success: '✅',
  error: '❌',
  warning: '⚠️',
  mention: '@',
  info: 'ℹ️',
};

export default function NotificationsPage() {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);

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

  const load = async () => {
    try {
      const { data } = await notificationApi.getAll();
      setNotifications(data);
    } catch {} finally {
      setLoading(false);
    }
  };

  const markRead = async (id: string) => {
    try {
      await notificationApi.markAsRead(id);
      setNotifications(prev => prev.map(n => n.id === id ? { ...n, isRead: true } : n));
    } catch {}
  };

  const markAllRead = async () => {
    try {
      await notificationApi.markAllAsRead();
      setNotifications(prev => prev.map(n => ({ ...n, isRead: true })));
      toast.success('All notifications marked as read');
    } catch {}
  };

  const unreadCount = notifications.filter(n => !n.isRead).length;

  if (loading) {
    return (
      <div className="h-full flex items-center justify-center">
        <Loader2 className="w-6 h-6 text-primary-500 animate-spin" />
      </div>
    );
  }

  return (
    <div className="h-full flex flex-col p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-3">
            <Bell className="w-6 h-6" />
            Notifications
            {unreadCount > 0 && (
              <span className="bg-primary-500 text-white text-xs font-medium px-2 py-0.5 rounded-full">
                {unreadCount} new
              </span>
            )}
          </h1>
        </div>
        {unreadCount > 0 && (
          <button onClick={markAllRead} className="btn-secondary text-xs flex items-center gap-1.5">
            <CheckCheck className="w-3.5 h-3.5" /> Mark all read
          </button>
        )}
      </div>

      <div className="flex-1 overflow-y-auto scrollbar-thin space-y-2">
        {notifications.length === 0 ? (
          <div className="text-center py-20">
            <Bell className="w-12 h-12 text-vault-muted mx-auto mb-3 opacity-30" />
            <p className="text-vault-muted">No notifications yet</p>
          </div>
        ) : (
          notifications.map((notif) => (
            <motion.div
              key={notif.id}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              onClick={() => !notif.isRead && markRead(notif.id)}
              className={`glass-card p-4 cursor-pointer transition-all hover:border-primary-500/20 ${
                !notif.isRead ? 'border-primary-500/30 bg-primary-500/5' : ''
              }`}
            >
              <div className="flex items-start gap-3">
                <span className="text-lg">{typeIcons[notif.type] || 'ℹ️'}</span>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-0.5">
                    <p className="text-sm font-medium">{notif.title}</p>
                    {!notif.isRead && (
                      <span className="w-2 h-2 bg-primary-500 rounded-full" />
                    )}
                  </div>
                  <p className="text-sm text-vault-muted">{notif.message}</p>
                  <p className="text-[10px] text-vault-muted/50 mt-1">{formatDate(notif.createdAt)}</p>
                </div>
              </div>
            </motion.div>
          ))
        )}
      </div>
    </div>
  );
}
