"use client"

import { SettingsSectionHeader } from "@/components/gmail/settings/settings-section-header"
import { SettingsSyncBanner } from "@/components/gmail/settings/settings-sync-banner"
import { useMailSettings } from "@/lib/api/hooks/use-mail-settings"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"
import { requestDesktopNotificationPermission } from "@/lib/notifications/desktop-notifications"

export function NotificationsSettingsSection() {
  const { isFetching, isError, refetch } = useMailSettings()
  const desktopNewMail = useMailSettingsStore((s) => s.desktopNewMail)
  const desktopMentions = useMailSettingsStore((s) => s.desktopMentions)
  const emailDigest = useMailSettingsStore((s) => s.emailDigest)
  const soundEnabled = useMailSettingsStore((s) => s.soundEnabled)
  const setDesktopNewMail = useMailSettingsStore((s) => s.setDesktopNewMail)
  const setDesktopMentions = useMailSettingsStore((s) => s.setDesktopMentions)
  const setEmailDigest = useMailSettingsStore((s) => s.setEmailDigest)
  const setSoundEnabled = useMailSettingsStore((s) => s.setSoundEnabled)

  return (
    <>
      <SettingsSectionHeader
        title="Notifications"
        description="Préférences d'alertes synchronisées avec votre compte Ultimail."
      />
      <SettingsSyncBanner isFetching={isFetching} isError={isError} onRetry={() => refetch()} />

      <div className="space-y-4">
        <ToggleRow
          label="Nouveaux messages (bureau)"
          checked={desktopNewMail}
          onChange={async (checked) => {
            if (checked) await requestDesktopNotificationPermission()
            setDesktopNewMail(checked)
          }}
        />
        <ToggleRow
          label="Mentions et réponses"
          checked={desktopMentions}
          onChange={async (checked) => {
            if (checked) await requestDesktopNotificationPermission()
            setDesktopMentions(checked)
          }}
        />
        <ToggleRow
          label="Résumé quotidien par e-mail"
          checked={emailDigest}
          onChange={setEmailDigest}
        />
        <ToggleRow
          label="Son de notification"
          checked={soundEnabled}
          onChange={setSoundEnabled}
        />
      </div>
    </>
  )
}

function ToggleRow({
  label,
  checked,
  onChange,
}: {
  label: string
  checked: boolean
  onChange: (checked: boolean) => void | Promise<void>
}) {
  return (
    <label className="flex cursor-pointer items-center justify-between gap-4 rounded-lg border border-border px-4 py-3">
      <span className="text-sm text-foreground">{label}</span>
      <input
        type="checkbox"
        checked={checked}
        onChange={(e) => onChange(e.target.checked)}
        className="size-4 accent-[#1a73e8]"
      />
    </label>
  )
}
