import React, { useEffect, useId, useMemo, useState } from 'react'
import { ArrowLeft, Calendar, Check, ChevronRight, ListPlus, Loader2, MapPin, Map as MapIcon, Search, Sparkles } from 'lucide-react'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { INPUT } from '../shared/dialogParts'
import { Tooltip } from '../shared/Tooltip'
import { tripsApi } from '../../api/client'
import { collectionsApi } from '../../api/collections'
import { getCategoryIcon } from '../shared/categoryIcons'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { formatDate } from '../../utils/formatters'
import { getApiErrorMessage } from '../../types'
import type { Category, TranslationFn } from '../../types'
import type { CollectionImportablePlace, Trip } from '@trek/shared'
interface ImportFromTripModalProps {
isOpen: boolean
collectionId: number
collectionName: string
categories: Category[]
onClose: () => void
onImported: () => void
t: TranslationFn
}
type Step = 'trip' | 'places' | 'done'
/** Rows sort new-and-unscheduled first, then the rest of the new ones, and the
* already-saved ones last. A trip whose places are mostly saved already then reads
* as "here are the two left over" instead of a wall of greyed-out rows. */
function importOrder(p: CollectionImportablePlace): number {
if (p.already_in_list) return 2
return p.scheduled ? 1 : 0
}
/** Dates go through the shared formatter, so they follow the reader's locale
* (and drop the year when it is the current one) instead of showing raw ISO. */
function tripRange(trip: Trip, locale: string): string | null {
const from = formatDate(trip.start_date, locale)
const to = formatDate(trip.end_date, locale)
if (from && to && to !== from) return `${from} → ${to}`
return from || to || null
}
/**
* The toolbar of the places step, pinned to the top of the scrolling body so the
* search and the filters stay in reach down a long trip. The negative margins
* let its background cover the body's padding while it is stuck.
*/
const STICKY_BAR = 'sticky top-0 z-10 -mx-6 -mb-3 -mt-5 flex flex-wrap items-center gap-2 bg-surface-card px-6 pb-3 pt-5'
const ROWS = 'flex flex-col gap-0.5 rounded-[14px] border border-edge-faint bg-surface-secondary p-1.5'
/** A small fact on a trip tile; each is its own pill, so a narrow tile wraps between them instead of clipping a word. */
const META_PILL = 'inline-flex min-w-0 max-w-full items-center gap-1 truncate rounded-full bg-surface-tertiary px-1.5 py-px font-semibold tabular-nums text-content-muted'
const CHIP = 'inline-flex flex-none items-center gap-1 rounded-full px-2.5 py-1 font-semibold disabled:cursor-default disabled:opacity-50'
const CHIP_OFF = 'bg-surface-card text-content-muted ring-1 ring-edge-faint hover:text-content'
const CHIP_ON = 'bg-accent text-accent-text'
const TAG = 'flex-none whitespace-nowrap rounded-full px-2 py-[2px] font-semibold tabular-nums'
/** The dashed box a step shows when there is nothing to pick. */
function EmptyState({ icon, good = false, children }: { icon: React.ReactNode; good?: boolean; children: React.ReactNode }) {
return (
{icon}
{children}
)
}
/**
* Bulk import of a trip's places into the current list.
*
* Two steps: pick a trip, then pick its places. The duplicate verdict comes from
* the server (`/importable/:tripId`) rather than a second comparison here, so a row
* shown as new can never come back as skipped. Places no day holds are pre-selected:
* those are the ones a trip left behind, which is what this import is for.
*/
export default function ImportFromTripModal({ isOpen, collectionId, collectionName, categories, onClose, onImported, t }: ImportFromTripModalProps): React.ReactElement {
const toast = useToast()
const { language } = useTranslation()
const labelId = useId()
const [step, setStep] = useState('trip')
const [trips, setTrips] = useState([])
const [tripsLoading, setTripsLoading] = useState(false)
const [trip, setTrip] = useState(null)
const [items, setItems] = useState([])
const [itemsLoading, setItemsLoading] = useState(false)
const [selected, setSelected] = useState>(new Set())
const [onlyNew, setOnlyNew] = useState(false)
const [query, setQuery] = useState('')
const [importing, setImporting] = useState(false)
const [result, setResult] = useState<{ copied: number; skipped: number } | null>(null)
useEffect(() => {
if (!isOpen) return
setStep('trip'); setTrip(null); setItems([]); setSelected(new Set()); setQuery(''); setOnlyNew(false); setResult(null)
setTripsLoading(true)
tripsApi.list()
.then((data: { trips?: Trip[] }) => setTrips(data.trips ?? []))
.catch(err => toast.error(getApiErrorMessage(err, t('common.error'))))
.finally(() => setTripsLoading(false))
// toast/t are stable enough for a mount effect; re-running on them would refetch on every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen])
const pickTrip = async (chosen: Trip) => {
setTrip(chosen); setStep('places'); setItemsLoading(true); setQuery('')
try {
const data = await collectionsApi.importable(collectionId, chosen.id)
setItems(data.places)
// Unscheduled places are the point of the import, so they start selected. A trip
// where everything was scheduled would otherwise open with an empty selection, so
// fall back to every new place there.
const fresh = data.places.filter(p => !p.already_in_list)
const leftovers = fresh.filter(p => !p.scheduled)
setSelected(new Set((leftovers.length ? leftovers : fresh).map(p => p.place_id)))
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
setStep('trip')
} finally {
setItemsLoading(false)
}
}
const newCount = useMemo(() => items.filter(p => !p.already_in_list).length, [items])
const savedCount = items.length - newCount
const visible = useMemo(() => {
const q = query.trim().toLowerCase()
return items
.filter(p => (onlyNew ? !p.already_in_list : true))
.filter(p => !q || p.name.toLowerCase().includes(q) || (p.address ?? '').toLowerCase().includes(q))
.sort((a, b) => importOrder(a) - importOrder(b) || a.name.localeCompare(b.name))
}, [items, onlyNew, query])
const selectableVisible = visible.filter(p => !p.already_in_list)
const allVisibleSelected = selectableVisible.length > 0 && selectableVisible.every(p => selected.has(p.place_id))
const toggle = (id: number) => {
setSelected(prev => {
const next = new Set(prev)
if (!next.delete(id)) next.add(id)
return next
})
}
const toggleAllVisible = () => {
setSelected(prev => {
const next = new Set(prev)
if (allVisibleSelected) selectableVisible.forEach(p => next.delete(p.place_id))
else selectableVisible.forEach(p => next.add(p.place_id))
return next
})
}
const runImport = async () => {
if (!trip || selected.size === 0) return
setImporting(true)
try {
const res = await collectionsApi.saveFromTripMany(collectionId, trip.id, [...selected])
setResult({ copied: res.copied, skipped: res.skipped.length })
setStep('done')
onImported()
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
} finally {
setImporting(false)
}
}
const categoryById = useMemo(() => new Map(categories.map(c => [c.id, c])), [categories])
const tripShown = step === 'places' ? trip : null
const title = tripShown
? tripShown.title
: step === 'done'
? t('collections.importDoneTitle')
: t('collections.importTitle')
// The first step says what it is for under the title; the second names the
// trip, and the dialog's own title moves up to the eyebrow.
let sub: React.ReactNode
if (step === 'trip') sub = t('collections.importPickTripHint', { name: collectionName })
else if (tripShown) sub = tripRange(tripShown, language) ?? undefined
const header = (
}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={onClose}
eyebrow={tripShown ? t('collections.importTitle') : undefined}
title={title}
sub={sub}
subWraps={step === 'trip'}
/>
)
let footer: React.ReactNode
if (step === 'done') {
footer = (
{t('common.close')}
)
} else if (step === 'places') {
footer = (
setStep('trip')} icon={}>{t('common.back')}
{t('collections.importSelectedCount', { count: selected.size })}
{t('common.cancel')} void runImport()}
disabled={importing || selected.size === 0}
icon={importing ? : }
>
{t('collections.importAction', { count: selected.size })}
)
} else {
footer = (
{t('common.cancel')}
)
}
return (
// Pinned at the top: the three steps are of very different heights.
{/* Step 1: which trip */}
{step === 'trip' && (
tripsLoading ? (