import React from 'react';
import { AlertTriangle, LogOut, Palette } from 'lucide-react';
import { useNavigate } from 'react-router-dom';

import AppearanceToggleDropdown from '@/components/appearance-dropdown';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import { Alert, AlertDescription } from '@/components/ui/alert';

import { AdminLayout } from '../components/AdminLayout';
import { useAuth } from '../auth/context';
import { ADMIN_EVENTS_PATH, ADMIN_LOGIN_PATH } from '../constants';
import {
  getNotificationPreferences,
  updateNotificationPreferences,
  NotificationPreferences,
  NotificationPreferencesMeta,
} from '../api';
import { getApiErrorMessage } from '../lib/apiError';
import { useTranslation } from 'react-i18next';

export default function SettingsPage() {
  const navigate = useNavigate();
  const { user, logout } = useAuth();
  const { t } = useTranslation('management');

  const [preferences, setPreferences] = React.useState<NotificationPreferences | null>(null);
  const [defaults, setDefaults] = React.useState<NotificationPreferences>({});
  const [loadingNotifications, setLoadingNotifications] = React.useState(true);
  const [savingNotifications, setSavingNotifications] = React.useState(false);
  const [notificationError, setNotificationError] = React.useState<string | null>(null);
  const [notificationMeta, setNotificationMeta] = React.useState<NotificationPreferencesMeta | null>(null);

  function handleLogout() {
    logout({ redirect: ADMIN_LOGIN_PATH });
  }

  React.useEffect(() => {
    (async () => {
      try {
        const result = await getNotificationPreferences();
        setPreferences(result.preferences);
        setDefaults(result.defaults);
        setNotificationMeta(result.meta ?? null);
      } catch (error) {
        setNotificationError(getApiErrorMessage(error, t('settings.notifications.errorLoad', 'Benachrichtigungseinstellungen konnten nicht geladen werden.')));
      } finally {
        setLoadingNotifications(false);
      }
    })();
  }, [t]);

  const actions = (
    <Button
      variant="outline"
      onClick={() => navigate(ADMIN_EVENTS_PATH)}
      className="border-pink-200 text-pink-600 hover:bg-pink-50"
    >
      Zurück zur Übersicht
    </Button>
  );

  return (
    <AdminLayout
      title="Einstellungen"
      subtitle="Passe das Erscheinungsbild deines Dashboards an und verwalte deine Session."
      actions={actions}
    >
      <Card className="max-w-2xl border-0 bg-white/85 shadow-xl shadow-amber-100/60">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-xl text-slate-900">
            <Palette className="h-5 w-5 text-amber-500" /> Darstellung & Account
          </CardTitle>
          <CardDescription className="text-sm text-slate-600">
            Gestalte den Admin-Bereich so farbenfroh wie dein Gästeportal.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <section className="space-y-2">
            <h2 className="text-sm font-semibold text-slate-800">Darstellung</h2>
            <p className="text-sm text-slate-600">
              Wechsel zwischen Hell- und Dunkelmodus oder übernimm automatisch die Systemeinstellung.
            </p>
            <AppearanceToggleDropdown />
          </section>

          <section className="space-y-2">
            <h2 className="text-sm font-semibold text-slate-800">Angemeldeter Account</h2>
            <p className="text-sm text-slate-600">
              {user ? (
                <>
                  Eingeloggt als <span className="font-medium text-slate-900">{user.name ?? user.email ?? 'Tenant Admin'}</span>
                  {user.tenant_id && <> - Tenant #{user.tenant_id}</>}
                </>
              ) : (
                'Aktuell kein Benutzer geladen.'
              )}
            </p>
            <div className="flex flex-wrap gap-3 pt-2">
              <Button variant="destructive" onClick={handleLogout} className="flex items-center gap-2">
                <LogOut className="h-4 w-4" /> Abmelden
              </Button>
              <Button variant="ghost" onClick={() => navigate(-1)}>
                Abbrechen
              </Button>
            </div>
          </section>
        </CardContent>
      </Card>

      <Card className="mt-8 max-w-3xl border-0 bg-white/85 shadow-xl shadow-pink-100/60">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-xl text-slate-900">
            <AlertTriangle className="h-5 w-5 text-pink-500" />
            {t('settings.notifications.title', 'Benachrichtigungen')}
          </CardTitle>
          <CardDescription className="text-sm text-slate-600">
            {t('settings.notifications.description', 'Lege fest, für welche Ereignisse wir dich per E-Mail informieren.')}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {notificationError && (
            <Alert variant="destructive">
              <AlertDescription>{notificationError}</AlertDescription>
            </Alert>
          )}

          {loadingNotifications ? (
            <div className="space-y-3">
              {Array.from({ length: 5 }).map((_, index) => (
                <div
                  key={index}
                  className="h-12 animate-pulse rounded-xl bg-gradient-to-r from-white/30 via-white/60 to-white/30"
                />
              ))}
            </div>
          ) : preferences ? (
            <NotificationPreferencesForm
              preferences={preferences}
              defaults={defaults}
              meta={notificationMeta}
              onChange={(next) => setPreferences(next)}
              onReset={() => setPreferences(defaults)}
              onSave={async () => {
                if (!preferences) {
                  return;
                }
                try {
                  setSavingNotifications(true);
                  const updated = await updateNotificationPreferences(preferences);
                  setPreferences(updated.preferences);
                  if (updated.defaults && Object.keys(updated.defaults).length > 0) {
                    setDefaults(updated.defaults);
                  }
                  if (updated.meta) {
                    setNotificationMeta(updated.meta);
                  }
                  setNotificationError(null);
                } catch (error) {
                  setNotificationError(
                    getApiErrorMessage(error, t('settings.notifications.errorSave', 'Speichern fehlgeschlagen. Bitte versuche es erneut.')),
                  );
                } finally {
                  setSavingNotifications(false);
                }
              }}
              saving={savingNotifications}
              translate={t}
            />
          ) : null}
        </CardContent>
      </Card>
    </AdminLayout>
  );
}

function NotificationPreferencesForm({
  preferences,
  defaults,
  meta,
  onChange,
  onReset,
  onSave,
  saving,
  translate,
}: {
  preferences: NotificationPreferences;
  defaults: NotificationPreferences;
  meta: NotificationPreferencesMeta | null;
  onChange: (next: NotificationPreferences) => void;
  onReset: () => void;
  onSave: () => Promise<void>;
  saving: boolean;
  translate: (key: string, options?: Record<string, unknown>) => string;
}) {
  const items = React.useMemo(() => buildPreferenceMeta(translate), [translate]);
  const locale = typeof window !== 'undefined' ? window.navigator.language : 'de-DE';
  const creditText = React.useMemo(() => {
    if (!meta) {
      return null;
    }

    if (meta.credit_warning_sent_at) {
      const date = formatDateTime(meta.credit_warning_sent_at, locale);

      return translate('settings.notifications.meta.creditLast', 'Letzte Credit-Warnung: {{date}}', {
        date,
      });
    }

    return translate('settings.notifications.meta.creditNever', 'Noch keine Credit-Warnung versendet.');
  }, [meta, translate, locale]);

  return (
    <div className="space-y-4">
      <div className="space-y-3">
        {items.map((item) => {
          const checked = preferences[item.key] ?? defaults[item.key] ?? true;

          return (
            <div key={item.key} className="flex items-start justify-between gap-4 rounded-xl border border-pink-100 bg-white/70 p-4 shadow-sm">
              <div className="space-y-1">
                <h3 className="text-sm font-semibold text-slate-900">{item.label}</h3>
                <p className="text-sm text-slate-600">{item.description}</p>
              </div>
              <Switch
                checked={checked}
                onCheckedChange={(value) => onChange({ ...preferences, [item.key]: Boolean(value) })}
              />
            </div>
          );
        })}
      </div>
      <div className="flex flex-wrap items-center gap-3">
        <Button onClick={onSave} disabled={saving} className="bg-gradient-to-r from-pink-500 via-fuchsia-500 to-purple-500 text-white">
          {saving ? 'Speichern...' : translate('settings.notifications.actions.save', 'Speichern')}
        </Button>
        <Button variant="ghost" onClick={onReset} disabled={saving}>
          {translate('settings.notifications.actions.reset', 'Auf Standard setzen')}
        </Button>
        <span className="text-xs text-slate-500">
          {translate('settings.notifications.hint', 'Du kannst Benachrichtigungen jederzeit wieder aktivieren.')}
        </span>
      </div>
      {creditText && <p className="text-xs text-slate-500">{creditText}</p>}
    </div>
  );
}

function buildPreferenceMeta(
  translate: (key: string, options?: Record<string, unknown>) => string
): Array<{ key: keyof NotificationPreferences; label: string; description: string }> {
  const map = [
    {
      key: 'photo_thresholds',
      label: translate('settings.notifications.items.photoThresholds.label', 'Warnung bei Foto-Schwellen'),
      description: translate('settings.notifications.items.photoThresholds.description', 'Sende Warnungen bei 80 % und 95 % Foto-Auslastung.'),
    },
    {
      key: 'photo_limits',
      label: translate('settings.notifications.items.photoLimits.label', 'Sperre bei Foto-Limit'),
      description: translate('settings.notifications.items.photoLimits.description', 'Informiere mich, sobald keine Foto-Uploads mehr möglich sind.'),
    },
    {
      key: 'guest_thresholds',
      label: translate('settings.notifications.items.guestThresholds.label', 'Warnung bei Gästekontingent'),
      description: translate('settings.notifications.items.guestThresholds.description', 'Warnung kurz bevor alle Gästelinks vergeben sind.'),
    },
    {
      key: 'guest_limits',
      label: translate('settings.notifications.items.guestLimits.label', 'Sperre bei Gästelimit'),
      description: translate('settings.notifications.items.guestLimits.description', 'Hinweis, wenn keine neuen Gästelinks mehr erzeugt werden können.'),
    },
    {
      key: 'gallery_warnings',
      label: translate('settings.notifications.items.galleryWarnings.label', 'Galerie läuft bald ab'),
      description: translate('settings.notifications.items.galleryWarnings.description', 'Erhalte 7 und 1 Tag vor Ablauf eine Erinnerung.'),
    },
    {
      key: 'gallery_expired',
      label: translate('settings.notifications.items.galleryExpired.label', 'Galerie ist abgelaufen'),
      description: translate('settings.notifications.items.galleryExpired.description', 'Informiere mich, sobald Gäste die Galerie nicht mehr sehen können.'),
    },
    {
      key: 'event_thresholds',
      label: translate('settings.notifications.items.eventThresholds.label', 'Warnung bei Event-Kontingent'),
      description: translate('settings.notifications.items.eventThresholds.description', 'Hinweis, wenn das Reseller-Paket fast ausgeschöpft ist.'),
    },
    {
      key: 'event_limits',
      label: translate('settings.notifications.items.eventLimits.label', 'Sperre bei Event-Kontingent'),
      description: translate('settings.notifications.items.eventLimits.description', 'Nachricht, sobald keine weiteren Events erstellt werden können.'),
    },
    {
      key: 'package_expiring',
      label: translate('settings.notifications.items.packageExpiring.label', 'Paket läuft bald ab'),
      description: translate('settings.notifications.items.packageExpiring.description', 'Erinnerungen bei 30, 7 und 1 Tag vor Paketablauf.'),
    },
    {
      key: 'package_expired',
      label: translate('settings.notifications.items.packageExpired.label', 'Paket ist abgelaufen'),
      description: translate('settings.notifications.items.packageExpired.description', 'Benachrichtige mich, wenn das Paket abgelaufen ist.'),
    },
    {
      key: 'credits_low',
      label: translate('settings.notifications.items.creditsLow.label', 'Event-Credits werden knapp'),
      description: translate('settings.notifications.items.creditsLow.description', 'Informiert mich bei niedrigen Credit-Schwellen.'),
    },
  ];

  return map as Array<{ key: keyof NotificationPreferences; label: string; description: string }>;
}

function formatDateTime(value: string, locale: string): string {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }

  try {
    return new Intl.DateTimeFormat(locale, {
      day: '2-digit',
      month: 'short',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    }).format(date);
  } catch {
    return date.toISOString();
  }
}
