'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'

/**
 * Profile → Account (Nash, 2026-09-23): "I should have the ability to change
 * my email — put the new email, send the verify, click the link and it
 * changes. For the phone number there is no need for any validation."
 */
export function AccountCard({ email, pendingEmail, phone, canEdit }: { email: string; pendingEmail: string | null; phone: string | null; canEdit: boolean }) {
  const router = useRouter()
  const [nextEmail, setNextEmail] = useState('')
  const [nextPhone, setNextPhone] = useState(phone ?? '')
  const [busy, setBusy] = useState<'email' | 'phone' | 'cancel' | null>(null)

  async function call(body: Record<string, unknown>) {
    const r = await fetch('/api/account', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
    const json = await r.json().catch(() => ({}))
    if (!r.ok) throw new Error(json.error ?? 'Something went wrong.')
    return json as { status?: string; pending?: string; phone?: string | null }
  }
  async function changeEmail() {
    setBusy('email')
    try {
      const j = await call({ op: 'change_email', email: nextEmail })
      toast.success(j.status === 'sent' ? `Verification link sent to ${j.pending}. Open it to switch your sign-in email.` : `Verification recorded for ${j.pending} — email delivery is not switched on in this environment.`)
      setNextEmail('')
      router.refresh()
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Could not start the change.') } finally { setBusy(null) }
  }
  async function cancel() {
    setBusy('cancel')
    try { await call({ op: 'cancel_email_change' }); toast.success('Email change cancelled.'); router.refresh() } catch (e) { toast.error(e instanceof Error ? e.message : 'Could not cancel.') } finally { setBusy(null) }
  }
  async function savePhone() {
    setBusy('phone')
    try {
      const j = await call({ op: 'phone', phone: nextPhone })
      toast.success(j.phone ? `Phone saved: ${j.phone}` : 'Phone removed.')
      router.refresh()
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Could not save the phone.') } finally { setBusy(null) }
  }

  return (
    <Card className="mt-6" id="account">
      <CardHeader><CardTitle className="text-base">Sign-in email &amp; phone</CardTitle></CardHeader>
      <CardContent className="space-y-6">
        <section>
          <p className="text-xs font-bold uppercase tracking-wide text-neutral-500">Sign-in email</p>
          <p className="mt-1 text-sm">You sign in with <span className="font-semibold">{email}</span>.</p>
          {pendingEmail && (
            <div className="mt-2 flex flex-wrap items-center gap-2 rounded-lg bg-amber-50 p-3 text-xs text-amber-900">
              <span>Verification pending for <span className="font-semibold">{pendingEmail}</span> — open the link we emailed there. The change happens only when you click it.</span>
              <Button size="sm" variant="outline" disabled={busy !== null || !canEdit} onClick={cancel}>{busy === 'cancel' ? 'Cancelling…' : 'Cancel'}</Button>
            </div>
          )}
          <div className="mt-3 flex flex-wrap items-end gap-2">
            <label className="text-xs font-semibold text-neutral-600">New sign-in email<Input value={nextEmail} onChange={(e) => setNextEmail(e.target.value)} type="email" placeholder="you@company.com" className="mt-1 w-64" disabled={!canEdit} /></label>
            <Button size="sm" disabled={busy !== null || !canEdit || !nextEmail.includes('@')} onClick={changeEmail}>{busy === 'email' ? 'Sending…' : 'Send verification link'}</Button>
          </div>
          <p className="mt-2 text-[11px] text-neutral-500">We email a one-time link to the new address. Nothing changes until you open it. Your delivery address follows unless you set a different one in Settings → Email.</p>
        </section>
        <section>
          <p className="text-xs font-bold uppercase tracking-wide text-neutral-500">Phone</p>
          <div className="mt-2 flex flex-wrap items-end gap-2">
            <label className="text-xs font-semibold text-neutral-600">Phone number<Input value={nextPhone} onChange={(e) => setNextPhone(e.target.value)} type="tel" placeholder="(555) 555-0100" className="mt-1 w-64" disabled={!canEdit} /></label>
            <Button size="sm" variant="outline" disabled={busy !== null || !canEdit || nextPhone.trim() === (phone ?? '')} onClick={savePhone}>{busy === 'phone' ? 'Saving…' : 'Save phone'}</Button>
          </div>
          <p className="mt-2 text-[11px] text-neutral-500">Saved as typed, no verification. Shown to the people you work with on a trip.</p>
        </section>
        {!canEdit && <p className="rounded-lg bg-neutral-50 p-3 text-xs text-neutral-500">You are viewing another account. Switch back to your own account to change its details.</p>}
      </CardContent>
    </Card>
  )
}
