"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type { NotificationPreferences } from "@/lib/types";

const REMINDER_OPTIONS = [
  { value: 14, label: "14 Tage" },
  { value: 7, label: "7 Tage" },
  { value: 3, label: "3 Tage" },
  { value: 1, label: "1 Tag" },
];

export function NotificationSettings() {
  const queryClient = useQueryClient();
  const [saved, setSaved] = useState(false);

  const { data: prefs, isLoading } = useQuery({
    queryKey: ["notification-preferences"],
    queryFn: () =>
      api.get<NotificationPreferences>("/api/notification-preferences"),
  });

  const [reminderDays, setReminderDays] = useState<number[]>([]);
  const [emailEnabled, setEmailEnabled] = useState(true);
  const [dailyDigest, setDailyDigest] = useState(false);
  const [initialized, setInitialized] = useState(false);

  // Sync state from server once loaded
  if (prefs && !initialized) {
    setReminderDays(prefs.deadline_reminder_days);
    setEmailEnabled(prefs.email_enabled);
    setDailyDigest(prefs.daily_digest);
    setInitialized(true);
  }

  const update = useMutation({
    mutationFn: (input: {
      deadline_reminder_days: number[];
      email_enabled: boolean;
      daily_digest: boolean;
    }) => api.put<NotificationPreferences>("/api/notification-preferences", input),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["notification-preferences"],
      });
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    },
  });

  function toggleDay(day: number) {
    setReminderDays((prev) =>
      prev.includes(day) ? prev.filter((d) => d !== day) : [...prev, day].sort((a, b) => b - a),
    );
  }

  function handleSave() {
    update.mutate({
      deadline_reminder_days: reminderDays,
      email_enabled: emailEnabled,
      daily_digest: dailyDigest,
    });
  }

  if (isLoading) {
    return (
      <div className="animate-pulse space-y-3">
        <div className="h-4 w-48 rounded bg-neutral-200" />
        <div className="h-8 w-full rounded bg-neutral-100" />
        <div className="h-8 w-full rounded bg-neutral-100" />
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {/* Reminder days */}
      <div>
        <p className="text-sm font-medium text-neutral-700">
          Fristen-Erinnerungen
        </p>
        <p className="mt-0.5 text-xs text-neutral-500">
          Erinnern Sie mich vor Fristablauf:
        </p>
        <div className="mt-2 flex flex-wrap gap-2">
          {REMINDER_OPTIONS.map((opt) => (
            <button
              key={opt.value}
              onClick={() => toggleDay(opt.value)}
              className={`rounded-lg border px-3 py-1.5 text-sm transition-colors ${
                reminderDays.includes(opt.value)
                  ? "border-blue-500 bg-blue-50 text-blue-700"
                  : "border-neutral-200 bg-white text-neutral-600 hover:border-neutral-300"
              }`}
            >
              {opt.label}
            </button>
          ))}
        </div>
      </div>

      {/* Email toggle */}
      <label className="flex items-center justify-between">
        <div>
          <p className="text-sm font-medium text-neutral-700">
            E-Mail-Benachrichtigungen
          </p>
          <p className="text-xs text-neutral-500">
            Erinnerungen per E-Mail erhalten
          </p>
        </div>
        <button
          onClick={() => setEmailEnabled(!emailEnabled)}
          className={`relative h-6 w-11 rounded-full transition-colors ${
            emailEnabled ? "bg-blue-500" : "bg-neutral-300"
          }`}
        >
          <span
            className={`absolute left-0.5 top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${
              emailEnabled ? "translate-x-5" : "translate-x-0"
            }`}
          />
        </button>
      </label>

      {/* Daily digest toggle */}
      <label className="flex items-center justify-between">
        <div>
          <p className="text-sm font-medium text-neutral-700">
            Tagesübersicht
          </p>
          <p className="text-xs text-neutral-500">
            Alle Benachrichtigungen gesammelt um 8:00 Uhr per E-Mail
          </p>
        </div>
        <button
          onClick={() => setDailyDigest(!dailyDigest)}
          className={`relative h-6 w-11 rounded-full transition-colors ${
            dailyDigest ? "bg-blue-500" : "bg-neutral-300"
          }`}
        >
          <span
            className={`absolute left-0.5 top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${
              dailyDigest ? "translate-x-5" : "translate-x-0"
            }`}
          />
        </button>
      </label>

      {/* Save */}
      <div className="flex items-center gap-3 pt-2">
        <button
          onClick={handleSave}
          disabled={update.isPending}
          className="rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50"
        >
          {update.isPending ? "Speichern..." : "Speichern"}
        </button>
        {saved && (
          <span className="text-sm text-green-600">Gespeichert</span>
        )}
      </div>
    </div>
  );
}
