import { useEffect, useState, type FormEvent, type ReactNode } from 'react'
import { createFileRoute, Link, redirect, useRouter } from '@tanstack/react-router'
import { AuthError, login, updateUser, type User } from '@netlify/identity'
import { ArrowLeft, BadgeCheck, CircleUserRound, KeyRound, Mail, MailCheck, MessageSquareText, ShieldCheck } from 'lucide-react'
import { useServerFn } from '@tanstack/react-start'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import { Switch } from '@/components/ui/switch'
import { useIdentity, startGoogleSignIn } from '@/components/IdentityProvider'
import { GoogleIcon, useGoogleAvailable } from '@/components/GoogleButton'
import { getServerUser } from '@/lib/identity.functions'
import { getTextAlerts, recordAccountChange, updateTextAlerts } from '@/lib/settings.functions'
import { cn } from '@/lib/utils'

export const Route = createFileRoute('/settings')({
  beforeLoad: async () => {
    const user = await getServerUser()
    if (!user) throw redirect({ to: '/login' })
  },
  head: () => ({ meta: [{ title: 'Settings — AkotoCreative SMS' }] }),
  component: SettingsPage,
})

const SECTIONS = [
  { id: 'account', label: 'Account', icon: CircleUserRound },
  { id: 'text-alerts', label: 'Text alerts', icon: MessageSquareText },
  { id: 'email', label: 'Change your email', icon: Mail },
  { id: 'password', label: 'Set a password', icon: KeyRound },
  { id: 'google', label: 'Google sign-in', icon: ShieldCheck },
] as const

const dateFormat = new Intl.DateTimeFormat('en-GH', { dateStyle: 'medium' })
const dateTimeFormat = new Intl.DateTimeFormat('en-GH', { dateStyle: 'medium', timeStyle: 'short' })

// Accounts created with Google have no password until the customer sets one here.
const hasPassword = (user: User) => user.provider !== 'google' || Boolean(user.userMetadata?.password_set)
const hasGoogle = (user: User) => user.provider === 'google' || Boolean(user.userMetadata?.google_connected)

function SettingsPage() {
  const { user, ready } = useIdentity()
  return (
    <div className="mx-auto max-w-content px-4 py-12 sm:px-6 lg:py-16">
      <Link
        to="/dashboard"
        className="inline-flex items-center gap-1.5 rounded text-sm font-medium text-muted-foreground transition-colors hover:text-foreground"
      >
        <ArrowLeft className="size-4" aria-hidden /> Back to dashboard
      </Link>
      <p className="mt-6 inline-flex items-center gap-2 font-display text-xs font-bold tracking-[0.22em] text-primary uppercase">
        <span className="h-px w-6 bg-gradient-to-r from-transparent to-primary" aria-hidden />
        Your account
      </p>
      <h1 className="mt-1 text-4xl font-extrabold tracking-tight sm:text-5xl">Settings</h1>
      <p className="mt-2 max-w-xl text-muted-foreground">
        Update your details, text alerts, the email you sign in with, your password and Google sign-in.
      </p>

      <div className="mt-10 grid gap-8 lg:grid-cols-[14rem_1fr] lg:items-start">
        <nav aria-label="Settings sections" className="lg:sticky lg:top-24">
          <ul className="flex gap-2 overflow-x-auto pb-1 lg:flex-col lg:gap-1 lg:pb-0">
            {SECTIONS.map((section) => (
              <li key={section.id} className="shrink-0">
                <a
                  href={`#${section.id}`}
                  className="flex items-center gap-2.5 rounded-full border px-4 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground lg:rounded-xl lg:border-transparent lg:px-3"
                >
                  <section.icon className="size-4 text-primary" aria-hidden />
                  {section.label}
                </a>
              </li>
            ))}
          </ul>
        </nav>

        {!ready || !user ? (
          <div className="grid gap-6">
            {SECTIONS.map((section) => (
              <Skeleton key={section.id} className="h-56 rounded-[1.75rem]" />
            ))}
          </div>
        ) : (
          <div className="grid gap-6">
            <AccountSection user={user} />
            <TextAlertsSection />
            <EmailSection user={user} />
            <PasswordSection user={user} />
            <GoogleSection user={user} />
          </div>
        )}
      </div>
    </div>
  )
}

