'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { formatDistanceToNow, parseISO } from 'date-fns';
import { tr } from 'date-fns/locale';
import {
  Bell,
  BellOff,
  Check,
  CheckCheck,
  Loader2,
  AlertCircle,
  Info,
  Megaphone,
  Sparkles,
} from 'lucide-react';
import { apiFetchJson } from '@/lib/auth';

// ─── Types ────────────────────────────────────────────────────

type Notification = {
  id: string;
  title: string;
  body?: string | null;
  readAt?: string | null;
  createdAt?: string;
};

type FilterTab = 'ALL' | 'UNREAD' | 'READ';

// ─── Helpers ─────────────────────────────────────────────────

function timeAgo(dateStr?: string): string {
  if (!dateStr) return '';
  try {
    return formatDistanceToNow(parseISO(dateStr), { addSuffix: true, locale: tr });
  } catch {
    return dateStr.slice(0, 16).replace('T', ' ');
  }
}

// Başlığa göre ikon seçimi
function NotifIcon({ title, isRead }: { title: string; isRead: boolean }) {
  const t = title.toLowerCase();
  const base = isRead ? 'text-zinc-400' : 'text-indigo-600';
  const bg = isRead ? 'bg-zinc-100' : 'bg-indigo-50';

  let Icon = Bell;
  if (t.includes('duyuru') || t.includes('ilan')) Icon = Megaphone;
  else if (t.includes('bilgi') || t.includes('haber')) Icon = Info;
  else if (t.includes('yeni') || t.includes('güncelle')) Icon = Sparkles;

  return (
    <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ${bg}`}>
      <Icon className={`size-4 ${base}`} strokeWidth={1.8} />
    </div>
  );
}

function Skeleton({ className }: { className?: string }) {
  return <div className={`animate-pulse rounded-xl bg-zinc-100 ${className}`} />;
}

// ─── Notification Item ────────────────────────────────────────

function NotificationItem({
  notif,
  onMarkRead,
  marking,
}: {
  notif: Notification;
  onMarkRead: (id: string) => void;
  marking: boolean;
}) {
  const isRead = !!notif.readAt;

  return (
    <li
      className={`group relative flex gap-3.5 rounded-2xl border p-4 transition-all
        ${isRead
          ? 'border-zinc-100 bg-white'
          : 'border-indigo-100 bg-indigo-50/40 shadow-[0_1px_3px_rgba(99,102,241,0.08)]'
        }`}
    >
      {/* Unread indicator dot */}
      {!isRead && (
        <span className="absolute right-4 top-4 h-2 w-2 rounded-full bg-indigo-500" />
      )}

      <NotifIcon title={notif.title} isRead={isRead} />

      <div className="min-w-0 flex-1 pr-6">
        <p className={`text-sm leading-snug ${isRead ? 'font-normal text-zinc-700' : 'font-semibold text-zinc-900'}`}>
          {notif.title}
        </p>
        {notif.body && (
          <p className="mt-1 text-sm leading-relaxed text-zinc-500">{notif.body}</p>
        )}
        <p className="mt-2 text-[11px] font-medium text-zinc-400">{timeAgo(notif.createdAt)}</p>
      </div>

      {!isRead && (
        <button
          type="button"
          disabled={marking}
          onClick={() => onMarkRead(notif.id)}
          title="Okundu işaretle"
          className="absolute bottom-3.5 right-3.5 flex h-7 w-7 shrink-0 cursor-pointer items-center justify-center rounded-lg bg-white shadow-sm ring-1 ring-zinc-200 transition-all hover:bg-indigo-600 hover:text-white hover:ring-indigo-600 disabled:opacity-50"
        >
          {marking ? (
            <Loader2 className="size-3.5 animate-spin text-zinc-400" />
          ) : (
            <Check className="size-3.5 text-zinc-500 group-hover:text-white" />
          )}
        </button>
      )}
    </li>
  );
}

// ─── Main Page ────────────────────────────────────────────────

export default function ParentNotificationsPage() {
  const [items, setItems] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [filter, setFilter] = useState<FilterTab>('ALL');
  const [markingId, setMarkingId] = useState<string | null>(null);
  const [markingAll, setMarkingAll] = useState(false);

  const load = useCallback(async () => {
    const res = await apiFetchJson<Notification[]>('/v1/parent/notifications');
    if (res.error) setError(res.error);
    else setItems(Array.isArray(res.data) ? res.data : []);
  }, []);

  useEffect(() => {
    (async () => {
      setLoading(true);
      await load();
      setLoading(false);
    })();
  }, [load]);

  const handleMarkOne = async (id: string) => {
    setMarkingId(id);
    await apiFetchJson(`/v1/parent/notifications/${id}/read`, { method: 'PATCH' });
    await load();
    setMarkingId(null);
  };

  const handleMarkAll = async () => {
    setMarkingAll(true);
    await apiFetchJson('/v1/parent/notifications/read-all', { method: 'PATCH' });
    await load();
    setMarkingAll(false);
  };

  const unreadCount = useMemo(() => items.filter((n) => !n.readAt).length, [items]);

  const filtered = useMemo(() => {
    if (filter === 'UNREAD') return items.filter((n) => !n.readAt);
    if (filter === 'READ') return items.filter((n) => !!n.readAt);
    return items;
  }, [items, filter]);

  return (
    <div className="space-y-6 pb-8 font-urbanist">

      {/* ─── Hero Banner ──────────────────────────────────────── */}
      <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-violet-600 via-indigo-600 to-indigo-700 p-6 text-white shadow-lg">
        <div className="pointer-events-none absolute -right-10 -top-10 h-48 w-48 rounded-full bg-white/[0.06]" />
        <div className="pointer-events-none absolute -bottom-8 right-20 h-32 w-32 rounded-full bg-white/[0.04]" />

        <div className="relative flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-indigo-200">
              Veli Paneli
            </p>
            <h1 className="mt-1.5 text-2xl font-bold tracking-tight">Bildirimler</h1>
            <p className="mt-1 text-sm text-indigo-100/70">
              Okul duyuruları ve mesajlar
            </p>
          </div>

          {!loading && (
            <div className="flex shrink-0 items-center gap-3">
              {unreadCount > 0 ? (
                <div className="flex items-center gap-2.5 rounded-2xl border border-white/15 bg-white/10 px-4 py-3 backdrop-blur-sm">
                  <Bell className="size-4 text-indigo-200" />
                  <div>
                    <p className="text-[10px] font-semibold uppercase tracking-wide text-indigo-200/70">Okunmamış</p>
                    <p className="text-base font-bold">{unreadCount} bildirim</p>
                  </div>
                </div>
              ) : items.length > 0 ? (
                <div className="flex items-center gap-2.5 rounded-2xl border border-white/15 bg-white/10 px-4 py-3 backdrop-blur-sm">
                  <CheckCheck className="size-4 text-emerald-300" />
                  <div>
                    <p className="text-[10px] font-semibold uppercase tracking-wide text-indigo-200/70">Durum</p>
                    <p className="text-sm font-bold">Tümü okundu</p>
                  </div>
                </div>
              ) : null}

              {unreadCount > 0 && (
                <button
                  type="button"
                  disabled={markingAll}
                  onClick={handleMarkAll}
                  className="flex items-center gap-2 rounded-xl border border-white/20 bg-white/10 px-3.5 py-2.5 text-xs font-semibold text-white backdrop-blur-sm transition-all hover:bg-white/20 disabled:opacity-60"
                >
                  {markingAll
                    ? <Loader2 className="size-3.5 animate-spin" />
                    : <CheckCheck className="size-3.5" />
                  }
                  Tümünü okundu işaretle
                </button>
              )}
            </div>
          )}
        </div>
      </div>

      {/* ─── Error ──────────────────────────────────────────────── */}
      {error && (
        <div className="flex items-center gap-3 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          <AlertCircle className="size-4 shrink-0" />
          {error}
        </div>
      )}

      {/* ─── Filter Tabs ────────────────────────────────────────── */}
      {!loading && items.length > 0 && (
        <div className="flex items-center gap-2">
          {(
            [
              { value: 'ALL' as FilterTab, label: 'Tümü', count: items.length },
              { value: 'UNREAD' as FilterTab, label: 'Okunmamış', count: unreadCount },
              { value: 'READ' as FilterTab, label: 'Okunmuş', count: items.length - unreadCount },
            ] as const
          ).map((tab) => (
            <button
              key={tab.value}
              type="button"
              onClick={() => setFilter(tab.value)}
              className={`flex items-center gap-2 rounded-xl px-3.5 py-2 text-sm font-semibold transition-all
                ${filter === tab.value
                  ? 'bg-indigo-600 text-white shadow-sm'
                  : 'bg-white text-zinc-500 ring-1 ring-zinc-200 hover:bg-zinc-50 hover:text-zinc-800'
                }`}
            >
              {tab.label}
              {tab.count > 0 && (
                <span className={`rounded-full px-1.5 py-0.5 text-[10px] font-bold
                  ${filter === tab.value ? 'bg-white/20 text-white' : 'bg-zinc-100 text-zinc-500'}`}>
                  {tab.count}
                </span>
              )}
            </button>
          ))}
        </div>
      )}

      {/* ─── Content ─────────────────────────────────────────────── */}
      {loading ? (
        <div className="space-y-3">
          {[1, 2, 3, 4].map((i) => <Skeleton key={i} className="h-20" />)}
        </div>
      ) : items.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-2xl border-2 border-dashed border-zinc-200 py-20 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-violet-50">
            <BellOff className="size-8 text-violet-300" strokeWidth={1.5} />
          </div>
          <p className="mt-4 font-semibold text-zinc-600">Bildirim yok</p>
          <p className="mt-1 text-sm text-zinc-400">
            Okul duyuruları ve mesajlar burada görünecek.
          </p>
        </div>
      ) : filtered.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-2xl border border-dashed border-zinc-200 py-14 text-center">
          <CheckCheck className="size-8 text-zinc-200" />
          <p className="mt-3 text-sm text-zinc-400">Bu filtrede bildirim yok.</p>
          <button
            type="button"
            onClick={() => setFilter('ALL')}
            className="mt-2 text-xs font-medium text-indigo-600 hover:underline"
          >
            Tümünü göster
          </button>
        </div>
      ) : (
        <ul className="space-y-2.5">
          {filtered.map((n) => (
            <NotificationItem
              key={n.id}
              notif={n}
              onMarkRead={handleMarkOne}
              marking={markingId === n.id}
            />
          ))}
        </ul>
      )}
    </div>
  );
}
