'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Bell, Mail, Smartphone, Save, ArrowLeft, ShoppingBag, CalendarDays, Bot, CreditCard, UserPlus, Settings2, Loader2, CheckCircle2 } from 'lucide-react';
import {
  getNotificationPreferences,
  saveNotificationPreferences,
  NotifPreference,
} from '@client/api/notification-preferences';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

const defaultPrefs: NotifPreference[] = [
  { id: 'new-order', category: 'Orders', event: 'New Order Received', description: 'When a customer places a new order through any channel', inApp: true, email: false, sms: false },
  { id: 'order-cancelled', category: 'Orders', event: 'Order Cancelled', description: 'When a customer cancels an existing order', inApp: true, email: true, sms: false },
  { id: 'order-high-volume', category: 'Orders', event: 'High Order Volume Alert', description: 'When order volume exceeds 40% above average', inApp: true, email: false, sms: false },
  { id: 'new-booking', category: 'Table Bookings', event: 'New Booking', description: 'When a customer makes a new table reservation', inApp: true, email: false, sms: false },
  { id: 'booking-cancelled', category: 'Table Bookings', event: 'Booking Cancelled', description: 'When a customer cancels a reservation', inApp: true, email: true, sms: false },
  { id: 'booking-reminder', category: 'Table Bookings', event: 'Upcoming Booking Reminder', description: '30 minutes before a scheduled reservation', inApp: true, email: false, sms: true },
  { id: 'ai-escalation', category: 'AI Agent', event: 'AI Escalation / Handoff', description: 'When the AI cannot resolve a query and escalates to staff', inApp: true, email: false, sms: true },
  { id: 'ai-low-balance', category: 'AI Agent', event: 'Low AI Call Balance', description: 'When monthly AI call usage exceeds 80%', inApp: true, email: true, sms: false },
  { id: 'ai-kb-sync', category: 'AI Agent', event: 'Knowledge Base Sync Complete', description: 'When a knowledge base update finishes syncing', inApp: true, email: false, sms: false },
  { id: 'system-update', category: 'System', event: 'Platform Update', description: 'When a new platform version is deployed', inApp: true, email: true, sms: false },
  { id: 'webhook-failure', category: 'System', event: 'Webhook Delivery Failure', description: 'When a webhook endpoint fails to receive events', inApp: true, email: true, sms: false },
  { id: 'new-staff-login', category: 'Staff', event: 'New Staff Login', description: 'When a staff member logs in from a new device', inApp: true, email: true, sms: false },
  { id: 'billing-invoice', category: 'Billing', event: 'Invoice Paid', description: 'When a monthly invoice is successfully charged', inApp: true, email: true, sms: false },
  { id: 'billing-failed', category: 'Billing', event: 'Payment Failed', description: 'When a billing payment fails', inApp: true, email: true, sms: true },
];

const categoryIcons: Record<string, React.ReactNode> = {
  Orders: <ShoppingBag size={15} />,
  'Table Bookings': <CalendarDays size={15} />,
  'AI Agent': <Bot size={15} />,
  System: <Settings2 size={15} />,
  Staff: <UserPlus size={15} />,
  Billing: <CreditCard size={15} />,
};

const categoryColors: Record<string, string> = {
  Orders: 'hsl(22, 89%, 48%)',
  'Table Bookings': 'hsl(210, 100%, 40%)',
  'AI Agent': 'hsl(231, 40%, 45%)',
  System: 'hsl(220, 9%, 46%)',
  Staff: 'hsl(280, 60%, 45%)',
  Billing: 'hsl(142, 72%, 29%)',
};

function Toggle({ checked, onChange }: { checked: boolean; onChange: () => void }) {
  return (
    <button
      onClick={onChange}
      className="relative inline-flex items-center w-9 h-5 rounded-full transition-colors shrink-0"
      style={{ backgroundColor: checked ? 'hsl(var(--primary))' : 'hsl(var(--border-strong))' }}
    >
      <span
        className="inline-block w-3.5 h-3.5 bg-white rounded-full shadow transition-transform"
        style={{ transform: checked ? 'translateX(18px)' : 'translateX(3px)' }}
      />
    </button>
  );
}

