'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { Bell, ShoppingBag, CalendarDays, Bot, Settings2, CheckCheck, CheckCircle2, UserPlus, CreditCard, X, RefreshCw } from 'lucide-react';
import { listNotifications, markNotificationRead, markAllNotificationsRead, deleteNotification } from '@client/api/notifications';
import { useAuth } from '@client/contexts/AuthContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { toast } from 'sonner';
import { usePageHeader } from '@client/contexts/PageHeaderContext';

type NotifType = 'order' | 'booking' | 'ai' | 'system' | 'billing' | 'staff';

interface Notification {
  id: string;
  type: NotifType;
  title: string;
  message: string;
  timestamp: string;
  read: boolean;
  actionLabel?: string;
  actionHref?: string;
}

function apiRowToNotif(row: any): Notification {
  return {
    id: row.id,
    type: (row.type as NotifType) || 'system',
    title: row.title || '',
    message: row.message || '',
    timestamp: row.created_at ? new Date(row.created_at).toLocaleString() : '',
    read: row.is_read || false,
    actionLabel: row.action_label,
    actionHref: row.action_href,
  };
}

export default function NotificationCenterPage() {
  const { t } = useLanguage();
  usePageHeader(t('notifications.title', "Notification Center"), t('notifications.subtitle', "All your alerts and updates in one place"));
  const { restaurantId } = useAuth();

  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeFilter, setActiveFilter] = useState<NotifType | 'all'>('all');

  const typeConfig: Record<NotifType, { icon: React.ReactNode; color: string; bg: string; label: string }> = {
    order: { icon: <ShoppingBag size={15} />, color: 'hsl(22, 89%, 48%)', bg: 'hsl(22, 100%, 96%)', label: t('notifications.typeOrders', 'Orders') },
    booking: { icon: <CalendarDays size={15} />, color: 'hsl(210, 100%, 40%)', bg: 'hsl(210, 100%, 96%)', label: t('notifications.typeBookings', 'Bookings') },
    ai: { icon: <Bot size={15} />, color: 'hsl(231, 40%, 45%)', bg: 'hsl(231, 40%, 96%)', label: t('notifications.typeAi', 'AI Alerts') },
    system: { icon: <Settings2 size={15} />, color: 'hsl(220, 9%, 46%)', bg: 'hsl(220, 9%, 96%)', label: t('notifications.typeSystem', 'System') },
    billing: { icon: <CreditCard size={15} />, color: 'hsl(142, 72%, 29%)', bg: 'hsl(142, 72%, 96%)', label: t('notifications.typeBilling', 'Billing') },
    staff: { icon: <UserPlus size={15} />, color: 'hsl(280, 60%, 45%)', bg: 'hsl(280, 60%, 96%)', label: t('notifications.typeStaff', 'Staff') },
  };

  const fetchNotifications = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const result = await listNotifications({ limit: '50' });
      setNotifications((result.notifications || []).map(apiRowToNotif));
    } catch (err: any) {
      toast.error(t('notifications.errorLoad', 'Failed to load notifications: ') + err.message);
    } finally {
      setLoading(false);
    }
  }, [restaurantId, t]);

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

  const markAllRead = async () => {
    if (!restaurantId) return;
    try {
      await markAllNotificationsRead();
      setNotifications(prev => prev.map(n => ({ ...n, read: true })));
    } catch (err: any) {
      toast.error(t('notifications.errorMarkAllRead', 'Failed to mark all read: ') + err.message);
    }
  };

  const markRead = async (id: string) => {
    try {
      await markNotificationRead(id);
      setNotifications(prev => prev.map(n => n.id === id ? { ...n, read: true } : n));
    } catch (err: any) {
      toast.error(t('notifications.errorMarkRead', 'Failed to mark read: ') + err.message);
    }
  };

  const deleteNotif = async (id: string) => {
    try {
      await deleteNotification(id);
      setNotifications(prev => prev.filter(n => n.id !== id));
    } catch (err: any) {
      toast.error(t('notifications.errorDelete', 'Failed to delete notification: ') + err.message);
    }
  };

  const unreadCount = notifications.filter(n => !n.read).length;
  const filtered = notifications.filter(n => activeFilter === 'all' || n.type === activeFilter);

  const filterTypes: Array<{ key: NotifType | 'all'; label: string }> = [
    { key: 'all', label: t('notifications.filterAll', 'All') },
    { key: 'order', label: t('notifications.typeOrders', 'Orders') },
    { key: 'booking', label: t('notifications.typeBookings', 'Bookings') },
    { key: 'ai', label: t('notifications.typeAi', 'AI Alerts') },
    { key: 'system', label: t('notifications.typeSystem', 'System') },
    { key: 'billing', label: t('notifications.typeBilling', 'Billing') },
    { key: 'staff', label: t('notifications.typeStaff', 'Staff') },
  ];

  return (
    <>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="flex items-center gap-3">
          <div className="flex gap-1 p-1 rounded-xl overflow-x-auto" style={{ backgroundColor: 'hsl(var(--muted))' }}>
            {filterTypes.map(f => (
              <button
                key={f.key}
                onClick={() => setActiveFilter(f.key)}
                className="px-3 py-1.5 rounded-lg text-xs font-medium transition-all whitespace-nowrap"
                style={{
                  backgroundColor: activeFilter === f.key ? 'hsl(var(--surface))' : 'transparent',
                  color: activeFilter === f.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))',
                  boxShadow: activeFilter === f.key ? 'var(--shadow-sm)' : 'none',
                }}
              >
                {f.label}
                {f.key !== 'all' && notifications.filter(n => n.type === f.key && !n.read).length > 0 && (
                  <span className="ml-1.5 text-xs opacity-60">{notifications.filter(n => n.type === f.key && !n.read).length}</span>
                )}
              </button>
            ))}
          </div>
        </div>
        <div className="flex gap-2">
          {unreadCount > 0 && (
            <button className="btn-secondary text-sm" onClick={markAllRead}>
              <CheckCheck size={15} /> {t('notifications.markAllRead', 'Mark all read ({count})').replace('{count}', unreadCount.toString())}
            </button>
          )}
          <button className="btn-secondary text-sm" onClick={fetchNotifications}>
            <RefreshCw size={15} className={loading ? 'animate-spin' : ''} />
          </button>
          <Link href="/notifications/preferences" className="btn-secondary text-sm">
            <Settings2 size={15} /> {t('notifications.preferences', 'Preferences')}
          </Link>
        </div>
      </div>

      {unreadCount > 0 && (
        <div className="flex items-center gap-3 p-3 rounded-xl mb-4" style={{ backgroundColor: 'hsl(var(--primary-light))', border: '1px solid hsl(22, 89%, 85%)' }}>
          <Bell size={16} style={{ color: 'hsl(var(--primary))' }} />
          <span className="text-sm font-medium" style={{ color: 'hsl(var(--primary))' }}>
            {t('notifications.unreadMessage', 'You have {count} unread notification{plural}').replace('{count}', unreadCount.toString()).replace('{plural}', unreadCount !== 1 ? 's' : '')}
          </span>
        </div>
      )}

      {loading ? (
        <div className="card overflow-hidden">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="flex items-center gap-4 px-5 py-4" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
              <div className="w-9 h-9 rounded-xl skeleton shrink-0" />
              <div className="flex-1 min-w-0">
                <div className="h-3.5 w-48 rounded skeleton mb-1.5" />
                <div className="h-3 w-32 rounded skeleton" />
              </div>
              <div className="h-3 w-16 rounded skeleton" />
            </div>
          ))}
        </div>
      ) : (
        <div className="space-y-2">
          {filtered.length === 0 && (
            <div className="text-center py-16" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <Bell size={32} className="mx-auto mb-3 opacity-30" />
              <p className="font-medium">{t('notifications.noNotifications', 'No notifications')}</p>
              <p className="text-xs mt-1">{t('notifications.caughtUp', "You're all caught up!")}</p>
            </div>
          )}
          {filtered.map(notif => {
            const tc = typeConfig[notif.type] || typeConfig.system;
            return (
              <div
                key={notif.id}
                className="flex items-start gap-4 p-4 rounded-xl transition-all"
                style={{
                  backgroundColor: notif.read ? 'hsl(var(--surface))' : 'hsl(var(--primary-light))',
                  border: `1px solid ${notif.read ? 'hsl(var(--border))' : 'hsl(22, 89%, 85%)'}`,
                }}
              >
                <div className="relative shrink-0 mt-0.5">
                  <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ backgroundColor: tc.bg, color: tc.color }}>
                    {tc.icon}
                  </div>
                  {!notif.read && (
                    <div className="absolute -top-0.5 -right-0.5 w-2.5 h-2.5 rounded-full" style={{ backgroundColor: 'hsl(var(--primary))' }} />
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-start justify-between gap-2">
                    <div>
                      <h4 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{notif.title}</h4>
                      <p className="text-xs mt-0.5 leading-relaxed" style={{ color: 'hsl(var(--muted-foreground))' }}>{notif.message}</p>
                    </div>
                    <div className="flex items-center gap-1 shrink-0">
                      {!notif.read && (
                        <button onClick={() => markRead(notif.id)} className="p-1.5 rounded-lg transition-colors hover:bg-black/5" title={t('notifications.markAsRead', 'Mark as read')}>
                          <CheckCircle2 size={14} style={{ color: 'hsl(var(--primary))' }} />
                        </button>
                      )}
                      <button onClick={() => deleteNotif(notif.id)} className="p-1.5 rounded-lg transition-colors hover:bg-black/5" title={t('notifications.delete', 'Delete')}>
                        <X size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
                      </button>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 mt-2">
                    <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{notif.timestamp}</span>
                    <span className="text-xs font-medium px-1.5 py-0.5 rounded" style={{ backgroundColor: tc.bg, color: tc.color }}>{tc.label}</span>
                    {notif.actionLabel && notif.actionHref && (
                      <Link href={notif.actionHref} className="text-xs font-semibold" style={{ color: 'hsl(var(--primary))' }}>
                        {notif.actionLabel} →
                      </Link>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </>
  );
}
