import {useEffect} from 'react'

import {AuthGate} from '@/components/auth-gate'
import {CrumbList} from '@/components/crumb-list'
import {ErrorState} from '@/components/error-state'
import {Card} from '@/components/ui/card'
import {Layout} from '@/components/ui/layout'
import {upcomingCrumbs} from '@/lib/planned'
import {
  usePlanned,
  usePlannedError,
  usePlannedLoading,
  useRefreshPlanned,
} from '@/stores/crumbs'

export default function PlannedScreen() {
  return (
    <AuthGate>
      <PlannedScreenInner />
    </AuthGate>
  )
}

function PlannedScreenInner() {
  const upcoming = upcomingCrumbs(usePlanned())
  const loading = usePlannedLoading()
  const error = usePlannedError()
  const refresh = useRefreshPlanned()

  useEffect(() => {
    void refresh()
  }, [refresh])

  return (
    <Layout.Content>
      <Card>
        {error && upcoming.length === 0 ? (
          <ErrorState
            message={error}
            onRetry={() => void refresh()}
          />
        ) : (
          <CrumbList
            crumbs={upcoming.map((u) => u.crumb)}
            loading={loading}
            emptyMessage="Nothing planned yet"
          />
        )}
      </Card>
    </Layout.Content>
  )
}
