import { useEffect, useState } from 'react';
import { Bell, CheckCheck } from 'lucide-react';
import { api, fmt } from '../api';
import { Card, Badge, Btn, Spinner, EmptyState, ErrorBox } from '../components/ui';

const TYPE_COLORS = {
  info: 'blue', warning: 'yellow', error: 'red', success: 'green',
  advice: 'purple', reminder: 'accent', system: 'muted'
};

export default function Notifications() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [marking, setMarking] = useState(false);

  const load = () => {
    setError(null);
    api.get('/notifications').then(setData).catch(setError);
  };
  useEffect(load, []);

  const markAll = async () => {
    setMarking(true);
    try {
      await api.post('/notifications/read-all');
      load();
    } catch (e) {
      alert(e.message);
    } finally {
      setMarking(false);
    }
  };

  const markOne = async (n) => {
    if (n.read) return;
    try {
      await api.post(`/notifications/${n.id}/read`);
      load();
    } catch (e) {
      alert(e.message);
    }
  };

  if (error) return <ErrorBox error={error} onRetry={load} />;
  if (!data) return <Spinner />;

  const { notifications, unread } = data;

  return (
    <div className="space-y-5 fade-in">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold tracking-tight">Notificaties</h1>
          <p className="text-[13px] text-muted mt-0.5">
            {unread > 0 ? `${unread} ongelezen` : 'Alles gelezen'}
          </p>
        </div>
        {unread > 0 && (
          <Btn variant="secondary" onClick={markAll} loading={marking}>
            <CheckCheck className="w-4 h-4" /> Alles als gelezen markeren
          </Btn>
        )}
      </div>

      {notifications.length === 0 ? (
        <Card>
          <EmptyState icon={Bell} title="Geen notificaties" hint="Je bent helemaal bij." />
        </Card>
      ) : (
        <div className="space-y-2">
          {notifications.map(n => (
            <div
              key={n.id}
              onClick={() => markOne(n)}
              className={`bg-card border border-border-soft rounded-xl px-4 py-3 transition-colors ${
                n.read ? '' : 'border-l-2 border-l-accent cursor-pointer hover:bg-card-hover'
              }`}
            >
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0">
                  <div className={`text-[13px] ${n.read ? '' : 'font-medium'}`}>{n.title}</div>
                  {n.message && <div className="text-[12px] text-muted mt-0.5">{n.message}</div>}
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  {n.type && <Badge color={TYPE_COLORS[n.type] || 'muted'}>{n.type}</Badge>}
                  <span className="text-[11px] text-muted whitespace-nowrap">{fmt.datetime(n.created_at)}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
