import { Field, Switch, Card, Subtitle2, Caption1 } from '@fluentui/react-components'
import { CodeRegular } from '@fluentui/react-icons'
import { useSettings } from '../../store/settings'
import { useTemplates } from '../../store/templates'
import { Select } from '../../components/Select'
import { TemplateManager } from '../../components/TemplateManager'
import { useSettingsStyles } from './settingsStyles'

export function CustomCommandsCard(): React.JSX.Element {
  const styles = useSettingsStyles()
  const enableCustomCommands = useSettings((s) => s.enableCustomCommands)
  const defaultTemplateId = useSettings((s) => s.defaultTemplateId)
  const update = useSettings((s) => s.update)
  const templates = useTemplates((s) => s.templates)

  return (
    <Card className={styles.card}>
      <div className={styles.sectionHeader}>
        <CodeRegular className={styles.sectionIcon} />
        <Subtitle2 as="h3">Custom commands</Subtitle2>
      </div>
      <Caption1 className={styles.hint}>
        Named templates of extra yt-dlp flags -- your own power-user recipes (e.g.
        --write-thumbnail, --no-mtime, anything yt-dlp supports). Appended after every other option,
        so a template flag can override a setting above it.
      </Caption1>

      <Field
        label="Run custom command"
        hint="Applies the default template below to every new download (still overridable per download)."
      >
        <Switch
          checked={enableCustomCommands}
          onChange={(_, d) => update({ enableCustomCommands: d.checked })}
        />
      </Field>

      {enableCustomCommands && (
        <Field label="Default template">
          <Select
            value={defaultTemplateId ?? 'none'}
            options={[
              { value: 'none', label: 'None' },
              ...templates.map((t) => ({ value: t.id, label: t.name }))
            ]}
            onChange={(v) => update({ defaultTemplateId: v === 'none' ? null : v })}
          />
        </Field>
      )}

      <TemplateManager />
    </Card>
  )
}
