import Feather from '@expo/vector-icons/Feather'
import { router } from 'expo-router'
import { useState } from 'react'
import { Switch } from 'src/components/form/Switch'
import { ScreenScrollContainer } from 'src/components/layout'
import { useScreenMenu } from 'src/components/menu'
import { BodyText, FormField, SectionHeader, SettingRow } from 'src/components/ui'
import { useCreateMastodonListMutation } from 'src/hooks/mutations/useCreateMastodonListMutation'
import { haptic } from 'src/lib/haptics'
import { useAuth } from 'src/state/AuthProvider'
import { Separator, useTheme, useToastController, View, YStack } from 'tamagui'

const TITLE_MAX = 50
type RepliesPolicy = 'followed' | 'list' | 'none'

const REPLIES_POLICY_OPTIONS: ReadonlyArray<{
  value: RepliesPolicy
  label: string
  description: string
}> = [
  {
    value: 'list',
    label: 'List members',
    description: 'Show replies to other members of this list.',
  },
  {
    value: 'followed',
    label: 'People you follow',
    description: 'Show replies to anyone you follow.',
  },
  { value: 'none', label: 'No one', description: 'Hide replies in the list timeline.' },
]

// Surface D — Create list. Lives as a formSheet route registered in
// `src/app/_layout.tsx` so on iOS it presents as `UIModalPresentationFormSheet`
// (Liquid Glass-adopted on iOS 26+) and on Android as a native
// `BottomSheetBehavior`. URL-addressable so the deep link / unsaved-changes
// guard both work canonically.
//
// Pixelfed-active accounts can't reach Lists at all (the catalogue route gates
// on `user.type === 'mastodon'`); to be defensive we re-check here so a stale
// deep link doesn't punch through.
export default function NewListScreen() {
  const theme = useTheme()
  const toast = useToastController()
  const { user } = useAuth()
  const isMastodon = user?.type === 'mastodon'

  const [title, setTitle] = useState('')
  const [repliesPolicy, setRepliesPolicy] = useState<RepliesPolicy>('list')
  const [exclusive, setExclusive] = useState(false)

  const create = useCreateMastodonListMutation()
  const trimmed = title.trim()
  const canSubmit = isMastodon && trimmed.length > 0 && !create.isPending

  const onCreate = () => {
    if (!canSubmit) return
    haptic.selection()
    create.mutate(
      { title: trimmed, repliesPolicy, exclusive },
      {
        onSuccess: (list) => {
          // expo-router's regenerated route map doesn't include the dynamic
          // `[id]` segment as a typed template-literal target — cast at the
          // boundary (same convention `LinkRow` already documents).
          router.replace(`/settings/lists/${list.id}` as any)
        },
        onError: () => {
          toast.show('Could not create list', { preset: 'error', duration: 2500 })
        },
      }
    )
  }

  useScreenMenu({
    title: 'New list',
    intents: [
      { kind: 'back', dismissMode: 'close' },
      {
        kind: 'commit',
        id: 'create-list',
        icon: 'check',
        label: 'Create',
        onPress: onCreate,
        state: create.isPending ? 'busy' : canSubmit ? 'idle' : 'disabled',
      },
    ],
  })

  if (!isMastodon) {
    return (
      <ScreenScrollContainer variant="scroll" header="New list">
        <YStack px="$5" pt="$4" gap="$2">
          <BodyText tone="secondary">
            Lists are a Mastodon-only feature. Switch to a Mastodon account to create one.
          </BodyText>
        </YStack>
      </ScreenScrollContainer>
    )
  }

  return (
    <ScreenScrollContainer variant="scroll" header="New list">
      <YStack px="$5" pt="$4" gap="$4">
        <FormField
          label="Name"
          value={title}
          onChangeText={setTitle}
          maxLength={TITLE_MAX}
          placeholder="My list"
          autoCapitalize="words"
          autoFocus
          enterKeyHint="done"
          onSubmitEditing={onCreate}
        />
      </YStack>

      <SectionHeader>Show replies to</SectionHeader>
      {REPLIES_POLICY_OPTIONS.map((opt, idx) => {
        const selected = repliesPolicy === opt.value
        return (
          <YStack key={opt.value}>
            <SettingRow
              title={opt.label}
              description={opt.description}
              onPress={() => {
                if (selected) return
                haptic.selection()
                setRepliesPolicy(opt.value)
              }}
              accessibility={{
                role: 'radio',
                label: opt.label,
                hint: opt.description,
                state: { selected },
              }}
              trailing={
                selected ? (
                  <Feather name="check" size={20} color={theme.interactiveActive.val} />
                ) : null
              }
              tone="secondary"
            />
            {idx < REPLIES_POLICY_OPTIONS.length - 1 ? (
              <Separator borderColor="$borderColor" />
            ) : null}
          </YStack>
        )
      })}

      <SectionHeader>Options</SectionHeader>
      <View px="$5">
        <SettingRow
          title="Exclusive"
          description="Hide list members' posts from the home timeline."
          trailing={
            <Switch
              size="$3"
              checked={exclusive}
              onCheckedChange={(checked) => {
                haptic.selection()
                setExclusive(checked)
              }}
            >
              <Switch.Thumb transition="quicker" />
            </Switch>
          }
        />
      </View>

      <Separator borderColor="$borderColor" mt="$4" />
    </ScreenScrollContainer>
  )
}
