import {TranslateIcon} from '@sanity/icons'
import {Autocomplete, Box, Card, Checkbox, Flex, Stack, Text} from '@sanity/ui'
import {uuid} from '@sanity/uuid'
import LanguagesList from 'iso-639-1'
import {Dispatch} from 'react'
import {FormField} from 'sanity'

import {type PluginConfig, SUPPORTED_MUX_LANGUAGES, UploadTextTrack} from '../util/types'

const ALL_LANGUAGE_CODES = LanguagesList.getAllCodes().map((code) => ({
  value: code,
  label: LanguagesList.getNativeName(code),
}))

const SUBTITLE_LANGUAGES: Record<
  Extract<UploadTextTrack, {language_code: any}>['type'],
  {value: string; label: string}[]
> = {
  autogenerated: SUPPORTED_MUX_LANGUAGES.map((lang) => ({
    value: lang.code,
    label: lang.label,
  })),
  subtitles: ALL_LANGUAGE_CODES,
  captions: ALL_LANGUAGE_CODES,
}

type TrackSubAction =
  | {subAction: 'add'; value: Partial<UploadTextTrack>}
  | {subAction: 'update'; value: Partial<UploadTextTrack>}
  | {subAction: 'delete'}

export type TrackAction = {action: 'track'; id: string} & TrackSubAction

export default function TextTracksEditor({
  tracks,
  dispatch,
  defaultLang,
}: {
  /**
   * Although the schema for tracks is an array, which we'll eventually support to allow uploading
   * multiple custom subtitles, for now we only support a single auto-generated track.
   */
  tracks: (Partial<UploadTextTrack> & {_id: string})[]
  dispatch: Dispatch<TrackAction>
  defaultLang: PluginConfig['defaultAutogeneratedSubtitleLang']
}) {
  const track = tracks[0]
  return (
    <FormField title="Auto-generated subtitle or caption">
      <Stack space={2}>
        <Flex align="center">
          <Checkbox
            id="include-autogenerated-track"
            style={{display: 'block'}}
            checked={!!track?.language_code}
            onChange={() => {
              if (track) {
                dispatch({action: 'track', id: track._id, subAction: 'delete'})
              } else {
                dispatch({
                  action: 'track',
                  id: uuid(),
                  subAction: 'add',
                  value: {
                    type: 'autogenerated',
                    name: defaultLang || undefined,
                    language_code: defaultLang || undefined,
                  },
                })
              }
            }}
          />
          <Box flex={1} paddingLeft={3}>
            <Text>
              <label htmlFor="checkbox">Generate captions</label>
            </Text>
          </Box>
        </Flex>
        {track && (
          <Autocomplete
            id={`text-tract-editor--language`}
            value={track.language_code}
            onChange={(newValue) =>
              dispatch({
                action: 'track',
                id: track._id,
                subAction: 'update',
                value: {
                  language_code: newValue,
                  name: LanguagesList.getNativeName(newValue),
                },
              })
            }
            options={SUBTITLE_LANGUAGES[track.type!]}
            icon={TranslateIcon}
            placeholder="Select language"
            filterOption={(query, option) =>
              option.label.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
              option.value.toLowerCase().indexOf(query.toLowerCase()) > -1
            }
            openButton
            renderValue={(value) =>
              SUBTITLE_LANGUAGES[track.type!].find((l) => l.value === value)?.label || value
            }
            renderOption={(option) => (
              <Card data-as="button" padding={3} radius={2} tone="inherit">
                <Text size={2} textOverflow="ellipsis">
                  {option.label} ({option.value})
                </Text>
              </Card>
            )}
          />
        )}
      </Stack>
    </FormField>
  )
}
