'use client'

/**
 * Notifications tab of the Form Schema drawer. Persists per-form notification
 * settings (recipients, reply-to, subject/message templates, field inclusion,
 * autoresponder). Actual email/webhook delivery + the "send test" action are
 * wired in a later phase (PR 6); this panel owns the configuration only.
 */
import { useEffect, useState } from 'react'
import * as Switch from '@radix-ui/react-switch'
import { toast } from 'sonner'
import {
  fetchNotificationSettings,
  updateNotificationSettings,
  type FormNotificationSettings,
} from '../../lib/forms-service.js'
import { emitFormsChanged } from '../../lib/forms-events.js'
import { FormsErrorState, FormsLoading, btnPrimary } from './primitives.js'

const inputCls =
  'border-border bg-input-background text-foreground focus-visible:ring-ring w-full rounded-md border px-2.5 py-1.5 text-sm focus-visible:ring-2 focus-visible:outline-none'

export function NotificationsPanel({
  formId,
  onChanged,
}: {
  formId: string
  /** Called after a successful save so the list can refresh the notify state. */
  onChanged?: () => void
}) {
  const [settings, setSettings] = useState<FormNotificationSettings | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    let active = true
    setLoading(true)
    setError(null)
    fetchNotificationSettings(formId)
      .then((s) => {
        if (active) setSettings(s)
      })
      .catch((e: unknown) => {
        if (active)
          setError(e instanceof Error ? e.message : 'Failed to load notification settings')
      })
      .finally(() => {
        if (active) setLoading(false)
      })
    return () => {
      active = false
    }
  }, [formId])

  function patch(p: Partial<FormNotificationSettings>) {
    setSettings((cur) => (cur ? { ...cur, ...p } : cur))
  }

  async function save() {
    if (!settings) return
    setSaving(true)
    const res = await updateNotificationSettings(formId, settings)
    setSaving(false)
    if (res.error) {
      toast.error(res.error)
      return
    }
    if (res.data) setSettings(res.data)
    toast.success('Notification settings saved.')
    emitFormsChanged()
    onChanged?.()
  }

  if (loading) return <FormsLoading label="Loading notification settings…" />
  if (error) return <FormsErrorState message={error} />
  if (!settings) return null

  return (
    <div className="space-y-4">
      <ToggleRow
        label="Enable notifications"
        help="Email the recipients below when a new entry arrives."
        checked={settings.enabled}
        onChange={(v) => patch({ enabled: v })}
      />

      <fieldset
        disabled={!settings.enabled}
        className="space-y-4 transition-opacity disabled:opacity-50"
      >
        <Field label="Recipients" hint="Comma-separated email addresses">
          <input
            type="text"
            value={settings.recipients.join(', ')}
            onChange={(e) =>
              patch({
                recipients: e.target.value
                  .split(',')
                  .map((s) => s.trim())
                  .filter(Boolean),
              })
            }
            placeholder="team@example.com"
            className={inputCls}
          />
        </Field>

        <Field label="Reply-to field key" hint="Field whose value is used as the reply-to address">
          <input
            type="text"
            value={settings.replyToFieldKey ?? ''}
            onChange={(e) => patch({ replyToFieldKey: e.target.value || null })}
            placeholder="email"
            className={inputCls}
          />
        </Field>

        <Field label="Subject template">
          <input
            type="text"
            value={settings.subjectTemplate ?? ''}
            onChange={(e) => patch({ subjectTemplate: e.target.value })}
            placeholder="New submission from {{name}}"
            className={inputCls}
          />
        </Field>

        <Field label="Message template">
          <textarea
            rows={3}
            value={settings.messageTemplate ?? ''}
            onChange={(e) => patch({ messageTemplate: e.target.value })}
            className={inputCls}
          />
        </Field>

        <ToggleRow
          label="Include all fields"
          help="Append every submitted field to the notification body."
          checked={settings.includeFields ?? true}
          onChange={(v) => patch({ includeFields: v })}
        />
        <ToggleRow
          label="Exclude sensitive fields"
          help="Omit fields marked as sensitive/PII from the email."
          checked={settings.excludeSensitiveFields ?? false}
          onChange={(v) => patch({ excludeSensitiveFields: v })}
        />

        <div className="border-border border-t pt-4">
          <ToggleRow
            label="Auto-response email"
            help="Send a confirmation email back to the submitter."
            checked={settings.autoresponderEnabled ?? false}
            onChange={(v) => patch({ autoresponderEnabled: v })}
          />
          {settings.autoresponderEnabled && (
            <div className="mt-3 space-y-3">
              <Field label="Auto-response subject">
                <input
                  type="text"
                  value={settings.autoresponderSubject ?? ''}
                  onChange={(e) => patch({ autoresponderSubject: e.target.value })}
                  className={inputCls}
                />
              </Field>
              <Field label="Auto-response body">
                <textarea
                  rows={3}
                  value={settings.autoresponderBody ?? ''}
                  onChange={(e) => patch({ autoresponderBody: e.target.value })}
                  className={inputCls}
                />
              </Field>
            </div>
          )}
        </div>
      </fieldset>

      <p className="text-muted-foreground text-xs">
        Email &amp; webhook delivery (including the test action) is wired in an upcoming release.
        Settings saved here apply automatically once delivery is enabled.
      </p>

      <div className="flex justify-end">
        <button className={btnPrimary} onClick={save} disabled={saving}>
          {saving ? 'Saving…' : 'Save notifications'}
        </button>
      </div>
    </div>
  )
}

function ToggleRow({
  label,
  help,
  checked,
  onChange,
}: {
  label: string
  help: string
  checked: boolean
  onChange: (v: boolean) => void
}) {
  return (
    <div className="flex items-center justify-between gap-3">
      <span className="min-w-0">
        <span className="text-foreground block text-sm font-medium">{label}</span>
        <span className="text-muted-foreground block text-sm">{help}</span>
      </span>
      <Switch.Root
        checked={checked}
        onCheckedChange={onChange}
        aria-label={label}
        className="bg-destructive data-[state=checked]:bg-success focus-visible:ring-ring relative h-[18px] w-8 shrink-0 rounded-full transition-colors focus-visible:ring-2 focus-visible:outline-none"
      >
        <Switch.Thumb className="bg-background block h-3.5 w-3.5 translate-x-0.5 rounded-full shadow-sm transition-transform data-[state=checked]:translate-x-[14px]" />
      </Switch.Root>
    </div>
  )
}

function Field({
  label,
  hint,
  children,
}: {
  label: string
  hint?: string
  children: React.ReactNode
}) {
  return (
    <label className="block">
      <span className="text-foreground mb-1 block text-sm font-medium">{label}</span>
      {children}
      {hint && <span className="text-muted-foreground mt-1 block text-xs">{hint}</span>}
    </label>
  )
}