function Panel({
  id,
  title,
  description,
  children,
}: {
  id: string
  title: string
  description: string
  children: ReactNode
}) {
  return (
    <section
      id={id}
      aria-labelledby={`${id}-heading`}
      className="scroll-mt-24 rounded-[1.75rem] border bg-card p-6 shadow-deep sm:p-8"
    >
      <h2 id={`${id}-heading`} className="text-xl font-bold">
        {title}
      </h2>
      <p className="mt-1 text-sm text-muted-foreground">{description}</p>
      <div className="mt-6">{children}</div>
    </section>
  )
}

function FormMessage({ error, notice }: { error: string | null; notice?: string | null }) {
  if (error)
    return (
      <p role="alert" className="text-sm text-destructive">
        {error}
      </p>
    )
  if (notice)
    return (
      <p role="status" className="text-sm text-primary">
        {notice}
      </p>
    )
  return null
}

function AccountSection({ user }: { user: User }) {
  const router = useRouter()
  const [pending, setPending] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const initial = (user.name || user.email || '?').trim().charAt(0).toUpperCase()
  const methods = [hasPassword(user) && 'Email and password', hasGoogle(user) && 'Google'].filter(Boolean) as string[]

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const name = String(new FormData(event.currentTarget).get('name') ?? '').trim()
    if (name === (user.name ?? '')) return
    setPending(true)
    setError(null)
    try {
      await updateUser({ data: { full_name: name } })
      await router.invalidate()
      toast.success('Your name was saved.')
    } catch {
      setError('We could not save your name. Please try again.')
    } finally {
      setPending(false)
    }
  }

  return (
    <Panel id="account" title="Account" description="How your account appears to you and our support team.">
      <div className="flex items-center gap-4">
        {user.pictureUrl ? (
          <img src={user.pictureUrl} alt="" className="size-14 rounded-2xl object-cover" referrerPolicy="no-referrer" />
        ) : (
          <span
            className="grid size-14 place-items-center rounded-2xl bg-gradient-to-br from-primary to-[oklch(0.45_0.11_165)] font-display text-2xl font-bold text-primary-foreground"
            aria-hidden
          >
            {initial}
          </span>
        )}
        <div className="min-w-0">
          <p className="truncate font-semibold">{user.name || 'No name yet'}</p>
          <p className="truncate text-sm text-muted-foreground">{user.email}</p>
        </div>
      </div>

      <dl className="mt-6 grid gap-4 rounded-2xl bg-secondary/60 p-4 text-sm sm:grid-cols-3">
        <div>
          <dt className="text-muted-foreground">Member since</dt>
          <dd className="mt-0.5 font-medium">{user.createdAt ? dateFormat.format(new Date(user.createdAt)) : '—'}</dd>
        </div>
        <div>
          <dt className="text-muted-foreground">Last sign-in</dt>
          <dd className="mt-0.5 font-medium">
            {user.lastSignInAt ? dateTimeFormat.format(new Date(user.lastSignInAt)) : '—'}
          </dd>
        </div>
        <div>
          <dt className="text-muted-foreground">Sign-in methods</dt>
          <dd className="mt-0.5 font-medium">{methods.join(' · ') || '—'}</dd>
        </div>
      </dl>

      <form onSubmit={submit} className="mt-6 grid gap-3 sm:max-w-md">
        <Label htmlFor="settings-name">Business or your name</Label>
        <div className="flex gap-2">
          <Input
            id="settings-name"
            name="name"
            defaultValue={user.name ?? ''}
            autoComplete="organization"
            maxLength={80}
            required
          />
          <Button type="submit" disabled={pending} className="shrink-0">
            {pending ? 'Saving…' : 'Save'}
          </Button>
        </div>
        <FormMessage error={error} />
      </form>
    </Panel>
  )
}

