'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import type { TripCompletion } from '@/lib/domain/status'
import type { Trip } from '@/types/db'

/**
 * Personal trip completion (2026-09-07).
 *
 * Nash: "when you complete the trip in a workspace, it completes it only for
 * you, and it gives an option for others to complete it also if they want to…
 * But I don't want to force close, force complete for all users this trip."
 *
 * Shared by the driver view and the trip workspace so both surfaces behave
 * identically — this is a platform rule, not a driver feature.
 */

async function setPersonalStatus(
  tripId: string,
  to: 'completed' | 'active' | 'dismiss_prompt',
): Promise<string | null> {
  const res = await fetch(`/api/trips/${tripId}/status`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ scope: 'me', to }),
  })
  const json = await res.json().catch(() => ({}))
  return res.ok ? null : (json.error ?? 'Could not update your trip status.')
}

/**
 * "Somebody marked this trip as completed — is that correct?"
 *
 * Nash: "it should work as a trigger for an alert, say, hey, this trip to
 * Tacoma to Macon was marked as completed, is that correct? And then he puts
 * yes or no, and he completes the trip for him, if he does yes."
 */
export function CompletionPrompt({
  trip,
  completion,
  onDone,
  className,
}: {
  trip: Trip
  completion: TripCompletion
  onDone: () => void
  className?: string
}) {
  const [saving, setSaving] = useState(false)
  const who = completion.othersCompleted[0]

  async function answer(to: 'completed' | 'dismiss_prompt') {
    setSaving(true)
    try {
      const error = await setPersonalStatus(trip.id, to)
      if (error) {
        toast.error(error)
        return
      }
      toast.success(to === 'completed' ? 'Completed for you' : 'Kept active for you')
      onDone()
    } finally {
      setSaving(false)
    }
  }

  return (
    <section
      className={
        className ??
        'rounded-2xl border border-amber-300 bg-amber-50 p-4 text-sm shadow-sm'
      }
    >
      <p className="leading-relaxed text-neutral-700">
        This trip{' '}
        <span className="font-bold">
          {trip.origin} → {trip.destination}
        </span>{' '}
        was marked as completed by{' '}
        <span className="font-bold">{who?.name ?? 'someone on this trip'}</span>
        {who?.role ? ` (${who.role})` : ''}. Is that correct?
      </p>
      <div className="mt-2.5 flex gap-2">
        <button
          onClick={() => answer('completed')}
          disabled={saving}
          className="rounded-lg bg-[#0f1b2d] px-3 py-1.5 text-[11px] font-bold text-white disabled:opacity-60"
        >
          Yes, complete it for me
        </button>
        <button
          onClick={() => answer('dismiss_prompt')}
          disabled={saving}
          className="rounded-lg border border-neutral-300 px-3 py-1.5 text-[11px] font-bold text-neutral-600 disabled:opacity-60"
        >
          No
        </button>
      </div>
    </section>
  )
}

/**
 * "Complete for me" — available to EVERY participant, including the driver,
 * who cannot change the trip-wide status. Sits alongside the trip-wide status
 * actions, which stay broker/dispatcher/admin only.
 */
export function PersonalCompletionButton({
  trip,
  completion,
  onDone,
}: {
  trip: Trip
  completion: TripCompletion
  onDone: () => void
}) {
  const [saving, setSaving] = useState(false)
  // Only an actual participant has a row of their own to mark.
  if (!completion.myParticipantId) return null
  const completed = !!completion.completedAt

  async function toggle() {
    setSaving(true)
    try {
      const error = await setPersonalStatus(trip.id, completed ? 'active' : 'completed')
      if (error) {
        toast.error(error)
        return
      }
      toast.success(
        completed
          ? 'Active again for you'
          : 'Completed for you. Everyone else keeps it active until they choose.',
      )
      onDone()
    } finally {
      setSaving(false)
    }
  }

  return (
    <button
      onClick={toggle}
      disabled={saving}
      title={
        completed
          ? 'Make this trip active again for you. Nobody else is affected.'
          : 'Complete this trip for you only. Everyone else is asked, never forced.'
      }
      className="rounded-md border border-neutral-300 px-2.5 py-1 text-xs font-semibold text-neutral-700 transition hover:border-neutral-400 disabled:opacity-60"
    >
      {saving ? '…' : completed ? 'Reactivate for me' : 'Complete for me'}
    </button>
  )
}
