'use client'

import { AlertTriangle, CheckCircle2, Info, KeyRound, Loader2, Send } from 'lucide-react'
import { useId } from 'react'

import { SettingsCard, SettingsSaveBar, SettingsToggleRow } from './components.js'
import {
  EMAIL_PROVIDER_OPTIONS,
  useEmailSettings,
  type EmailProviderKey,
  type UseEmailSettings,
} from './useEmailSettings.js'

const INPUT_CLASS =
  'w-full max-w-md rounded-md border border-border bg-input-background px-3 py-2 text-base text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60'
const LABEL_CLASS = 'mb-1 block text-sm font-medium text-foreground'
const HELP_CLASS = 'mt-1 text-sm text-muted-foreground'

const PROVIDER_LABEL: Record<EmailProviderKey, string> = {
  resend: 'Resend',
  smtpcom: 'SMTP.com',
  ses: 'Amazon SES',
  smtp: 'SMTP server',
}

function Field({
  id,
  label,
  help,
  children,
}: {
  id: string
  label: string
  help?: string
  children: React.ReactNode
}) {
  return (
    <div>
      <label htmlFor={id} className={LABEL_CLASS}>
        {label}
      </label>
      {children}
      {help && <p className={HELP_CLASS}>{help}</p>}
    </div>
  )
}

function SecretField({
  id,
  label,
  value,
  onChange,
  disabled,
  hasStored,
  last4,
  help,
}: {
  id: string
  label: string
  value: string
  onChange: (v: string) => void
  disabled: boolean
  hasStored: boolean
  last4?: string
  help?: string
}) {
  return (
    <Field
      id={id}
      label={label}
      help={
        hasStored && !value
          ? `A ${label.toLowerCase()} is saved${last4 ? ` (ends in ${last4})` : ''}. Enter a new value to replace it.`
          : help
      }
    >
      <div className="relative max-w-md">
        <KeyRound
          size={16}
          aria-hidden="true"
          className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 -translate-y-1/2"
        />
        <input
          id={id}
          type="password"
          autoComplete="off"
          value={value}
          disabled={disabled}
          onChange={(e) => onChange(e.target.value)}
          placeholder={hasStored ? `••••••••${last4 ? last4 : ''}` : 'Enter value'}
          className={`${INPUT_CLASS} pl-9`}
        />
      </div>
    </Field>
  )
}

function Notice({
  tone,
  children,
}: {
  tone: 'info' | 'warning' | 'success' | 'error'
  children: React.ReactNode
}) {
  const toneClass =
    tone === 'warning'
      ? 'border-warning/30 bg-warning/10 text-warning'
      : tone === 'success'
        ? 'border-success/30 bg-success/10 text-success'
        : tone === 'error'
          ? 'border-destructive/30 bg-destructive/10 text-destructive'
          : 'border-border bg-muted text-muted-foreground'
  const Icon = tone === 'success' ? CheckCircle2 : tone === 'info' ? Info : AlertTriangle
  return (
    <div
      role="status"
      aria-live="polite"
      className={`flex items-start gap-2.5 rounded-lg border p-3 text-sm ${toneClass}`}
    >
      <Icon size={16} className="mt-0.5 shrink-0" aria-hidden="true" />
      <div className="min-w-0">{children}</div>
    </div>
  )
}