// Phone number for the automatic texts we send when you sign in or buy credit.
function TextAlertsSection() {
  const load = useServerFn(getTextAlerts)
  const save = useServerFn(updateTextAlerts)
  const [current, setCurrent] = useState<{ phone: string | null; enabled: boolean } | null>(null)
  const [phone, setPhone] = useState('')
  const [enabled, setEnabled] = useState(true)
  const [pending, setPending] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    load()
      .then((data) => {
        setCurrent(data)
        setPhone(data.phone ? `0${data.phone.slice(3)}` : '')
        setEnabled(data.enabled)
      })
      .catch(() => setError('We could not load your text alert settings.'))
  }, [load])

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setPending(true)
    setError(null)
    try {
      const saved = await save({ data: { phone, enabled } })
      setCurrent(saved)
      setPhone(saved.phone ? `0${saved.phone.slice(3)}` : '')
      toast.success(saved.phone && saved.enabled ? 'Text alerts are on.' : 'Your text alert settings were saved.')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'We could not save your settings. Please try again.')
    } finally {
      setPending(false)
    }
  }

  return (
    <Panel
      id="text-alerts"
      title="Text alerts"
      description="We text this number when you sign in and when credit you buy is added. These texts are free and don’t use your credits."
    >
      {!current && !error ? (
        <Skeleton className="h-24 rounded-2xl" />
      ) : (
        <form onSubmit={submit} className="grid gap-5 sm:max-w-md">
          <div className="grid gap-2">
            <Label htmlFor="settings-phone">Mobile number</Label>
            <Input
              id="settings-phone"
              type="tel"
              inputMode="tel"
              autoComplete="tel"
              placeholder="024 123 4567"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              maxLength={30}
            />
            <p className="text-xs text-muted-foreground">
              Ghana numbers only. If you leave this blank, purchase texts go to the mobile money number that paid.
            </p>
          </div>
          <label className="flex items-start justify-between gap-4 rounded-2xl bg-secondary/60 p-4 text-sm">
            <span>
              <span className="font-medium">Send me text alerts</span>
              <span className="mt-0.5 block text-muted-foreground">Sign-in alerts and credit purchase receipts.</span>
            </span>
            <Switch checked={enabled} onCheckedChange={setEnabled} aria-label="Send me text alerts" />
          </label>
          <div className="flex items-center gap-3">
            <Button type="submit" disabled={pending}>
              {pending ? 'Saving…' : 'Save text alerts'}
            </Button>
          </div>
          <FormMessage error={error} />
        </form>
      )}
    </Panel>
  )
}

function EmailSection({ user }: { user: User }) {
  const [pending, setPending] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [sentTo, setSentTo] = useState<string | null>(user.pendingEmail ?? null)

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const form = event.currentTarget
    const email = String(new FormData(form).get('email') ?? '').trim()
    if (email.toLowerCase() === user.email?.toLowerCase()) {
      setError('That is already your email address.')
      return
    }
    setPending(true)
    setError(null)
    try {
      await updateUser({ email })
      setSentTo(email)
      form.reset()
    } catch (err) {
      setError(
        err instanceof AuthError && err.status === 422
          ? 'That email address is not valid or is already used by another account.'
          : 'We could not start the email change. Please try again.',
      )
    } finally {
      setPending(false)
    }
  }

  return (
    <Panel
      id="email"
      title="Change your email"
      description="This is the address you sign in with and where we send receipts and account emails."
    >
      <p className="text-sm">
        Current email: <strong className="font-semibold">{user.email}</strong>
      </p>
      {sentTo && (
        <div className="mt-4 flex gap-3 rounded-2xl border border-primary/25 bg-primary/5 p-4 text-sm" role="status">
          <MailCheck className="mt-0.5 size-5 shrink-0 text-primary" aria-hidden />
          <p>
            We sent a confirmation link to <strong>{sentTo}</strong>. Open it in this browser while you are signed in to
            finish the change. Until then, keep signing in with your current email.
          </p>
        </div>
      )}
      <form onSubmit={submit} className="mt-6 grid gap-3 sm:max-w-md">
        <Label htmlFor="settings-email">New email address</Label>
        <div className="flex gap-2">
          <Input id="settings-email" name="email" type="email" autoComplete="email" maxLength={254} required />
          <Button type="submit" disabled={pending} className="shrink-0">
            {pending ? 'Sending…' : 'Change email'}
          </Button>
        </div>
        <FormMessage error={error} />
      </form>
    </Panel>
  )
}

