import { useState, useEffect } from 'react';
import api from '../services/api';
import EmptyState from '../components/EmptyState';
import ConfirmDialog from '../components/ConfirmDialog';
import toast from 'react-hot-toast';
import { ClipboardList, CheckCircle, Clock, Calendar, Folder, MessageSquare, AtSign, Bell, AlertTriangle, Trash2 } from 'lucide-react';
import { formatJalaliDateTime } from '../utils/date';

export default function Notifications() {
  const [notifications, setNotifications] = useState([]);
  const [loading, setLoading] = useState(true);
  const [deleting, setDeleting] = useState(null);

  const fetchNotifications = () => {
    setLoading(true);
    api.get('/notifications').then(({ data }) => setNotifications(data.data || [])).catch(() => toast.error('خطا')).finally(() => setLoading(false));
  };

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

  const markAsRead = async (n) => {
    try {
      await api.post(`/notifications/${n.id}/read`);
      setNotifications(notifications.map(item => item.id === n.id ? { ...item, read_at: new Date().toISOString() } : item));
    } catch { toast.error('خطا'); }
  };

  const markAllAsRead = async () => {
    try {
      await api.post('/notifications/read-all');
      setNotifications(notifications.map(n => ({ ...n, read_at: n.read_at || new Date().toISOString() })));
      toast.success('همه اعلان‌ها خوانده شد');
    } catch { toast.error('خطا'); }
  };

  const handleDelete = async () => {
    try {
      await api.delete(`/notifications/${deleting.id}`);
      toast.success('حذف شد');
      setDeleting(null);
      fetchNotifications();
    } catch { toast.error('خطا'); }
  };

  const getIcon = (type) => {
    const icons = {
      task_assigned: ClipboardList,
      task_completed: CheckCircle,
      task_delayed: Clock,
      meeting_reminder: Calendar,
      project_update: Folder,
      comment_added: MessageSquare,
      mention: AtSign,
      system: Bell,
      warning: AlertTriangle,
    };
    return icons[type] || Bell;
  };

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

  return (
    <div className="page-container">
      <div className="page-header">
        {unreadCount > 0 && (
          <button className="btn btn-secondary btn-sm" onClick={markAllAsRead}>علامت‌گذاری همه به عنوان خوانده‌شده</button>
        )}
      </div>

      {loading ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
          {Array.from({ length: 5 }).map((_, i) => <div key={i} className="skeleton" style={{ height: 80, borderRadius: 'var(--radius)' }} />)}
        </div>
      ) : notifications.length === 0 ? (
        <EmptyState icon={Bell} title="اعلانی وجود ندارد" description="هنوز هیچ اعلانی دریافت نکرده‌اید" />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.625rem' }}>
          {notifications.map(n => (
            <div key={n.id} className="card" style={{
              padding: '1rem',
              cursor: 'pointer',
              borderRight: n.read_at ? 'none' : '4px solid var(--primary)',
              background: n.read_at ? 'var(--card-bg)' : 'var(--gray-50)',
            }} onClick={() => !n.read_at && markAsRead(n)}>
              <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'flex-start' }}>
                {(() => { const Icon = getIcon(n.type); return <Icon size={22} strokeWidth={1.5} style={{ flexShrink: 0 }} />; })()}
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div>
                      <div style={{ fontSize: '0.9375rem', fontWeight: n.read_at ? 400 : 600 }}>{n.title || n.message}</div>
                      {n.message && n.title && <div style={{ fontSize: '0.8125rem', color: 'var(--gray-500)', marginTop: '0.25rem' }}>{n.message}</div>}
                    </div>
                    <button className="btn btn-sm btn-danger" style={{ padding: '0.25rem', opacity: 0.6 }} onClick={e => { e.stopPropagation(); setDeleting(n); }}><Trash2 size={14} /></button>
                  </div>
                  <div style={{ fontSize: '0.75rem', color: 'var(--gray-400)', marginTop: '0.375rem' }}>
                    {formatJalaliDateTime(n.created_at, '')}
                    {n.read_at && <span style={{ marginRight: '0.5rem', color: 'var(--primary)' }}>• خوانده شده</span>}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {deleting && <ConfirmDialog title="حذف اعلان" message={`آیا از حذف این اعلان اطمینان دارید؟`} onConfirm={handleDelete} onCancel={() => setDeleting(null)} danger />}
    </div>
  );
}
