'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { EmailPreferencesForm } from '@/components/app/email-preferences-form'
import type { EmailPreferences } from '@/lib/domain/email-policy'

/** Settings → Email (2026-09-22): the delivery address and the category preferences. */
export function EmailAddressCard({ email, deliveryEmail, pendingEmail, suppressed }: { email: string; deliveryEmail: string | null; pendingEmail: string | null; suppressed: { reason: string; temporary: boolean } | null }) {
  const router = useRouter()
  const [next, setNext] = useState('')
  const [busy, setBusy] = useState(false)
  const current = deliveryEmail || email
  async function change() {
    setBusy(true)
    try {
      const r = await fetch('/api/email/address', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: next }) })
      const json = await r.json().catch(() => ({}))
      if (!r.ok) throw new Error(json.error ?? 'Could not send the verification email.')
      toast.success(json.status === 'sent' ? `Verification email sent to ${next.trim()}.` : `Verification recorded for ${next.trim()} — email delivery is not switched on in this environment.`)
      setNext('')
      router.refresh()
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Something went wrong.')
    } finally {
      setBusy(false)
    }
  }
  async function reset() {
    setBusy(true)
    try {
      const r = await fetch('/api/email/address', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ reset: true }) })
      const json = await r.json().catch(() => ({}))
      if (!r.ok) throw new Error(json.error ?? 'Could not reset the delivery address.')
      toast.success(`Delivering to ${email} again.`)
      router.refresh()
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Something went wrong.')
    } finally {
      setBusy(false)
    }
  }
  return (
    <Card className="mt-6" id="email">
      <CardContent className="pt-6">
        <h3 className="text-sm font-bold uppercase tracking-wide text-neutral-500">Email · delivery address</h3>
        <p className="mt-2 text-sm">HeavyHaul Agent sends to <span className="font-semibold">{current}</span>{deliveryEmail && deliveryEmail !== email ? <span className="text-xs text-neutral-500"> (your sign-in email is {email})</span> : <span className="text-xs text-neutral-500"> — your sign-in email, the default</span>}</p>
        {deliveryEmail && deliveryEmail !== email && <button onClick={reset} disabled={busy} className="mt-1 text-xs font-semibold underline">Deliver to my sign-in email instead</button>}
        {suppressed && (
          <p className="mt-2 rounded-lg bg-red-50 p-3 text-xs text-red-800">
            <span className="font-bold">This address could not receive messages</span> ({suppressed.reason.replace(/_/g, ' ')}){suppressed.temporary ? ' — delivery is paused for a few days.' : ' — delivery has stopped.'} Enter a working address below and verify it.
          </p>
        )}
        {pendingEmail && <p className="mt-2 text-xs text-amber-800">Verification pending for {pendingEmail} — open the link we emailed there.</p>}
        <div className="mt-3 flex flex-wrap items-end gap-2">
          <label className="text-xs font-semibold text-neutral-600">New address<Input value={next} onChange={(e) => setNext(e.target.value)} type="email" placeholder="you@company.com" className="mt-1 w-64" /></label>
          <Button size="sm" disabled={busy || !next.includes('@')} onClick={change}>{busy ? 'Sending…' : 'Send verification'}</Button>
        </div>
        <p className="mt-2 text-[11px] text-neutral-500">Your sign-in stays the same; only where we deliver changes, after you open the verification link.</p>
      </CardContent>
    </Card>
  )
}

export function EmailPreferencesCard({ prefs, available }: { prefs: EmailPreferences; available: boolean }) {
  return (
    <Card className="mt-6">
      <CardContent className="pt-6">
        <h3 className="text-sm font-bold uppercase tracking-wide text-neutral-500">Email · preferences</h3>
        <p className="mt-1 mb-4 text-xs text-neutral-500">Choose what we send. Account, security and company-verification messages are required to run your account.</p>
        <EmailPreferencesForm initial={prefs} hasAccount available={available} />
      </CardContent>
    </Card>
  )
}
