import {
  Button,
  Card,
  Subtitle2,
  Caption1,
  Text,
  Spinner,
  ProgressBar,
  tokens
} from '@fluentui/react-components'
import {
  ArrowSyncRegular,
  ArrowDownloadRegular,
  OpenRegular,
  DismissRegular
} from '@fluentui/react-icons'
import { useErrorTextStyles } from '../../components/ui/errorText'
import { useSettingsStyles } from './settingsStyles'
import { useSoftwareUpdateCard } from './useSoftwareUpdateCard'

export function SoftwareUpdateCard(): React.JSX.Element {
  const styles = useSettingsStyles()
  const errText = useErrorTextStyles()

  // View-model hook owns the check → download → install orchestration (L93/CC13).
  const {
    appVersion,
    appUpd,
    appChecking,
    appDownloading,
    appFraction,
    appUpdError,
    checkAppUpdate,
    installAppUpdate,
    cancelDownload,
    openReleasePage
  } = useSoftwareUpdateCard()

  return (
    <Card className={styles.card}>
      <div className={styles.sectionHeader}>
        <ArrowSyncRegular className={styles.sectionIcon} />
        <Subtitle2 as="h3">Software update</Subtitle2>
      </div>
      <Caption1 className={styles.hint}>
        {appVersion
          ? `You're running AeroFetch v${appVersion}. Updates are fetched from the AeroFetch release repo.`
          : 'Checking your AeroFetch version…'}
      </Caption1>

      <div className={styles.folderRow}>
        <Button
          icon={appChecking ? <Spinner size="tiny" /> : <ArrowSyncRegular />}
          onClick={checkAppUpdate}
          disabled={appChecking || appDownloading}
        >
          {appChecking ? 'Checking…' : 'Check for updates'}
        </Button>
      </div>

      {appUpd?.ok && appUpd.available && (
        <>
          <Text style={{ fontWeight: tokens.fontWeightSemibold }}>
            Version {appUpd.latestVersion} is available -- here&apos;s what changed:
          </Text>
          {appUpd.notes && <div className={styles.notesBox}>{appUpd.notes}</div>}
          <div className={styles.folderRow}>
            <Button
              appearance="primary"
              icon={<ArrowDownloadRegular />}
              onClick={installAppUpdate}
              disabled={appDownloading || !appUpd.downloadUrl}
            >
              {appDownloading ? 'Downloading…' : 'Update now'}
            </Button>
            {appUpd.htmlUrl && (
              <Button icon={<OpenRegular />} onClick={openReleasePage}>
                View release
              </Button>
            )}
          </div>
          {!appUpd.downloadUrl && (
            <Caption1 className={styles.hint}>
              This release has no installer attached -- use "View release" to download it manually.
            </Caption1>
          )}
          {appDownloading && (
            <>
              <ProgressBar value={appFraction} aria-label="App update download progress" />
              {/* B6: a ~300 MB installer download can take a while — let the user abort it. */}
              <div className={styles.folderRow}>
                <Button
                  size="small"
                  appearance="subtle"
                  icon={<DismissRegular />}
                  onClick={cancelDownload}
                >
                  Cancel download
                </Button>
              </div>
            </>
          )}
        </>
      )}

      {appUpd?.ok && !appUpd.available && (
        <Text>You&apos;re up to date -- v{appUpd.currentVersion} is the latest.</Text>
      )}

      {appUpdError && <Caption1 className={errText.errorPre}>{appUpdError}</Caption1>}
    </Card>
  )
}
