import type { ReactNode } from 'react'
import { VIDEO_PROFILES, type VideoTarget, type VideoCodec } from '@/shared/video'
import type { ConvertOptions } from '../options'

const labels: Record<VideoCodec, string> = { auto: 'Automatic', h264: 'H.264', vp9: 'VP9', vp8: 'VP8', av1: 'AV1 (slower)', ffv1: 'FFV1 (lossless)', prores: 'ProRes 4444', mpeg4: 'MPEG-4 Part 2', wmv2: 'Windows Media Video 8', mjpeg: 'Motion JPEG', gif: 'Animated GIF', webp: 'Animated WebP' }
function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
  return <label className="grid gap-1.5 sm:grid-cols-[9.5rem_1fr] sm:items-start sm:gap-4"><span className="pt-1 text-sm font-medium">{label}</span><span>{children}{hint && <span className="mt-1 block text-xs text-muted-foreground">{hint}</span>}</span></label>
}
const selectClass = 'h-9 max-w-full rounded-lg border bg-background px-2 text-sm'
export function VideoOptions({ to, options: o, setOptions }: { to: VideoTarget; options: ConvertOptions; setOptions: (o: ConvertOptions) => void }) {
  const set = <K extends keyof ConvertOptions>(key: K, value: ConvertOptions[K]) => setOptions({ ...o, [key]: value })
  const profile = VIDEO_PROFILES[to], silent = to === 'gif' || to === 'webp'
  return <>
    {!silent && <Field label="Video codec" hint={`Automatic uses ${labels[profile.codec]}. Codec support varies between players.`}><select aria-label="Video codec" className={selectClass} value={o.videoCodec} onChange={e => setOptions({ ...o, videoCodec: e.target.value as VideoCodec, videoQuality: e.target.value === 'ffv1' ? 'lossless' : o.videoQuality === 'lossless' ? 'high' : o.videoQuality })}><option value="auto">Automatic</option>{profile.choices.map(c => <option key={c} value={c}>{labels[c]}</option>)}</select></Field>}
    {to === 'webp' ? <>
      <p className="text-sm text-muted-foreground">Silent WebP animation with millisecond picture delays and 8-bit alpha. Limits: 60 seconds and 2 megapixels per frame, or 15 seconds and 0.5 megapixels on iPhone/iPad. Source video packet limits: 20,000 desktop or 5,000 on iPhone/iPad.</p>
      <Field label="WebP compression" hint="Lossless keeps resulting 8-bit visible RGB and alpha. Fully transparent RGB can change; source color conversion and resizing still apply."><select aria-label="WebP compression" className={selectClass} value={o.videoWebpLossless ? 'lossless' : 'lossy'} onChange={e => set('videoWebpLossless', e.target.value === 'lossless')}><option value="lossy">Lossy</option><option value="lossless">Lossless pixels</option></select></Field>
      <Field label="WebP quality" hint={o.videoWebpLossless ? 'In lossless mode this controls compression effort, not pixel fidelity. Encoding time and size vary by image.' : '0–100. Higher values usually keep more color detail at a larger size. Alpha is encoded losslessly.'}><input aria-label="WebP quality" className={selectClass} type="number" min="0" max="100" value={o.videoWebpQuality} onChange={e => set('videoWebpQuality', Number(e.target.value))} /></Field>
      <Field label="WebP playback" hint="0 loops forever. 1 plays once; 2–65535 gives the total play count."><input aria-label="WebP playback" className={selectClass} type="number" min="0" max="65535" step="1" value={o.videoWebpLoop} onChange={e => set('videoWebpLoop', Number(e.target.value))} /></Field>
    </> : to === 'gif' ? <>
      <p className="text-sm text-muted-foreground">Silent animation, with a separate palette for each picture. GIF reduces colors and opacity. Limits: 60 seconds and 2 megapixels per frame, or 15 seconds and 0.5 megapixels on iPhone/iPad. Source video packet limits: 20,000 desktop or 5,000 on iPhone/iPad.</p>
      <Field label="GIF colors" hint="Fewer colors can make files smaller, with more banding. Palettes may change between pictures."><select aria-label="GIF colors" className={selectClass} value={o.videoQuality} onChange={e => set('videoQuality', e.target.value as ConvertOptions['videoQuality'])}><option value="high">256 colors</option><option value="balanced">128 colors</option><option value="small">64 colors</option></select></Field>
      <Field label="GIF dithering" hint="Error diffusion softens palette banding with noise. Ordered dithering uses a stable pattern; None keeps flat areas clean but can show bands."><select aria-label="GIF dithering" className={selectClass} value={o.videoGifDither} onChange={e => set('videoGifDither', e.target.value as ConvertOptions['videoGifDither'])}><option value="sierra2_4a">Error diffusion</option><option value="bayer">Ordered pattern</option><option value="none">None</option></select></Field>
      <Field label="GIF playback"><select aria-label="GIF playback" className={selectClass} value={o.videoGifLoop} onChange={e => set('videoGifLoop', e.target.value as ConvertOptions['videoGifLoop'])}><option value="forever">Loop forever</option><option value="once">Play once</option></select></Field>
    </> : <Field label="Video quality" hint="Higher quality takes more space. Slider values from other encoders are not comparable. FFV1 retains decoded pixels when no transform is applied."><select aria-label="Video quality" className={selectClass} value={o.videoQuality} onChange={e => setOptions({ ...o, videoQuality: e.target.value as ConvertOptions['videoQuality'], videoCodec: e.target.value === 'lossless' ? 'ffv1' : o.videoCodec === 'ffv1' ? 'auto' : o.videoCodec })}><option value="high">High quality</option><option value="balanced">Balanced</option><option value="small">Smaller file</option>{to === 'mkv' && <option value="lossless">Lossless FFV1</option>}</select></Field>}
    {profile.choices.some(c => c === 'vp9' || c === 'av1') && <Field label="Video color detail" hint="VP9 and AV1 default to 4:2:0 for wider playback. Source chroma keeps finer color detail where supported, but some browsers and hardware players cannot decode its profile. H.264 remains 4:2:0; FFV1 keeps its supported source sample format."><select aria-label="Video color detail" className={selectClass} value={o.videoChroma} onChange={e => set('videoChroma', e.target.value as ConvertOptions['videoChroma'])}><option value="compatible">4:2:0 (wider playback)</option><option value="source">Source chroma (compatible players only)</option></select></Field>}
    <Field label="Video resolution" hint="Original keeps source display size. Non-square pixels are resampled; odd edges may be padded. Large sources have device memory limits."><select aria-label="Video resolution" className={selectClass} value={o.videoMaxSide} onChange={e => set('videoMaxSide', Number(e.target.value))}><option value="0">Original display size</option>{[3840, 2560, 1920, 1280, 960, 640, 320, 160].map(n => <option key={n} value={n}>Maximum {n} px longest side</option>)}</select></Field>
    <Field label="Video frame rate" hint={to === 'webp' ? 'Source delays round to millisecond WebP units. Players may slow very short delays. Choosing a rate can repeat or drop pictures.' : to === 'gif' ? 'Delays round to 10 ms GIF units. Source rates above 50 fps are reduced to 50; players may slow very short delays.' : profile.variableTiming ? 'Source preserves variable timestamps. Choosing a rate can repeat or drop frames.' : 'This container uses a constant rate. Source selects the average source rate; frames can repeat or drop.'}><select aria-label="Video frame rate" className={selectClass} value={o.videoFrameRate} onChange={e => set('videoFrameRate', Number(e.target.value))}><option value="0">Source</option>{[12, 15, 23.976, 24, 25, 29.97, 30, 50, ...(to === 'gif' ? [] : [59.94, 60])].map(n => <option key={n} value={n}>{n} fps</option>)}</select></Field>
    {!silent && <Field label="Video audio" hint="Automatic copies compatible audio; other tracks are re-encoded. Copy requires a compatible container. Timing offsets are retained."><select aria-label="Video audio" className={selectClass} value={o.videoAudio} onChange={e => set('videoAudio', e.target.value as ConvertOptions['videoAudio'])}><option value="auto">Automatic</option><option value="copy">Copy audio without re-encoding</option><option value="none">Remove audio</option></select></Field>}
    {!silent && o.videoAudio !== 'none' && <Field label="Video audio tracks" hint={to === 'flv' ? 'FLV accepts one audio track. Choose First if the source has several.' : 'All keeps languages and tracks separate inside the output file.'}><select aria-label="Video audio tracks" className={selectClass} value={o.videoAudioTracks} onChange={e => set('videoAudioTracks', e.target.value as ConvertOptions['videoAudioTracks'])}><option value="all">All audio tracks</option><option value="first">First audio track</option></select></Field>}
    <Field label="HDR video" hint="H.264, VP8, MPEG-4 and WMV use SDR here. Automatic tone maps HDR for these codecs. VP9, AV1, ProRes and FFV1 can retain HDR; dynamic HDR metadata is omitted."><select aria-label="HDR video" className={selectClass} value={o.videoHdr} onChange={e => set('videoHdr', e.target.value as ConvertOptions['videoHdr'])}><option value="auto">Automatic</option><option value="tonemap">Tone map to SDR</option>{!silent && <option value="preserve">Require HDR preservation</option>}</select></Field>
    <Field label="Video transparency" hint={to === 'webp' ? 'WebP can retain 8-bit partial opacity. Fully transparent RGB can be changed by animation optimization. Choose a background to composite instead.' : to === 'gif' ? 'GIF has binary transparency: alpha below 128 becomes transparent, while 128 and above becomes opaque. Composite onto white or black to retain the appearance of partial opacity.' : "VP9, FFV1 and ProRes can keep alpha. VP9 alpha overrides quality presets with lossless sample coding; color conversion still applies and files can be larger. Other codecs composite onto white by default."}><select aria-label="Video transparency" className={selectClass} value={o.videoAlpha} onChange={e => set('videoAlpha', e.target.value as ConvertOptions['videoAlpha'])}><option value="preserve">Keep when supported, otherwise white</option><option value="white">Composite onto white</option><option value="black">Composite onto black</option></select></Field>
    <Field label="Interlaced video" hint="Automatic outputs one progressive picture per flagged source field, retaining field motion. Retaining interlacing requires FFV1 in MKV."><select aria-label="Interlaced video" className={selectClass} value={o.videoDeinterlace} onChange={e => set('videoDeinterlace', e.target.value as ConvertOptions['videoDeinterlace'])}><option value="auto">Automatic deinterlacing</option><option value="keep">Keep source fields</option></select></Field>
    {!silent && <Field label="Video metadata" hint="Keep can include location and other private tags. Subtitles, attachments and editing-project data are omitted."><select aria-label="Video metadata" className={selectClass} value={o.videoMetadata} onChange={e => set('videoMetadata', e.target.value as ConvertOptions['videoMetadata'])}><option value="none">Remove source tags and chapters</option><option value="keep">Keep supported source metadata</option></select></Field>}
  </>
}
