'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { canActivateTrip } from '@/lib/domain/status'
import type { Trip, TripRole } from '@/types/db'

/**
 * "Set trip Active" — trip-wide, one push for everyone (2026-09-07, Task 67).
 *
 * Nash: "changing it from waiting for permits into active, it's a one push for
 * all members inside, it's for the entire trip, okay? This is not per user,
 * this is for the entire trip." Open to the carrier, the driver and the
 * broker alike.
 *
 * Always confirms first — Nash [CONFIRMED]: "inform the user that if he will
 * activate the trip, it will be activated for all parties in this order."
 *
 * Shared by the desktop workspace (status row, Section 3) and the driver's
 * Active Trip pane so both surfaces behave identically; `variant` only
 * changes the button styling to match its surroundings.
 */
export function ActivateTripButton({
  trip,
  myRole,
  onDone,
  variant = 'workspace',
}: {
  trip: Trip
  myRole: TripRole | null
  onDone: () => void
  variant?: 'workspace' | 'driver'
}) {
  const [confirming, setConfirming] = useState(false)
  const [pending, setPending] = useState(false)

  if (!myRole || !canActivateTrip(myRole, trip.status)) return null

  async function activate() {
    setPending(true)
    try {
      const res = await fetch(`/api/trips/${trip.id}/status`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ scope: 'trip', to: 'active' }),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok) {
        toast.error(json.error ?? 'Could not activate the trip')
        return
      }
      toast.success('Trip is now Active for everyone on it')
      setConfirming(false)
      onDone()
    } finally {
      setPending(false)
    }
  }

  const trigger =
    variant === 'driver' ? (
      <button
        onClick={() => setConfirming(true)}
        className="w-full rounded-xl bg-amber-brand py-2.5 text-xs font-bold text-navy-900 hover:bg-amber-deep"
        title="Activate this trip for everyone on it"
      >
        ▶ Set trip Active
      </button>
    ) : (
      <Button
        size="sm"
        onClick={() => setConfirming(true)}
        className="bg-[#f5a623] font-bold text-[#0f1b2d] hover:bg-[#d98b06]"
        title="Activate this trip for everyone on it"
      >
        Set trip Active
      </Button>
    )

  return (
    <>
      {trigger}
      <Dialog open={confirming} onOpenChange={(open) => !open && !pending && setConfirming(false)}>
        <DialogContent className="sm:max-w-sm">
          <DialogHeader>
            <DialogTitle>Set this trip Active?</DialogTitle>
          </DialogHeader>
          <p className="text-sm text-neutral-600">
            Activating this trip activates it for <span className="font-semibold">all parties</span>{' '}
            on this order, not just you. Everyone on{' '}
            <span className="font-semibold">
              {trip.origin || 'Origin TBD'} → {trip.destination || 'Destination TBD'}
            </span>{' '}
            will see it as Active.
          </p>
          <div className="flex justify-end gap-2">
            <Button variant="ghost" onClick={() => setConfirming(false)} disabled={pending}>
              Go back
            </Button>
            <Button
              onClick={activate}
              disabled={pending}
              className="bg-[#f5a623] font-bold text-[#0f1b2d] hover:bg-[#d98b06]"
            >
              {pending ? 'Working…' : 'Yes, set Active'}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}
