import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { cn } from '@/lib/utils'
import { FormatChip, Logo, formatBytes } from '@/shared/brand'
import { FORMATS, type Format } from '@/shared/formats'
import { pairLabel, targetsFor } from '@/shared/pairs'
import { SITE_URL } from '@/shared/site'
import { ArrowRightIcon, ChevronDownIcon, DownloadIcon, LoaderCircleIcon, PlusIcon, Settings2Icon, ShareIcon, ShieldCheckIcon, Trash2Icon, UploadIcon, WifiOffIcon } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { zipOutputs } from '../convert'
import { IOS } from '../pool'
import { CombinedCard, FileRow } from './file-list'
import { OptionsPanel, optionsSummary, visibleOptions } from './options-panel'
import { MAX_FILES, useConverter, ZIP_LIMIT, type Mode } from './use-converter'

const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.userAgent)
const TOUCH = typeof navigator !== 'undefined' && (IOS || /Android/i.test(navigator.userAgent))

const ALL_ACCEPT = Object.values(FORMATS).filter((f) => f.kind !== 'subtitle').flatMap((f) => f.accept)

function nounFor(from: Format) {
  if (from === 'heic') return 'photos'
  if (FORMATS[from].kind === 'image') return 'images'
  if (FORMATS[from].kind === 'font') return 'fonts'
  return 'files'
}

function downloadBlob(blob: Blob, name: string) {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = name
  document.body.append(a)
  a.click()
  a.remove()
  setTimeout(() => URL.revokeObjectURL(url), 60_000)
}

function Notice({ children, action, tone = 'info' }: { children: ReactNode; action?: ReactNode; tone?: 'info' | 'warn' }) {
  return (
    <div className={cn('flex flex-wrap items-center gap-x-3 gap-y-2 rounded-xl border px-3 py-2 text-sm', tone === 'warn' ? 'border-amber-500/30 bg-amber-500/10' : 'bg-muted/50')}>
      <p className="min-w-0 flex-1">{children}</p>
      {action}
    </div>
  )
}

