import React, { useState, useEffect } from 'react';
import { Button } from '../ui/button';
import { NotificationItem } from '../notifications/NotificationItem';
import { Notification } from '../../types';
import { Bell, Filter, Check, Trash2, Loader2 } from 'lucide-react';
import { useToast } from '../../context/ToastContext';
import { socialService } from '../../services/socialService';
import { logger } from '@/utils/logger';

export const NotificationsView: React.FC = () => {
  const { addToast } = useToast();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [filter, setFilter] = useState<'all' | 'unread' | 'mentions'>('all');
  const [loading, setLoading] = useState(true);

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

  const loadNotifications = async () => {
    try {
      setLoading(true);
      const res = await socialService.getNotifications();
      setNotifications(res.notifications);
    } catch (e) {
      logger.error('Error loading notifications', {
        error: e instanceof Error ? e.message : String(e),
        stack: e instanceof Error ? e.stack : undefined,
      });
    } finally {
      setLoading(false);
    }
  };

  const filtered = notifications.filter((n) => {
    if (filter === 'unread') return !n.read;
    if (filter === 'mentions')
      return n.type === 'mention' || n.type === 'like' || n.type === 'follow';
    return true;
  });

  const handleRead = async (id: string) => {
    // Optimistic update
    setNotifications(
      notifications.map((n) => (n.id === id ? { ...n, read: true } : n)),
    );
    // In real app, call service
    // await socialService.markRead(id);
  };

  const handleMarkAllRead = async () => {
    setNotifications(notifications.map((n) => ({ ...n, read: true })));
    await socialService.markAllRead();
    addToast('All notifications marked as read', 'success');
  };

  const handleClearAll = () => {
    setNotifications([]);
    addToast('Notifications cleared', 'info');
  };

  if (loading) {
    return (
      <div className="flex h-[50vh] items-center justify-center">
        <Loader2 className="w-8 h-8 text-kodo-cyan animate-spin" />
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6 animate-fadeIn pb-20">
      <div className="flex flex-col md:flex-row justify-between items-end border-b border-kodo-steel/50 pb-6 gap-4">
        <div>
          <h1 className="text-3xl font-display font-bold text-white mb-2">
            NOTIFICATIONS
          </h1>
          <p className="text-gray-400 font-mono text-sm">
            Stay updated with your network activity.
          </p>
        </div>
        <div className="flex gap-2">
          <Button
            variant="ghost"
            icon={<Check className="w-4 h-4" />}
            onClick={handleMarkAllRead}
          >
            Mark all read
          </Button>
          <Button
            variant="ghost"
            className="text-kodo-red hover:bg-kodo-red/10"
            icon={<Trash2 className="w-4 h-4" />}
            onClick={handleClearAll}
          >
            Clear
          </Button>
        </div>
      </div>

      <div className="flex gap-4 items-center bg-kodo-ink/50 p-2 rounded-xl border border-kodo-steel/50">
        <div className="flex bg-kodo-void rounded-lg p-1 border border-kodo-steel">
          {['all', 'unread', 'mentions'].map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f as any)}
              className={`px-4 py-2 rounded text-sm font-bold capitalize transition-colors ${filter === f ? 'bg-kodo-slate text-white' : 'text-gray-400 hover:text-white'}`}
            >
              {f}
            </button>
          ))}
        </div>
        <div className="h-6 w-px bg-kodo-steel/50 hidden md:block"></div>
        <div className="flex items-center gap-2 text-xs text-gray-500">
          <Filter className="w-3 h-3" />
          <span>Showing {filtered.length} notifications</span>
        </div>
      </div>

      <div className="space-y-2">
        {filtered.length === 0 ? (
          <div className="text-center py-20 border-2 border-dashed border-kodo-steel rounded-xl text-gray-500">
            <Bell className="w-12 h-12 mx-auto mb-4 opacity-50" />
            <p>No notifications to display.</p>
          </div>
        ) : (
          filtered.map((n) => (
            <NotificationItem
              key={n.id}
              notification={n}
              onRead={handleRead}
              onAction={(notif) =>
                addToast(`Action triggered for ${notif.type}`)
              }
            />
          ))
        )}
      </div>
    </div>
  );
};
