import { useState } from 'react'
import {
  Button,
  Field,
  Input,
  Textarea,
  Caption1,
  Text,
  makeStyles,
  tokens,
  shorthands
} from '@fluentui/react-components'
import {
  AddRegular,
  EditRegular,
  DeleteRegular,
  SaveRegular,
  DismissRegular
} from '@fluentui/react-icons'
import type { CommandTemplate } from '@shared/ipc'
import { useTemplates } from '../store/templates'
import { newId } from '../lib/id'
import { Hint } from './Hint'
import { EmptyState } from './ui/EmptyState'
import { SPACE } from './ui/tokens'

const useStyles = makeStyles({
  root: {
    display: 'flex',
    flexDirection: 'column',
    gap: '10px'
  },
  row: {
    display: 'flex',
    alignItems: 'center',
    gap: '10px',
    // Control-tier padding (UI3): tight vertical, snug horizontal.
    padding: `${SPACE.tight} ${SPACE.snug}`,
    backgroundColor: tokens.colorNeutralBackground2,
    ...shorthands.borderRadius(tokens.borderRadiusLarge),
    border: `1px solid ${tokens.colorNeutralStroke2}`
  },
  rowBody: {
    flexGrow: 1,
    minWidth: 0,
    display: 'flex',
    flexDirection: 'column'
  },
  rowName: {
    fontWeight: tokens.fontWeightSemibold
  },
  rowArgs: {
    color: tokens.colorNeutralForeground3,
    fontFamily: tokens.fontFamilyMonospace,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap'
  },
  actions: {
    display: 'flex',
    gap: '4px',
    flexShrink: 0
  },
  form: {
    display: 'flex',
    flexDirection: 'column',
    gap: '8px',
    // List-row padding tier (UI3): cozy on both axes.
    padding: SPACE.cozy,
    backgroundColor: tokens.colorNeutralBackground2,
    ...shorthands.borderRadius(tokens.borderRadiusLarge),
    border: `1px solid ${tokens.colorNeutralStroke2}`
  },
  formActions: {
    display: 'flex',
    gap: '8px',
    justifyContent: 'flex-end'
  }
})

interface Draft {
  /** null while adding a brand-new template */
  id: string | null
  name: string
  args: string
  /** optional regex; auto-applies the template to matching URLs */
  urlPattern: string
}
const BLANK_DRAFT: Draft = { id: null, name: '', args: '', urlPattern: '' }

/**
 * Inline (no-modal — see the Hint/Select comments re: composited overlays
 * flickering on this dev machine's GPU) CRUD list + add/edit form for
 * CommandTemplate. Used standalone from SettingsView's "Custom commands" card.
 */
export function TemplateManager(): React.JSX.Element {
  const styles = useStyles()
  const templates = useTemplates((s) => s.templates)
  const save = useTemplates((s) => s.save)
  const remove = useTemplates((s) => s.remove)

  const [draft, setDraft] = useState<Draft | null>(null)

  function startEdit(t: CommandTemplate): void {
    setDraft({ id: t.id, name: t.name, args: t.args, urlPattern: t.urlPattern ?? '' })
  }

  function patternError(): string | undefined {
    const p = draft?.urlPattern.trim()
    if (!p) return undefined
    try {
      new RegExp(p)
      return undefined
    } catch {
      return 'Invalid regex — this pattern will never match.'
    }
  }

  function commit(): void {
    if (!draft) return
    const name = draft.name.trim()
    if (!name || patternError()) return
    const urlPattern = draft.urlPattern.trim()
    save({
      id: draft.id ?? newId('tpl'),
      name,
      args: draft.args.trim(),
      ...(urlPattern ? { urlPattern } : {})
    })
    setDraft(null)
  }

  return (
    <div className={styles.root}>
      {templates.length === 0 && !draft && (
        <EmptyState compact message="No custom command templates yet." />
      )}

      {templates.map((t) => (
        <div key={t.id} className={styles.row}>
          <div className={styles.rowBody}>
            <Text className={styles.rowName}>{t.name}</Text>
            <Caption1 className={styles.rowArgs} title={t.args}>
              {t.args || '(no extra args)'}
            </Caption1>
          </div>
          <div className={styles.actions}>
            <Hint label="Edit" placement="top" align="end">
              <Button
                appearance="subtle"
                icon={<EditRegular />}
                onClick={() => startEdit(t)}
                aria-label="Edit template"
              />
            </Hint>
            <Hint label="Delete" placement="top" align="end">
              <Button
                appearance="subtle"
                icon={<DeleteRegular />}
                onClick={() => remove(t.id)}
                aria-label="Delete template"
              />
            </Hint>
          </div>
        </div>
      ))}

      {draft ? (
        <div className={styles.form}>
          <Input
            value={draft.name}
            placeholder="Template name"
            onChange={(_, d) => setDraft({ ...draft, name: d.value })}
          />
          <Textarea
            value={draft.args}
            placeholder="Extra yt-dlp flags, e.g. --write-thumbnail --no-mtime"
            resize="vertical"
            onChange={(_, d) => setDraft({ ...draft, args: d.value })}
          />
          <Field
            validationState={patternError() ? 'error' : 'none'}
            validationMessage={patternError()}
          >
            <Input
              value={draft.urlPattern}
              placeholder="Auto-apply to URLs matching (regex, optional) — e.g. soundcloud\.com"
              onChange={(_, d) => setDraft({ ...draft, urlPattern: d.value })}
            />
          </Field>
          <div className={styles.formActions}>
            <Button appearance="subtle" icon={<DismissRegular />} onClick={() => setDraft(null)}>
              Cancel
            </Button>
            <Button
              appearance="primary"
              icon={<SaveRegular />}
              onClick={commit}
              disabled={!draft.name.trim()}
            >
              Save
            </Button>
          </div>
        </div>
      ) : (
        <Button
          appearance="subtle"
          icon={<AddRegular />}
          onClick={() => setDraft({ ...BLANK_DRAFT })}
        >
          Add template
        </Button>
      )}
    </div>
  )
}