export function EngineApp({ mode, embedded }: { mode: Mode; embedded: boolean }) {
  const c = useConverter(mode)
  const inputRef = useRef<HTMLInputElement>(null)
  const [dragging, setDragging] = useState(false)
  const [settingsOpen, setSettingsOpen] = useState(false)
  const [zipping, setZipping] = useState(false)
  const [message, setMessage] = useState<string | null>(null)
  const { add } = c

  const froms = useMemo(() => {
    if (mode.kind === 'source') return [mode.from]
    const seen = [...new Set(c.items.map((i) => i.from).filter(Boolean) as Format[])]
    if (seen.length) return seen
    return mode.kind === 'pair' ? [mode.pair.from] : []
  }, [c.items, mode])

  const targets = useMemo(() => {
    if (!froms.length) return []
    const all = froms.map((f) => targetsFor(f))
    const shared = all[0].filter((t) => all.every((list) => list.includes(t)))
    return shared.length ? shared : all[0]
  }, [froms])

  const visible = visibleOptions(froms, c.target)
  const summary = optionsSummary(visible, c.options)
  const open = useCallback(() => inputRef.current?.click(), [])

  // Files can be dropped anywhere in this frame, or pasted.
  useEffect(() => {
    let depth = 0
    const hasFiles = (e: DragEvent) => !!e.dataTransfer && [...e.dataTransfer.types].includes('Files')
    const enter = (e: DragEvent) => {
      if (!hasFiles(e)) return
      depth++
      setDragging(true)
    }
    const leave = () => {
      depth = Math.max(0, depth - 1)
      if (!depth) setDragging(false)
    }
    const over = (e: DragEvent) => {
      if (!hasFiles(e)) return
      e.preventDefault()
      e.dataTransfer!.dropEffect = 'copy'
    }
    const drop = (e: DragEvent) => {
      e.preventDefault()
      depth = 0
      setDragging(false)
      void add([...(e.dataTransfer?.files ?? [])])
    }
    const paste = (e: ClipboardEvent) => {
      const files = [...(e.clipboardData?.files ?? [])]
      if (!files.length) return
      e.preventDefault()
      void add(files)
    }
    window.addEventListener('dragenter', enter)
    window.addEventListener('dragleave', leave)
    window.addEventListener('dragover', over)
    window.addEventListener('drop', drop)
    window.addEventListener('paste', paste)
    return () => {
      window.removeEventListener('dragenter', enter)
      window.removeEventListener('dragleave', leave)
      window.removeEventListener('dragover', over)
      window.removeEventListener('drop', drop)
      window.removeEventListener('paste', paste)
    }
  }, [add])

  const outputs = c.outputs
  const total = outputs.reduce((n, o) => n + o.blob.size, 0)
  const busy = c.counts.working > 0 || c.combined.status === 'working'

  const canShare = useMemo(() => {
    if (!TOUCH || typeof navigator.canShare !== 'function') return false
    try {
      return navigator.canShare({ files: [new File([''], 'x.jpg', { type: 'image/jpeg' })] })
    } catch {
      return false
    }
  }, [])

  async function downloadAll() {
    setMessage(null)
    if (outputs.length === 1) return downloadBlob(outputs[0].blob, outputs[0].name)
    if (total > ZIP_LIMIT) {
      setMessage(`These files add up to ${formatBytes(total)}, too much for one ZIP on this device. Download them one at a time instead.`)
      return
    }
    setZipping(true)
    try {
      const zip = await zipOutputs(outputs)
      const to = c.target ? FORMATS[c.target].ext : 'files'
      downloadBlob(zip, `tabmorph-${outputs.length}-${to}-files.zip`)
    } finally {
      setZipping(false)
    }
  }

  async function share() {
    setMessage(null)
    const files = outputs.map((o) => new File([o.blob], o.name, { type: o.blob.type }))
    try {
      await navigator.share({ files })
    } catch (err) {
      if ((err as Error)?.name !== 'AbortError') setMessage('Sharing didn’t work here. Use Download instead.')
    }
  }

  const source = mode.kind === 'pair' ? mode.pair.from : mode.kind === 'source' ? mode.from : undefined
  const fromLabel = source ? FORMATS[source].label : null
  const accept = source ? [...FORMATS[source].accept, FORMATS[source].mime].join(',') : ALL_ACCEPT.join(',')
  const reorder = c.isCombined && c.items.length > 1
  const doneLabel =
    c.counts.total === 0
      ? ''
      : busy
        ? `Converting ${Math.min(c.counts.done + c.counts.error + 1, c.counts.total)} of ${c.counts.total}…`
        : c.counts.error
          ? `${c.counts.done} converted, ${c.counts.error} couldn’t be`
          : `${c.counts.done} file${c.counts.done === 1 ? '' : 's'} converted`
  const networkCount = c.network.main + c.network.workers

  return (
    <div className="relative flex h-dvh flex-col bg-background">
      <input
        ref={inputRef}
        type="file"
        multiple
        accept={accept}
        className="sr-only"
        tabIndex={-1}
        aria-hidden
        onChange={(e) => {
          void add([...(e.target.files ?? [])])
          e.target.value = ''
        }}
      />

      {!embedded && (
        <header className="flex items-center gap-3 border-b px-4 py-2.5">
          <a href={`${SITE_URL}/`} className="rounded-md">
            <Logo />
          </a>
          <span className="hidden text-sm text-muted-foreground sm:inline">{mode.kind === 'pair' ? `${pairLabel(mode.pair)} converter` : fromLabel ? `${fromLabel} converter` : 'File converter'} · in its own tab, no ads</span>
          <a href={`${SITE_URL}/how-it-works`} className="ml-auto text-sm text-muted-foreground hover:text-foreground">
            How it works
          </a>
        </header>
      )}

      {c.target && ['pdf','png','jpg'].includes(c.target) && froms.some(f => ['docx','xlsx','pptx','odt','ods','odp','rtf','xls','ppt','csv','tsv'].includes(f)) && (
        <div className="px-3 py-2 sm:px-4"><Notice>Office page conversion needs a desktop browser and about 2 GB of available memory. The initial download is about 139 MB. A stalled conversion is retried once and may take about four minutes. Review fonts and page breaks in the result. Thai text extraction varies between PDF readers.{froms.some(f => f === 'xlsx' || f === 'xls') && ' Review historical financial/date formulas and error values; some Excel edge cases differ.'}</Notice></div>
      )}

      {/* Toolbar: what converts to what, and the settings */}
      <div className="flex min-h-12 items-center gap-2 border-b px-3 py-1.5 sm:px-4">
        <div className="flex min-w-0 items-center gap-1.5">
          {froms.length ? (
            <>
              {froms.slice(0, 3).map((f) => (
                <FormatChip key={f} format={f} />
              ))}
              {froms.length > 3 && <span className="text-xs text-muted-foreground">+{froms.length - 3}</span>}
            </>
          ) : (
            <span className="text-sm font-medium">Any file</span>
          )}
          <ArrowRightIcon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden />
          {mode.kind === 'pair' ? (
            <FormatChip format={mode.pair.to} />
          ) : targets.length ? (
            <Select value={c.target ?? undefined} onValueChange={(v) => c.setTarget(v as Format)}>
              <SelectTrigger size="sm" className="h-7 font-mono text-xs font-semibold uppercase" aria-label="Convert to">
                <SelectValue placeholder="Choose" />
              </SelectTrigger>
              <SelectContent position="popper" align="start" className="max-h-80">
                {targets.map((t) => (
                  <SelectItem key={t} value={t} className="font-mono text-xs font-semibold uppercase">
                    {FORMATS[t].label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          ) : (
            <span className="text-sm text-muted-foreground">JPG, PNG, PDF…</span>
          )}
        </div>
        <div className="ml-auto flex min-w-0 items-center gap-2">
          {!settingsOpen && summary && <span className="hidden min-w-0 truncate text-xs text-muted-foreground md:block">{summary}</span>}
          <Button variant={settingsOpen ? 'secondary' : 'ghost'} size="sm" onClick={() => setSettingsOpen((o) => !o)} aria-expanded={settingsOpen} aria-controls="settings">
            <Settings2Icon />
            Settings
            <ChevronDownIcon className={cn('transition-transform', settingsOpen && 'rotate-180')} />
          </Button>
        </div>
      </div>
      {settingsOpen && (
        <div id="settings" className="max-h-[60%] shrink-0 overflow-y-auto border-b bg-muted/30 px-3 py-4 sm:px-4">
          <OptionsPanel visible={visible} options={c.options} setOptions={c.setOptions} to={c.target} />
        </div>
      )}

      <main className="min-h-0 flex-1 overflow-y-auto">
        {c.items.length === 0 ? (
          <div className="flex h-full min-h-72 flex-col p-3 sm:p-4">
            <div
              onClick={open}
              className="group flex flex-1 cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-border bg-[radial-gradient(ellipse_at_center,var(--brand-soft),transparent_70%)] px-4 py-8 text-center transition-colors hover:border-brand/50"
            >
              <div className="flex size-14 items-center justify-center rounded-2xl bg-brand text-brand-foreground shadow-sm ring-8 ring-brand/10 transition-transform group-hover:-translate-y-0.5">
                <UploadIcon className="size-6" />
              </div>
              <p className="mt-5 text-lg font-semibold tracking-tight text-balance">{source ? `Drop ${fromLabel} ${nounFor(source)} here` : 'Drop files here to convert them'}</p>
              <p className="mt-1 max-w-sm text-sm text-pretty text-muted-foreground">
                {mode.kind === 'pair' ? `They become ${FORMATS[mode.pair.to].label} files right here in your browser.` : mode.kind === 'source' ? 'Choose an output format above. Your files stay on this device.' : 'Images, PDFs, documents, tables, archives, fonts, audio and video. Nothing is uploaded.'}
              </p>
              <Button
                size="lg"
                className="mt-5 h-10 px-5"
                onClick={(e) => {
                  e.stopPropagation()
                  open()
                }}
              >
                Choose files
              </Button>
              <p className="mt-3 text-xs text-muted-foreground">
                {TOUCH ? `Up to ${MAX_FILES} files at once` : `or paste with ${MAC ? '⌘V' : 'Ctrl+V'} · up to ${MAX_FILES} files at once`}
              </p>
            </div>
          </div>
        ) : (
          <div className="space-y-2.5 p-3 sm:p-4">
            {c.limitHit && <Notice tone="warn">Tabmorph converts up to {MAX_FILES} files at a time. Download these, then clear the list and add the rest.</Notice>}
            {c.stale && (
              <Notice
                action={
                  <Button size="sm" onClick={c.reconvert}>
                    Convert again
                  </Button>
                }
              >
                Settings changed. Convert again to apply them.
              </Notice>
            )}
            {message && <Notice tone="warn">{message}</Notice>}
            {!c.stale && c.canRetry && <Notice action={<Button size="sm" onClick={c.retryFailed}>Retry conversion</Button>}>Review the error and settings, then retry the failed files.</Notice>}
            {IOS && busy && c.counts.total > 3 && <Notice>Keep this tab open until it finishes. iOS pauses tabs in the background.</Notice>}
            {c.isCombined && c.combined.status !== 'idle' && <CombinedCard combined={c.combined} />}
            <ul className="space-y-2" aria-label="Files">
              {c.items.map((item, index) => (
                <FileRow key={item.id} item={item} index={index} count={c.items.length} reorder={reorder} combined={c.isCombined} onRemove={() => c.remove(item.id)} onMove={(d) => c.move(item.id, d)} />
              ))}
            </ul>
            {c.items.length < MAX_FILES && (
              <button type="button" onClick={open} className="flex h-11 w-full items-center justify-center gap-1.5 rounded-xl border border-dashed text-sm text-muted-foreground transition-colors hover:border-brand/50 hover:text-foreground">
                <PlusIcon className="size-4" />
                Add more files
              </button>
            )}
          </div>
        )}
      </main>

      {c.items.length > 0 && (
        <div className="relative flex shrink-0 flex-wrap items-center gap-2 border-t bg-background px-3 py-2.5 sm:px-4">
          {busy && <div className="absolute inset-x-0 -top-px h-0.5 origin-left bg-brand transition-transform" style={{ transform: `scaleX(${(c.counts.done + c.counts.error) / Math.max(1, c.counts.total)})` }} />}
          <p className="mr-auto text-sm font-medium tabular-nums" aria-live="polite">
            {doneLabel}
            {!busy && outputs.length > 0 && <span className="font-normal text-muted-foreground"> · {formatBytes(total)}</span>}
          </p>
          <Button variant="ghost" size="sm" onClick={c.clear} className="text-muted-foreground">
            <Trash2Icon />
            Clear
          </Button>
          {canShare && outputs.length > 0 && (
            <Button variant="outline" onClick={share} disabled={busy}>
              <ShareIcon />
              Save or share
            </Button>
          )}
          <Button onClick={downloadAll} disabled={!outputs.length || busy || zipping}>
            {zipping ? <LoaderCircleIcon className="animate-spin" /> : <DownloadIcon />}
            {outputs.length === 1 ? `Download ${FORMATS[c.target ?? 'pdf'].label}` : `Download all${outputs.length ? ` (${outputs.length})` : ''}`}
          </Button>
        </div>
      )}

      <footer className="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-0.5 border-t bg-muted/40 px-3 py-1.5 text-[11px] text-muted-foreground sm:px-4">
        <span className="flex items-center gap-1">
          <ShieldCheckIcon className="size-3.5 text-success" aria-hidden />
          Files stay in this tab
        </span>
        <span className="tabular-nums" aria-live="polite">
          {c.network.since === null
            ? 'Nothing is uploaded'
            : `${networkCount} network request${networkCount === 1 ? '' : 's'} since you added files${networkCount ? ' (converter code, never your files)' : ''}`}
        </span>
        {c.readyError && <span role="alert">{c.readyError}</span>}
        {c.ready && (
          // Only the formats loaded so far work offline; others load their code when added, and
          // pdf.js can still fetch a font or character map a particular PDF needs.
          <span
            className="flex items-center gap-1"
            title="The code for these formats is loaded, so converting them needs no network. Other formats load their code when you add them."
          >
            <WifiOffIcon className="size-3.5" aria-hidden />
            {(source && c.target ? `${pairLabel({ from: source, to: c.target })} works offline now` : 'These formats work offline now')}
          </span>
        )}
      </footer>

      {dragging && (
        <div className="pointer-events-none absolute inset-2 z-50 flex flex-col items-center justify-center rounded-2xl border-2 border-dashed border-brand bg-background/85 backdrop-blur-sm">
          <UploadIcon className="size-8 text-brand" />
          <p className="mt-3 text-lg font-semibold">Drop to convert</p>
          <p className="text-sm text-muted-foreground">Files stay on this device</p>
        </div>
      )}
    </div>
  )
}