function ProviderFields({ s, canEdit }: { s: UseEmailSettings; canEdit: boolean }) {
  const ids = {
    from: useId(),
    apiKey: useId(),
    channel: useId(),
    region: useId(),
    host: useId(),
    port: useId(),
    user: useId(),
    pass: useId(),
  }
  const { form, setField, stored } = s
  const disabled = !canEdit
  if (form.provider === '') return null

  const sameProvider = stored.sameProvider

  return (
    <div className="space-y-4">
      <Field
        id={ids.from}
        label="Sender address"
        help="The From address for invitations, password resets, and form notifications. Must be verified with your provider."
      >
        <input
          id={ids.from}
          type="email"
          value={form.from}
          disabled={disabled}
          onChange={(e) => setField('from', e.target.value)}
          placeholder="noreply@yoursite.com"
          className={INPUT_CLASS}
        />
      </Field>

      {(form.provider === 'resend' || form.provider === 'smtpcom') && (
        <SecretField
          id={ids.apiKey}
          label="API key"
          value={form.apiKey}
          onChange={(v) => setField('apiKey', v)}
          disabled={disabled}
          hasStored={sameProvider && stored.hasApiKey}
          last4={stored.apiKeyLast4}
          help={
            form.provider === 'resend'
              ? 'Your Resend API key (starts with re_). Stored encrypted.'
              : 'Your SMTP.com v4 API key. Stored encrypted.'
          }
        />
      )}

      {form.provider === 'smtpcom' && (
        <Field
          id={ids.channel}
          label="Sender channel"
          help="Optional. The SMTP.com channel to send through; defaults to your account default."
        >
          <input
            id={ids.channel}
            type="text"
            value={form.channel}
            disabled={disabled}
            onChange={(e) => setField('channel', e.target.value)}
            placeholder="default"
            className={INPUT_CLASS}
          />
        </Field>
      )}

      {form.provider === 'ses' && (
        <Field
          id={ids.region}
          label="AWS region"
          help="SES sends with your deployment's AWS credentials (env vars or IAM role); only the region is stored here."
        >
          <input
            id={ids.region}
            type="text"
            value={form.region}
            disabled={disabled}
            onChange={(e) => setField('region', e.target.value)}
            placeholder="us-east-1"
            className={INPUT_CLASS}
          />
        </Field>
      )}

      {form.provider === 'smtp' && (
        <>
          <div className="grid max-w-md grid-cols-1 gap-4 sm:grid-cols-[1fr_8rem]">
            <Field id={ids.host} label="Host">
              <input
                id={ids.host}
                type="text"
                value={form.host}
                disabled={disabled}
                onChange={(e) => setField('host', e.target.value)}
                placeholder="smtp.example.com"
                className={INPUT_CLASS}
              />
            </Field>
            <Field id={ids.port} label="Port">
              <input
                id={ids.port}
                type="text"
                inputMode="numeric"
                value={form.port}
                disabled={disabled}
                onChange={(e) => setField('port', e.target.value.replace(/[^\d]/g, ''))}
                placeholder="587"
                className={INPUT_CLASS}
              />
            </Field>
          </div>
          <div className="max-w-md">
            <SettingsToggleRow
              label="Implicit TLS"
              description="Enable for port 465. Leave off for STARTTLS (port 587, the common default)."
              checked={form.secure}
              disabled={disabled}
              onChange={(v) => setField('secure', v)}
            />
          </div>
          <Field
            id={ids.user}
            label="Username"
            help="Leave blank for relays that authenticate by IP address."
          >
            <input
              id={ids.user}
              type="text"
              autoComplete="off"
              value={form.smtpUser}
              disabled={disabled}
              onChange={(e) => setField('smtpUser', e.target.value)}
              className={INPUT_CLASS}
            />
          </Field>
          <SecretField
            id={ids.pass}
            label="Password"
            value={form.smtpPass}
            onChange={(v) => setField('smtpPass', v)}
            disabled={disabled}
            hasStored={sameProvider && stored.hasSmtpPass}
            help="Stored encrypted."
          />
        </>
      )}
    </div>
  )
}

