import {DatePicker, Host} from '@expo/ui/swift-ui'
import {Redirect, Stack, useLocalSearchParams} from 'expo-router'
import {useState} from 'react'
import {View} from 'react-native'

import {Button} from '@/components/ui/button'
import {Layout} from '@/components/ui/layout'
import {Text} from '@/components/ui/typography'
import {useDetail} from '@/hooks/use-detail'
import {useSubmitAction} from '@/hooks/use-submit-action'
import {goBack} from '@/lib/navigation'
import {enablePushReminders} from '@/lib/push'
import {atoms as a, useTheme} from '@/sprinkles'
import {crumbDetail, useUpdateCrumb} from '@/stores/crumbs'

const DAY_MS = 24 * 60 * 60 * 1000

const defaultPlanDate = (startsAt: string | null | undefined) => {
  if (startsAt && new Date(startsAt).getTime() > Date.now())
    return new Date(startsAt)
  const tomorrow = new Date(Date.now() + DAY_MS)
  tomorrow.setHours(18, 0, 0, 0)
  return tomorrow
}

export default function PlanCrumbScreen() {
  const {crumbId} = useLocalSearchParams<{crumbId: string}>()
  const t = useTheme()
  const {data: crumb, loading: resolving} = useDetail(
    crumbDetail,
    crumbId,
    {refresh: false},
  )
  const updateCrumb = useUpdateCrumb()
  const [date, setDate] = useState(() =>
    defaultPlanDate(crumb?.event?.startsAt),
  )
  const {submitting: saving, submit} = useSubmitAction(
    async (when: Date) => {
      if (!crumb) return
      await updateCrumb(crumb.id, {
        status: 'planned',
        plannedFor: when.toISOString(),
      })
      // contextual prompt — first plan is the moment a nudge makes sense
      void enablePushReminders()
      goBack()
    },
    {alertOnError: true},
  )

  // wait for the detail fetch before deciding the crumb is missing
  if (!crumb) return resolving ? null : <Redirect href="/" />

  return (
    <>
      <Stack.Screen options={{title: 'Plan it'}} />
      <Layout.ModalContent contentContainerStyle={a.gap_lg}>
        <Text emoji style={t.atoms.text_contrast_medium}>
          When are you going to {crumb.name}?
        </Text>

        <View style={{height: 64}}>
          <Host style={a.flex_1}>
            <DatePicker
              title="Date"
              selection={date}
              range={{start: new Date()}}
              displayedComponents={['date', 'hourAndMinute']}
              onDateChange={setDate}
            />
          </Host>
        </View>

        <Text style={[t.atoms.text_contrast_medium]}>
          We&apos;ll remind you the day before.
        </Text>

        <Button
          label={saving ? 'Saving…' : 'Plan it'}
          color="primary"
          size="large"
          shape="rectangular"
          onPress={() => void submit(date)}
          disabled={saving}
        />
      </Layout.ModalContent>
    </>
  )
}
