"use client";

import { Bell, Volume2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { LabeledField } from "@/components/ui/labeled-field";
import { notify } from "@/lib/notify";
import { useNotifPrefs } from "@/lib/notifications/notification-prefs.store";
import { SOUND_PRESETS, playSound, type SoundId } from "@/lib/notifications/sounds";
import {
  showDesktopNotification,
  useNotificationPermission,
} from "@/lib/notifications/use-desktop-notifications";

function Toggle({
  id,
  checked,
  onChange,
  label,
  hint,
}: {
  id: string;
  checked: boolean;
  onChange: (v: boolean) => void;
  label: string;
  hint?: string;
}) {
  return (
    <label
      htmlFor={id}
      className="flex cursor-pointer items-start justify-between gap-4 rounded-lg border border-border/80 bg-card px-4 py-3"
    >
      <span className="min-w-0 space-y-0.5">
        <span className="block text-sm font-medium">{label}</span>
        {hint ? <span className="block text-xs text-muted-foreground">{hint}</span> : null}
      </span>
      <span className="relative mt-0.5 inline-flex shrink-0">
        <input
          id={id}
          type="checkbox"
          className="peer sr-only"
          checked={checked}
          onChange={(e) => onChange(e.target.checked)}
        />
        <span className="h-6 w-11 rounded-full bg-muted transition-colors peer-checked:bg-[#0F6E56]" />
        <span className="absolute top-0.5 start-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform peer-checked:translate-x-5 rtl:peer-checked:-translate-x-5" />
      </span>
    </label>
  );
}

export function SettingsNotificationsPanel() {
  const t = useTranslations("settings.notifPrefs");
  const prefs = useNotifPrefs();
  const hasHydrated = useNotifPrefs((s) => s._hasHydrated);
  const setPrefs = useNotifPrefs((s) => s.setPrefs);
  const { permission, request, supported } = useNotificationPermission();

  if (!hasHydrated) {
    return <p className="text-sm text-muted-foreground">…</p>;
  }

  const enableDesktop = async () => {
    const p = await request();
    if (p === "granted") {
      setPrefs({ desktopEnabled: true });
      notify.success(t("desktopGranted"));
    } else if (p === "denied") {
      setPrefs({ desktopEnabled: false });
      notify.error(t("desktopDenied"));
    }
  };

  const desktopReady = supported && permission === "granted";

  return (
    <div className="space-y-4">
      {/* Sound */}
      <Card className="rounded-xl border border-border/80 shadow-sm">
        <CardHeader className="px-6 pb-4 pt-6">
          <CardTitle className="flex items-center gap-2 text-base font-medium">
            <Volume2 className="size-4 text-[#0F6E56]" />
            {t("soundSection")}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-5 px-6 pb-6 pt-0">
          <Toggle
            id="notif-sound"
            checked={prefs.soundEnabled}
            onChange={(v) => setPrefs({ soundEnabled: v })}
            label={t("soundEnabled")}
            hint={t("soundEnabledHint")}
          />

          <div className="grid gap-4 sm:grid-cols-2">
            <LabeledField label={t("soundChoice")} htmlFor="notif-sound-choice">
              <div className="flex gap-2">
                <select
                  id="notif-sound-choice"
                  className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm disabled:opacity-50"
                  value={prefs.soundId}
                  disabled={!prefs.soundEnabled}
                  onChange={(e) => setPrefs({ soundId: e.target.value as SoundId })}
                >
                  {SOUND_PRESETS.map((s) => (
                    <option key={s.id} value={s.id}>
                      {t(s.labelKey)}
                    </option>
                  ))}
                </select>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  disabled={!prefs.soundEnabled}
                  onClick={() => playSound(prefs.soundId, prefs.volume)}
                >
                  {t("preview")}
                </Button>
              </div>
            </LabeledField>

            <LabeledField label={t("volume")} htmlFor="notif-volume">
              <div className="flex h-10 items-center gap-3">
                <input
                  id="notif-volume"
                  type="range"
                  min={0}
                  max={100}
                  step={5}
                  value={Math.round(prefs.volume * 100)}
                  disabled={!prefs.soundEnabled}
                  onChange={(e) => setPrefs({ volume: Number(e.target.value) / 100 })}
                  className="h-2 w-full cursor-pointer accent-[#0F6E56] disabled:opacity-50"
                />
                <span className="w-10 text-end text-xs tabular-nums text-muted-foreground">
                  {Math.round(prefs.volume * 100)}%
                </span>
              </div>
            </LabeledField>
          </div>
        </CardContent>
      </Card>

      {/* Desktop / Windows popups */}
      <Card className="rounded-xl border border-border/80 shadow-sm">
        <CardHeader className="px-6 pb-4 pt-6">
          <CardTitle className="flex items-center gap-2 text-base font-medium">
            <Bell className="size-4 text-[#0F6E56]" />
            {t("desktopSection")}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4 px-6 pb-6 pt-0">
          <p className="text-xs leading-relaxed text-muted-foreground">{t("desktopHint")}</p>

          {!supported ? (
            <p className="rounded-lg border border-border/80 bg-muted/40 px-4 py-2.5 text-xs">
              {t("desktopUnsupported")}
            </p>
          ) : permission === "denied" ? (
            <p className="rounded-lg border border-[#A32D2D]/30 bg-[#A32D2D]/5 px-4 py-2.5 text-xs text-[#A32D2D]">
              {t("desktopBlocked")}
            </p>
          ) : permission !== "granted" ? (
            <Button
              type="button"
              className="bg-[#0F6E56] hover:bg-[#0c5e46]"
              onClick={enableDesktop}
            >
              {t("enableDesktop")}
            </Button>
          ) : (
            <div className="space-y-4">
              <Toggle
                id="notif-desktop"
                checked={prefs.desktopEnabled}
                onChange={(v) => setPrefs({ desktopEnabled: v })}
                label={t("desktopEnabled")}
                hint={t("desktopEnabledHint")}
              />
              <Button
                type="button"
                variant="outline"
                size="sm"
                disabled={!prefs.desktopEnabled}
                onClick={() => {
                  if (prefs.soundEnabled) playSound(prefs.soundId, prefs.volume);
                  showDesktopNotification({ title: t("testTitle"), body: t("testBody"), force: true });
                  notify.info(t("testToast"));
                }}
              >
                {t("sendTest")}
              </Button>
              {desktopReady ? (
                <p className="text-[11px] text-muted-foreground">{t("desktopFocusNote")}</p>
              ) : null}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Tab badge + in-app toast */}
      <Card className="rounded-xl border border-border/80 shadow-sm">
        <CardHeader className="px-6 pb-4 pt-6">
          <CardTitle className="text-base font-medium">{t("inAppSection")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3 px-6 pb-6 pt-0">
          <Toggle
            id="notif-tab-badge"
            checked={prefs.tabBadgeEnabled}
            onChange={(v) => setPrefs({ tabBadgeEnabled: v })}
            label={t("tabBadge")}
            hint={t("tabBadgeHint")}
          />
          <Toggle
            id="notif-toast"
            checked={prefs.toastEnabled}
            onChange={(v) => setPrefs({ toastEnabled: v })}
            label={t("toast")}
            hint={t("toastHint")}
          />
        </CardContent>
      </Card>
    </div>
  );
}