function PasswordSection({ user }: { user: User }) {
  const existing = hasPassword(user)
  const [pending, setPending] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [notice, setNotice] = useState<string | null>(null)

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const form = event.currentTarget
    const fields = new FormData(form)
    const current = String(fields.get('current') ?? '')
    const password = String(fields.get('password') ?? '')
    if (password !== String(fields.get('confirm') ?? '')) {
      setError('The new passwords don’t match.')
      return
    }
    if (existing && current === password) {
      setError('Choose a password that is different from your current one.')
      return
    }
    setPending(true)
    setError(null)
    setNotice(null)
    try {
      if (existing && user.email) {
        try {
          await login(user.email, current)
        } catch (err) {
          setError(
            err instanceof AuthError && (err.status === 400 || err.status === 401)
              ? 'Your current password is incorrect.'
              : 'We could not check your current password. Please try again.',
          )
          return
        }
      }
      await updateUser({ password, data: { password_set: true } })
      await recordAccountChange({ data: { change: 'password' } }).catch(() => undefined)
      form.reset()
      setNotice(existing ? 'Password changed.' : 'Password set. You can now also sign in with your email and password.')
    } catch (err) {
      setError(
        err instanceof AuthError && err.status === 422
          ? 'Use a password of at least 8 characters.'
          : 'We could not save your password. Please try again.',
      )
    } finally {
      setPending(false)
    }
  }

  return (
    <Panel
      id="password"
      title={existing ? 'Change your password' : 'Set a password'}
      description={
        existing
          ? 'Use at least 8 characters. Signing in elsewhere keeps working until those sessions expire.'
          : 'You signed up with Google. Add a password so you can also sign in with your email address.'
      }
    >
      <form onSubmit={submit} className="grid gap-4 sm:max-w-md">
        {existing && (
          <div className="grid gap-2">
            <Label htmlFor="settings-current">Current password</Label>
            <Input id="settings-current" name="current" type="password" autoComplete="current-password" required />
          </div>
        )}
        <div className="grid gap-2">
          <Label htmlFor="settings-password">New password</Label>
          <Input
            id="settings-password"
            name="password"
            type="password"
            minLength={8}
            autoComplete="new-password"
            required
          />
        </div>
        <div className="grid gap-2">
          <Label htmlFor="settings-confirm">Confirm new password</Label>
          <Input
            id="settings-confirm"
            name="confirm"
            type="password"
            minLength={8}
            autoComplete="new-password"
            required
          />
        </div>
        <FormMessage error={error} notice={notice} />
        <Button type="submit" disabled={pending} className="justify-self-start">
          {pending ? 'Saving…' : existing ? 'Change password' : 'Set password'}
        </Button>
      </form>
    </Panel>
  )
}

function GoogleSection({ user }: { user: User }) {
  const available = useGoogleAvailable()
  const connected = hasGoogle(user)

  return (
    <Panel id="google" title="Google sign-in" description="Sign in with one tap using your Google account.">
      <div className="flex flex-wrap items-center justify-between gap-4 rounded-2xl border p-4">
        <div className="flex items-center gap-3">
          <span className="grid size-11 place-items-center rounded-xl border bg-background">
            <GoogleIcon className="size-5" />
          </span>
          <div>
            <p className="font-semibold">Google</p>
            <p className="text-sm text-muted-foreground">
              {connected ? `Connected to ${user.email}` : `Use the Google account for ${user.email}`}
            </p>
          </div>
        </div>
        {available === null ? (
          <Skeleton className="h-9 w-32 rounded-md" />
        ) : connected ? (
          <Badge className={cn('gap-1 bg-primary/10 text-primary ring-1 ring-primary/20 hover:bg-primary/10')}>
            <BadgeCheck className="size-3.5" aria-hidden /> Connected
          </Badge>
        ) : available ? (
          <Button variant="outline" onClick={() => startGoogleSignIn(user.id)}>
            <GoogleIcon className="size-4" /> Connect Google
          </Button>
        ) : (
          <Badge variant="outline">Not available yet</Badge>
        )}
      </div>
      <p className="mt-4 text-sm text-muted-foreground">
        {available === false
          ? 'Google sign-in isn’t switched on for AkotoCreative SMS yet. You can keep signing in with your email and password.'
          : connected
            ? 'Choose “Continue with Google” on the sign-in page. If you change your email, sign in with a Google account that uses the new address.'
            : 'Google connects to your account when its email address matches yours. You’ll be sent to Google and brought straight back here.'}
      </p>
    </Panel>
  )
}