export function EmailSettingsTab({ role }: { role?: string }) {
  const canEdit = String(role ?? '').toUpperCase() === 'ADMIN'
  const s = useEmailSettings(canEdit)
  const providerGroupId = useId()

  if (s.loading) {
    return (
      <div className="flex h-48 items-center justify-center" aria-label="Loading email settings">
        <Loader2 className="text-brand h-6 w-6 animate-spin" aria-hidden="true" />
      </div>
    )
  }

  if (s.loadError) {
    return (
      <div
        role="alert"
        className="border-destructive/30 bg-destructive/10 text-destructive flex items-center gap-3 rounded-lg border p-3 text-sm"
      >
        <AlertTriangle size={20} className="shrink-0" aria-hidden="true" />
        <span className="flex-1">{s.loadError}</span>
        <button
          onClick={s.reload}
          className="border-destructive/40 rounded-md border px-3 py-1 transition-colors hover:opacity-80"
        >
          Retry
        </button>
      </div>
    )
  }

  const configured = s.form.provider !== ''

  return (
    <div className="space-y-4">
      {!canEdit && (
        <Notice tone="info">
          You have read-only access to email settings. Ask an administrator to make changes.
        </Notice>
      )}

      {s.platformAdapter && (
        <Notice tone="info">
          A platform email adapter is configured in code (<code>platform.email</code>); it takes
          precedence over the settings on this page.
        </Notice>
      )}

      {!s.platformAdapter && s.env.provider && (
        <Notice tone="info">
          Environment variables currently configure{' '}
          <strong>{PROVIDER_LABEL[s.env.provider]}</strong>. Settings saved here take precedence
          over the environment configuration.
        </Notice>
      )}

      {configured && !s.factoryAvailable && (
        <Notice tone="warning">
          Sending with these settings requires the email plugin. Add <code>emailPlugin()</code> from{' '}
          <code>@actuate-media/plugin-email</code> to your <code>actuate.config.ts</code>.
        </Notice>
      )}

      <SettingsCard
        title="Email delivery"
        description="Transactional email provider for invitations, password resets, and form notifications. Credentials are encrypted at rest."
        actions={
          <button
            type="button"
            onClick={() => void s.sendTest()}
            disabled={s.testing || s.dirty || (!configured && !s.env.senderActive)}
            title={s.dirty ? 'Save your changes before sending a test.' : undefined}
            className="border-border text-foreground hover:bg-accent inline-flex items-center gap-2 rounded-md border px-3 py-1.5 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50"
          >
            {s.testing ? (
              <Loader2 size={14} className="animate-spin" aria-hidden="true" />
            ) : (
              <Send size={14} aria-hidden="true" />
            )}
            Send test email
          </button>
        }
      >
        <div className="space-y-5">
          <div>
            <span id={providerGroupId} className={LABEL_CLASS}>
              Provider
            </span>
            <div
              role="radiogroup"
              aria-labelledby={providerGroupId}
              className="flex flex-wrap gap-2"
            >
              {[{ value: '' as const, label: 'None' }, ...EMAIL_PROVIDER_OPTIONS].map((opt) => {
                const active = s.form.provider === opt.value
                return (
                  <button
                    key={opt.value || 'none'}
                    type="button"
                    role="radio"
                    aria-checked={active}
                    disabled={!canEdit}
                    onClick={() => s.setField('provider', opt.value)}
                    className={`rounded-md border px-3 py-1.5 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
                      active
                        ? 'border-brand bg-brand/10 text-brand font-medium'
                        : 'border-border text-muted-foreground hover:text-foreground hover:bg-accent'
                    }`}
                  >
                    {opt.label}
                  </button>
                )
              })}
            </div>
            {!configured && (
              <p className={HELP_CLASS}>
                {s.env.senderActive
                  ? 'No provider is configured here, but an environment-configured sender is active.'
                  : 'No email provider configured. Transactional email (invites, password resets, form notifications) is skipped.'}
              </p>
            )}
          </div>

          <ProviderFields s={s} canEdit={canEdit} />

          {s.testResult && (
            <Notice tone={s.testResult.success ? 'success' : 'error'}>
              {s.testResult.message}
            </Notice>
          )}
          {!s.testResult && s.lastTest.status && (
            <p className="text-muted-foreground text-sm">
              Last test {s.lastTest.status === 'success' ? 'succeeded' : `failed`}
              {s.lastTest.testedAt ? ` on ${new Date(s.lastTest.testedAt).toLocaleString()}` : ''}
              {s.lastTest.status === 'failed' && s.lastTest.error ? ` — ${s.lastTest.error}` : ''}
            </p>
          )}
        </div>

        {s.saveError && (
          <p className="text-destructive mt-4 text-sm" role="alert">
            {s.saveError}
          </p>
        )}
      </SettingsCard>

      <SettingsSaveBar
        dirty={s.dirty}
        canEdit={canEdit}
        hasErrors={false}
        saveState={s.saveState}
        onSave={() => void s.save()}
        onReset={s.reset}
      />
    </div>
  )
}