export default function NotificationPreferencesPage() {
  const { t } = useLanguage();
  usePageHeader(t('notifications.preferences_title', "Notification Preferences"), t('notifications.preferences_subtitle', "Control how and when you receive notifications"));
  const [prefs, setPrefs] = useState<NotifPreference[]>(defaultPrefs);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    getNotificationPreferences()
      .then(serverPrefs => {
        if (serverPrefs && Array.isArray(serverPrefs) && serverPrefs.length > 0) {
          setPrefs(serverPrefs);
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const toggle = (id: string, channel: 'inApp' | 'email' | 'sms') => {
    setPrefs(prev => prev.map(p => p.id === id ? { ...p, [channel]: !p[channel] } : p));
    setSaved(false);
  };

  const categories = [...new Set(prefs.map(p => p.category))];

  const handleSave = async () => {
    setSaving(true);
    try {
      await saveNotificationPreferences(prefs);
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    } catch {
      // save failed silently
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <div className="flex items-center justify-between mb-6">
        <Link href="/notifications" className="flex items-center gap-2 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <ArrowLeft size={15} /> {t('notifications.back_to_list', 'Back to Notifications')}
        </Link>
        <button className="btn-primary flex items-center gap-2" onClick={handleSave} disabled={saving}>
          {saving ? <Loader2 size={15} className="animate-spin" /> : saved ? <CheckCircle2 size={15} /> : <Save size={15} />}
          {saved ? t('notifications.saved', 'Saved!') : saving ? t('notifications.saving', 'Saving…') : t('notifications.save_preferences', 'Save Preferences')}
        </button>
      </div>

      <div className="flex items-center gap-6 p-4 rounded-xl mb-6" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
        <span className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('notifications.channels', 'Channels:')}</span>
        {[
          { icon: <Bell size={13} />, label: t('notifications.channel_in_app', 'In-App'), color: 'hsl(var(--primary))' },
          { icon: <Mail size={13} />, label: t('notifications.channel_email', 'Email'), color: 'hsl(210, 100%, 40%)' },
          { icon: <Smartphone size={13} />, label: t('notifications.channel_sms', 'SMS'), color: 'hsl(142, 72%, 29%)' },
        ].map(ch => (
          <div key={ch.label} className="flex items-center gap-1.5">
            <span style={{ color: ch.color }}>{ch.icon}</span>
            <span className="text-xs font-medium" style={{ color: 'hsl(var(--foreground-secondary))' }}>{ch.label}</span>
          </div>
        ))}
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-16 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Loader2 size={20} className="animate-spin" /> {t('notifications.loading_preferences', 'Loading preferences…')}
        </div>
      ) : (
        <div className="space-y-6">
          {categories.map(category => {
            const catPrefs = prefs.filter(p => p.category === category);
            const color = categoryColors[category] || 'hsl(var(--primary))';
            return (
              <div key={category} className="rounded-2xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <div className="flex items-center gap-3 px-5 py-3" style={{ backgroundColor: `${color}08`, borderBottom: '1px solid hsl(var(--border))' }}>
                  <div className="w-7 h-7 rounded-lg flex items-center justify-center" style={{ backgroundColor: `${color}15`, color }}>
                    {categoryIcons[category]}
                  </div>
                  <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t(`notifications.category_${category.toLowerCase().replace(/\s+/g, '_')}`, category)}</h3>
                  <span className="text-xs ml-auto" style={{ color: 'hsl(var(--muted-foreground))' }}>{catPrefs.length} {t('notifications.events_count', 'events')}</span>
                </div>

                <div className="grid grid-cols-12 px-5 py-2 text-xs font-semibold uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))', borderBottom: '1px solid hsl(var(--border))' }}>
                  <div className="col-span-6">{t('notifications.event_column', 'Event')}</div>
                  <div className="col-span-2 text-center flex items-center justify-center gap-1"><Bell size={11} /> {t('notifications.channel_in_app', 'In-App')}</div>
                  <div className="col-span-2 text-center flex items-center justify-center gap-1"><Mail size={11} /> {t('notifications.channel_email', 'Email')}</div>
                  <div className="col-span-2 text-center flex items-center justify-center gap-1"><Smartphone size={11} /> {t('notifications.channel_sms', 'SMS')}</div>
                </div>

                {catPrefs.map((pref, idx) => (
                  <div
                    key={pref.id}
                    className="grid grid-cols-12 items-center px-5 py-3.5"
                    style={{ borderBottom: idx < catPrefs.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}
                  >
                    <div className="col-span-6 pr-4">
                      <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t(`notifications.event_${pref.id.replace(/-/g, '_')}`, pref.event)}</p>
                      <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t(`notifications.desc_${pref.id.replace(/-/g, '_')}`, pref.description)}</p>
                    </div>
                    <div className="col-span-2 flex justify-center">
                      <Toggle checked={pref.inApp} onChange={() => toggle(pref.id, 'inApp')} />
                    </div>
                    <div className="col-span-2 flex justify-center">
                      <Toggle checked={pref.email} onChange={() => toggle(pref.id, 'email')} />
                    </div>
                    <div className="col-span-2 flex justify-center">
                      <Toggle checked={pref.sms} onChange={() => toggle(pref.id, 'sms')} />
                    </div>
                  </div>
                ))}
              </div>
            );
          })}
        </div>
      )}

      <div className="flex justify-end mt-6">
        <button className="btn-primary flex items-center gap-2" onClick={handleSave} disabled={saving}>
          {saving ? <Loader2 size={15} className="animate-spin" /> : saved ? <CheckCircle2 size={15} /> : <Save size={15} />}
          {saved ? t('notifications.saved', 'Saved!') : saving ? t('notifications.saving', 'Saving…') : t('notifications.save_preferences', 'Save Preferences')}
        </button>
      </div>
    </>
  );
}
