'use client';

import { useState, useEffect } from 'react';
import AlertOverlay from '@client/components/AlertOverlay';
import { Volume2, VolumeX, ShoppingBag, CalendarDays, Bot, Save, ArrowLeft, Sliders, Monitor, Clock, TestTube, Loader2 } from 'lucide-react';
import Link from 'next/link';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { getAlertSettings, saveAlertSettings } from '@client/api/alert-settings';
import { toast } from 'sonner';

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

const DEFAULT_SETTINGS = {
  soundEnabled: true,
  volume: 70,
  autoDismiss: 30,
  showOrders: true,
  showBookings: true,
  showAiEscalations: true,
  browserNotifications: false,
};

export default function AlertSettingsPage() {
  const { t } = useLanguage();
  usePageHeader(t('alertSettings.title', 'Alert Settings'), t('alertSettings.subtitle', 'Configure real-time order and booking alert behavior'));
  const [settings, setSettings] = useState(DEFAULT_SETTINGS);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [showDemo, setShowDemo] = useState(false);

  useEffect(() => {
    getAlertSettings()
      .then(s => setSettings(s))
      .catch(() => { toast.error(t('alertSettings.errorLoad', 'Failed to load alert settings')); })
      .finally(() => setLoading(false));
  }, [t]);

  const update = (key: string, value: boolean | number) =>
    setSettings(prev => ({ ...prev, [key]: value }));

  const handleSave = async () => {
    setSaving(true);
    try {
      await saveAlertSettings(settings);
      setSaved(true);
      toast.success(t('alertSettings.successSave', 'Alert settings saved'));
      if (settings.browserNotifications && typeof window !== 'undefined' && 'Notification' in window) {
        Notification.requestPermission();
      }
      setTimeout(() => setSaved(false), 2500);
    } catch {
      toast.error(t('alertSettings.errorSave', 'Failed to save settings. Please try again.'));
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
        <Loader2 size={20} className="animate-spin" /> {t('alertSettings.loading', 'Loading settings…')}
      </div>
    );
  }

  return (
    <>
      <div className="max-w-2xl">
        <div className="flex items-center justify-between mb-6">
          <Link href="/restaurant-dashboard" className="flex items-center gap-2 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
            <ArrowLeft size={15} /> {t('alertSettings.backToDashboard', 'Back to Dashboard')}
          </Link>
          <div className="flex gap-2 items-center">
            <button className="btn-secondary text-sm" onClick={() => setShowDemo(true)}>
              <TestTube size={15} /> {t('alertSettings.previewAlert', 'Preview Alert')}
            </button>
            <button className="btn-primary" onClick={handleSave} disabled={saving}>
              {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
              {saving ? t('alertSettings.saving', 'Saving…') : saved ? t('alertSettings.saved', 'Saved!') : t('alertSettings.saveSettings', 'Save Settings')}
            </button>
          </div>
        </div>

        <div className="space-y-4">
          {/* Sound settings */}
          <div className="rounded-2xl p-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <h3 className="font-semibold text-sm mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
              <Volume2 size={16} style={{ color: 'hsl(var(--primary))' }} /> {t('alertSettings.soundNotifications', 'Sound Notifications')}
            </h3>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('alertSettings.enableSoundAlerts', 'Enable Sound Alerts')}</p>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('alertSettings.enableSoundAlertsDesc', 'Play a sound when new alerts arrive')}</p>
                </div>
                <Toggle checked={settings.soundEnabled} onChange={() => update('soundEnabled', !settings.soundEnabled)} />
              </div>
              {settings.soundEnabled && (
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('alertSettings.alertVolume', 'Alert Volume')}</label>
                    <span className="text-xs font-mono font-semibold" style={{ color: 'hsl(var(--primary))' }}>{settings.volume}%</span>
                  </div>
                  <input
                    type="range"
                    min={0}
                    max={100}
                    value={settings.volume}
                    onChange={e => update('volume', parseInt(e.target.value, 10))}
                    className="w-full accent-orange-500"
                  />
                  <div className="flex items-center justify-between mt-1">
                    <VolumeX size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />
                    <Volume2 size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Auto-dismiss */}
          <div className="rounded-2xl p-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <h3 className="font-semibold text-sm mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
              <Clock size={16} style={{ color: 'hsl(210, 100%, 40%)' }} /> {t('alertSettings.autoDismissTimer', 'Auto-Dismiss Timer')}
            </h3>
            <div>
              <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                {t('alertSettings.dismissAlertsAfter', 'Dismiss alerts after')}
              </label>
              <div className="flex gap-2">
                {[15, 30, 60, 120].map(sec => (
                  <button
                    key={sec}
                    onClick={() => update('autoDismiss', sec)}
                    className="flex-1 py-2 rounded-xl text-sm font-semibold transition-all"
                    style={{
                      backgroundColor: settings.autoDismiss === sec ? 'hsl(var(--primary))' : 'hsl(var(--muted))',
                      color: settings.autoDismiss === sec ? 'white' : 'hsl(var(--foreground-secondary))',
                    }}
                  >
                    {sec < 60 ? `${sec}s` : `${sec / 60}m`}
                  </button>
                ))}
              </div>
              <p className="text-xs mt-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t('alertSettings.autoDismissDesc', 'Alerts will automatically dismiss after {seconds} seconds if not acted upon').replace('{seconds}', settings.autoDismiss.toString())}
              </p>
            </div>
          </div>

          {/* Alert types */}
          <div className="rounded-2xl p-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <h3 className="font-semibold text-sm mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
              <Sliders size={16} style={{ color: 'hsl(142, 72%, 29%)' }} /> {t('alertSettings.alertTypes', 'Alert Types')}
            </h3>
            <div className="space-y-3">
              {[
                { key: 'showOrders', icon: <ShoppingBag size={15} />, label: t('alertSettings.newOrders', 'New Orders'), desc: t('alertSettings.newOrdersDesc', 'Show alert when a new order is placed'), color: 'hsl(22, 89%, 48%)' },
                { key: 'showBookings', icon: <CalendarDays size={15} />, label: t('alertSettings.newBookings', 'New Bookings'), desc: t('alertSettings.newBookingsDesc', 'Show alert when a table is reserved'), color: 'hsl(210, 100%, 40%)' },
                { key: 'showAiEscalations', icon: <Bot size={15} />, label: t('alertSettings.aiEscalations', 'AI Escalations'), desc: t('alertSettings.aiEscalationsDesc', 'Show alert when AI hands off to staff'), color: 'hsl(231, 40%, 45%)' },
              ].map(item => (
                <div key={item.key} className="flex items-center justify-between p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ backgroundColor: `${item.color}15`, color: item.color }}>
                      {item.icon}
                    </div>
                    <div>
                      <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{item.label}</p>
                      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.desc}</p>
                    </div>
                  </div>
                  <Toggle
                    checked={settings[item.key as keyof typeof settings] as boolean}
                    onChange={() => update(item.key, !settings[item.key as keyof typeof settings])}
                  />
                </div>
              ))}
            </div>
          </div>

          {/* Browser notifications */}
          <div className="rounded-2xl p-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <h3 className="font-semibold text-sm mb-4 flex items-center gap-2" style={{ color: 'hsl(var(--foreground))' }}>
              <Monitor size={16} style={{ color: 'hsl(38, 92%, 40%)' }} /> {t('alertSettings.browserNotifications', 'Browser Notifications')}
            </h3>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('alertSettings.enableBrowserNotifications', 'Enable Browser Notifications')}</p>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('alertSettings.enableBrowserNotificationsDesc', 'Receive alerts even when the tab is not in focus')}</p>
              </div>
              <Toggle checked={settings.browserNotifications} onChange={() => update('browserNotifications', !settings.browserNotifications)} />
            </div>
            {settings.browserNotifications && (
              <div className="mt-3 p-3 rounded-lg text-xs" style={{ backgroundColor: 'hsl(var(--warning-bg))', color: 'hsl(var(--warning))', border: '1px solid hsl(var(--warning-border))' }}>
                {t('alertSettings.browserNotificationsWarning', 'Browser will request notification permission when you save these settings.')}
              </div>
            )}
          </div>
        </div>
      </div>

      {showDemo && (
        <AlertOverlay
          alerts={[
            {
              id: 'demo-order',
              type: 'order',
              title: t('alertSettings.demoOrderTitle', '1 New Order'),
              subtitle: t('alertSettings.demoOrderSubtitle', 'Just placed'),
              details: [t('alertSettings.demoOrderDetails', '1 pending order awaiting confirmation')],
              timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
              countdown: settings.autoDismiss,
            },
          ]}
          onDismiss={() => setShowDemo(false)}
          onAccept={() => setShowDemo(false)}
          soundEnabled={settings.soundEnabled}
          volume={settings.volume}
        />
      )}
    </>
  );
}
