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, MessageSquare, Heart, UserPlus } from 'lucide-react';
import { useToast } from '../../components/feedback/ToastProvider';
import { socialService } from '../../services/socialService';
import { logger } from '@/utils/logger';
import { Card } from '../ui/card';
import { cn } from '@/lib/utils';

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 });
    } 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) => {
    setNotifications(notifications.map((n) => (n.id === id ? { ...n, read: true } : n)));
    // 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-primary animate-spin" /></div>;

  return (
    <div className="max-w-4xl mx-auto space-y-6 pb-20 container px-4 py-8">
      <div className="flex flex-col md:flex-row justify-between items-end gap-4 mb-2">
        <div>
          <h1 className="text-3xl font-display font-bold text-white mb-1">Notifications</h1>
          <p className="text-muted-foreground font-mono text-xs">NETWORK ACTIVITY</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={handleMarkAllRead} className="border-primary/20 hover:bg-primary/10 text-primary">
            <Check className="w-4 h-4 mr-2" /> Mark all read
          </Button>
          <Button variant="outline" size="sm" onClick={handleClearAll} className="border-red-500/20 hover:bg-red-500/10 text-red-500">
            <Trash2 className="w-4 h-4 mr-2" /> Clear
          </Button>
        </div>
      </div>

      <Card variant="glass" className="p-2 flex items-center justify-between border-white/5 bg-black/40">
        <div className="flex gap-1">
          {['all', 'unread', 'mentions'].map((f) => (
            <Button
              key={f}
              variant={filter === f ? 'default' : 'ghost'}
              size="sm"
              onClick={() => setFilter(f as any)}
              className="capitalize"
            >
              {f}
            </Button>
          ))}
        </div>
        <div className="flex items-center gap-2 text-xs text-muted-foreground px-2">
          <Filter className="w-3 h-3" /> {filtered.length} items
        </div>
      </Card>

      <div className="space-y-2">
        {filtered.length === 0 ? (
          <div className="text-center py-24 rounded-2xl border border-dashed border-white/10 text-muted-foreground bg-black/20">
            <Bell className="w-12 h-12 mx-auto mb-4 opacity-20" />
            <p>No new signals detected.</p>
          </div>
        ) : (
          filtered.map((n) => (
            <Card key={n.id} variant="glass" className={cn("p-4 flex gap-4 transition-all hover:bg-white/5", !n.read && "border-l-2 border-l-primary bg-primary/5")}>
              <div className={cn("p-2 rounded-full h-fit",
                n.type === 'like' ? 'bg-red-500/10 text-red-500' :
                  n.type === 'follow' ? 'bg-lime-500/10 text-lime-500' :
                    'bg-cyan-500/10 text-cyan-500')}>
                {n.type === 'like' && <Heart className="w-4 h-4" />}
                {n.type === 'follow' && <UserPlus className="w-4 h-4" />}
                {n.type === 'mention' && <MessageSquare className="w-4 h-4" />}
              </div>
              <div className="flex-1">
                <p className="text-sm text-white mb-1">{n.message}</p>
                <p className="text-xs text-muted-foreground">{new Date(n.timestamp).toLocaleString()}</p>
              </div>
              {!n.read && (
                <Button variant="ghost" size="sm" className="h-8 w-8 p-0 rounded-full hover:bg-primary/20 text-primary" onClick={() => handleRead(n.id)}>
                  <Check className="w-4 h-4" />
                </Button>
              )}
            </Card>
          ))
        )}
      </div>
    </div>
  );
};
