import {useEffect} from 'react'
import {View} from 'react-native'

import {Button} from '@/components/ui/button'
import {Text} from '@/components/ui/typography'
import {formatDayDate} from '@/lib/dates'
import {alertError, showActionSheet} from '@/lib/dialogs'
import {enablePushReminders} from '@/lib/push'
import {reminderOptions} from '@/lib/reminders'
import {atoms as a, useTheme} from '@/sprinkles'
import {type Crumb} from '@/stores/crumbs'
import {
  useAddReminder,
  useLoadReminders,
  useReminders,
  useRemoveReminder,
  type Reminder,
} from '@/stores/reminders'

const reminderLabel = (reminder: Reminder): string => {
  const day = formatDayDate(reminder.remindAt)
  if (reminder.kind === 'week_before') return `A week before · ${day}`
  if (reminder.kind === 'day_before') return `The day before · ${day}`
  return day
}

// pending reminders for an own crumb: auto ones materialize from the plan,
// manual ones are added from a canned-moments sheet
export function RemindersSection({crumb}: {crumb: Crumb}) {
  const t = useTheme()
  const reminders = useReminders(crumb.id)
  const load = useLoadReminders()
  const add = useAddReminder()
  const remove = useRemoveReminder()

  useEffect(() => {
    void load(crumb.id)
  }, [crumb.id, load])

  const anchor =
    crumb.status === 'planned' && crumb.plannedFor
      ? new Date(crumb.plannedFor)
      : crumb.event?.startsAt
        ? new Date(crumb.event.startsAt)
        : null

  const addReminder = async (remindAt: Date) => {
    try {
      await add(crumb.id, remindAt)
      // the moment a reminder exists is the moment the permission ask
      // makes sense
      void enablePushReminders()
    } catch (err) {
      alertError(err)
    }
  }

  const showAddSheet = () =>
    showActionSheet(
      reminderOptions(anchor, new Date()).map((option) => ({
        label: `${option.label} — ${formatDayDate(option.remindAt)}`,
        onPress: () => void addReminder(option.remindAt),
      })),
      {title: 'Remind me'},
    )

  return (
    <View style={a.gap_xs}>
      {(reminders ?? []).map((reminder) => (
        <View
          key={reminder.id}
          style={[a.flex_row, a.align_center, a.justify_between]}
        >
          <Text
            emoji
            style={[a.text_sm, t.atoms.text_contrast_medium]}
          >
            🔔 {reminderLabel(reminder)}
          </Text>
          <Button
            label="Remove"
            accessibilityLabel={`Remove reminder ${reminderLabel(reminder)}`}
            variant="ghost"
            color="negative"
            size="small"
            onPress={() =>
              void remove(crumb.id, reminder.id).catch(alertError)
            }
          />
        </View>
      ))}
      <Button
        label="+ Remind me"
        variant="ghost"
        color="primary"
        size="small"
        shape="flush"
        onPress={showAddSheet}
      />
    </View>
  )
}
