'use client'

import { useState } from 'react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Label } from '@/components/ui/label'

type RoleOption = { role_type: string; label: string }

/** Accept / Decline for the token landing (Task 6.4). Asks for a role when the server says so (D6). */
export function RespondButtons({ token, owner }: { token: string; owner: string }) {
  const [pending, setPending] = useState<'accept' | 'decline' | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [roles, setRoles] = useState<RoleOption[] | null>(null)
  const [roleType, setRoleType] = useState('')
  const [done, setDone] = useState<'accept' | 'decline' | null>(null)

  async function respond(decision: 'accept' | 'decline') {
    setPending(decision)
    setError(null)
    try {
      const res = await fetch('/api/auto-participants/respond', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, decision, ...(roleType ? { role_type: roleType } : {}) }),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok) {
        if (res.status === 400 && Array.isArray(json.needs_role) && json.needs_role.length > 0) {
          setRoles(json.needs_role as RoleOption[])
          return
        }
        setError(json.error ?? 'Could not respond to the request.')
        return
      }
      setDone(decision)
    } catch {
      setError('Network error. Please try again.')
    } finally {
      setPending(null)
    }
  }

  if (done) {
    return (
      <div className="text-center text-sm">
        <p className="font-semibold">
          {done === 'accept' ? `You accepted. You will be added automatically to ${owner}'s Trips.` : 'Declined.'}
        </p>
        <Link href="/settings/auto-participants" className="mt-2 inline-block font-semibold underline">
          Open your Auto-Participants settings
        </Link>
      </div>
    )
  }

  return (
    <div className="space-y-3">
      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}
      {roles && (
        <div>
          <Label htmlFor="ap-role">Which of your roles applies to this rule?</Label>
          <select
            id="ap-role"
            className="mt-1 h-9 w-full rounded-lg border bg-white px-2 text-sm"
            value={roleType}
            onChange={(e) => setRoleType(e.target.value)}
          >
            <option value="">Choose a role…</option>
            {roles.map((r) => <option key={r.role_type} value={r.role_type}>{r.label}</option>)}
          </select>
        </div>
      )}
      <Button onClick={() => respond('accept')} className="w-full" size="lg" disabled={!!pending || (!!roles && !roleType)}>
        {pending === 'accept' ? 'Accepting…' : 'Accept'}
      </Button>
      <Button onClick={() => respond('decline')} variant="outline" className="w-full" size="lg" disabled={!!pending}>
        {pending === 'decline' ? 'Declining…' : 'Decline'}
      </Button>
    </div>
  )
}
