import { useState } from 'react'
import {
  Button,
  Field,
  Input,
  Caption1,
  Text,
  makeStyles,
  tokens,
  shorthands
} from '@fluentui/react-components'
import {
  AddRegular,
  EditRegular,
  DeleteRegular,
  SaveRegular,
  DismissRegular
} from '@fluentui/react-icons'
import type { MediaProfile, MediaKind } from '@shared/ipc'
import { QUALITY_OPTIONS } from '../lib/qualityOptions'
import { useProfiles } from '../store/profiles'
import { newId } from '../lib/id'
import { Hint } from './Hint'
import { Select } from './Select'
import { SegmentedControl } from './ui/SegmentedControl'
import { EmptyState } from './ui/EmptyState'
import { SPACE, META_SEP } from './ui/tokens'

const useStyles = makeStyles({
  root: { display: 'flex', flexDirection: 'column', gap: '10px' },
  row: {
    display: 'flex',
    alignItems: 'center',
    gap: '10px',
    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 },
  rowMeta: { color: tokens.colorNeutralForeground3 },
  actions: { display: 'flex', gap: '4px', flexShrink: 0 },
  form: {
    display: 'flex',
    flexDirection: 'column',
    gap: '8px',
    padding: SPACE.cozy,
    backgroundColor: tokens.colorNeutralBackground2,
    ...shorthands.borderRadius(tokens.borderRadiusLarge),
    border: `1px solid ${tokens.colorNeutralStroke2}`
  },
  formRow: { display: 'flex', gap: '8px', alignItems: 'flex-end', flexWrap: 'wrap' },
  formActions: { display: 'flex', gap: '8px', justifyContent: 'flex-end' }
})

interface Draft {
  /** null while adding a brand-new profile */
  id: string | null
  name: string
  kind: MediaKind
  quality: string
  outputTemplate: string
  extraArgs: string
}
const BLANK_DRAFT: Draft = {
  id: null,
  name: '',
  kind: 'video',
  quality: 'Best available',
  outputTemplate: '',
  extraArgs: ''
}

/** One-line summary of a profile's overrides for the list row. */
function summarize(p: MediaProfile): string {
  const parts = [p.kind === 'audio' ? 'Audio' : 'Video']
  if (p.quality) parts.push(p.quality)
  if (p.outputTemplate) parts.push('custom folders')
  if (p.extraArgs) parts.push('extra args')
  return parts.join(META_SEP)
}

/**
 * Inline (no-modal, per the app's composited-overlay avoidance) CRUD list +
 * add/edit form for MediaProfile — named download presets a Library Source can
 * point at. Mirrors TemplateManager; used from SettingsView's "Media profiles"
 * card.
 */
export function ProfileManager(): React.JSX.Element {
  const styles = useStyles()
  const profiles = useProfiles((s) => s.profiles)
  const save = useProfiles((s) => s.save)
  const remove = useProfiles((s) => s.remove)

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

  function startEdit(p: MediaProfile): void {
    setDraft({
      id: p.id,
      name: p.name,
      kind: p.kind ?? 'video',
      quality: p.quality ?? 'Best available',
      outputTemplate: p.outputTemplate ?? '',
      extraArgs: p.extraArgs ?? ''
    })
  }

  function commit(): void {
    if (!draft) return
    const name = draft.name.trim()
    if (!name) return
    const outputTemplate = draft.outputTemplate.trim()
    const extraArgs = draft.extraArgs.trim()
    save({
      id: draft.id ?? newId('prof'),
      name,
      kind: draft.kind,
      quality: draft.quality,
      ...(outputTemplate ? { outputTemplate } : {}),
      ...(extraArgs ? { extraArgs } : {})
    })
    setDraft(null)
  }

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

      {profiles.map((p) => (
        <div key={p.id} className={styles.row}>
          <div className={styles.rowBody}>
            <Text className={styles.rowName}>{p.name}</Text>
            <Caption1 className={styles.rowMeta}>{summarize(p)}</Caption1>
          </div>
          <div className={styles.actions}>
            <Hint label="Edit" placement="top" align="end">
              <Button
                appearance="subtle"
                icon={<EditRegular />}
                onClick={() => startEdit(p)}
                aria-label="Edit profile"
              />
            </Hint>
            <Hint label="Delete" placement="top" align="end">
              <Button
                appearance="subtle"
                icon={<DeleteRegular />}
                onClick={() => remove(p.id)}
                aria-label="Delete profile"
              />
            </Hint>
          </div>
        </div>
      ))}

      {draft ? (
        <div className={styles.form}>
          <Input
            value={draft.name}
            placeholder="Profile name, e.g. Archive (1080p)"
            onChange={(_, d) => setDraft({ ...draft, name: d.value })}
          />
          <div className={styles.formRow}>
            <Field label="Format">
              <SegmentedControl<MediaKind>
                value={draft.kind}
                options={[
                  { value: 'video', label: 'Video' },
                  { value: 'audio', label: 'Audio' }
                ]}
                onChange={(kind) =>
                  setDraft({ ...draft, kind, quality: QUALITY_OPTIONS[kind][0] ?? draft.quality })
                }
                ariaLabel="Profile format"
              />
            </Field>
            <Field label="Quality">
              <Select
                value={draft.quality}
                options={QUALITY_OPTIONS[draft.kind].map((q) => ({ value: q, label: q }))}
                onChange={(quality) => setDraft({ ...draft, quality })}
              />
            </Field>
          </div>
          <Field
            label="Collection folder layout (optional)"
            hint="Raw yt-dlp -o template for this profile's sources. Blank = the global default."
          >
            <Input
              value={draft.outputTemplate}
              placeholder="%(uploader)s/%(playlist)s/%(title)s.%(ext)s"
              onChange={(_, d) => setDraft({ ...draft, outputTemplate: d.value })}
            />
          </Field>
          <Field label="Extra yt-dlp args (optional)">
            <Input
              value={draft.extraArgs}
              placeholder="--write-thumbnail --no-mtime"
              onChange={(_, d) => setDraft({ ...draft, extraArgs: 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 profile
        </Button>
      )}
    </div>
  )
}
