import { Field, Input, Button, Card, Subtitle2, Caption1 } from '@fluentui/react-components'
import { CookiesRegular } from '@fluentui/react-icons'
import { COOKIE_BROWSERS, type CookieSource, type CookieBrowser } from '@shared/ipc'
import { useSettings } from '../../store/settings'
import { Select } from '../../components/Select'
import { useErrorTextStyles } from '../../components/ui/errorText'
import { useSettingsStyles } from './settingsStyles'
import { useCookiesCard } from './useCookiesCard'

const COOKIE_SOURCE_OPTIONS = [
  { value: 'none', label: 'None' },
  { value: 'browser', label: "From a browser's cookie store" },
  { value: 'login', label: 'Sign-in window (built into AeroFetch)' }
]

const COOKIE_BROWSER_OPTIONS = COOKIE_BROWSERS.map((b) => ({
  value: b,
  label: b.charAt(0).toUpperCase() + b.slice(1)
}))

export function CookiesCard(): React.JSX.Element {
  const styles = useSettingsStyles()
  const errText = useErrorTextStyles()
  const cookieSource = useSettings((s) => s.cookieSource)
  const cookiesBrowser = useSettings((s) => s.cookiesBrowser)
  const update = useSettings((s) => s.update)

  // View-model hook owns the cookies status + sign-in orchestration (L93/CC13).
  const { cookiesStatus, loginUrl, setLoginUrl, signingIn, loginError, signIn, clearSavedCookies } =
    useCookiesCard()

  return (
    <Card className={styles.card}>
      <div className={styles.sectionHeader}>
        <CookiesRegular className={styles.sectionIcon} />
        <Subtitle2 as="h3">Cookies</Subtitle2>
      </div>
      <Caption1 className={styles.hint}>
        Some sites only serve full quality, age-restricted, or members-only video to a logged-in
        session. Supply cookies so yt-dlp can act like one.
      </Caption1>

      <Field label="Cookie source">
        <Select
          value={cookieSource}
          options={COOKIE_SOURCE_OPTIONS}
          onChange={(v) => update({ cookieSource: v as CookieSource })}
        />
      </Field>

      {cookieSource === 'browser' && (
        <Field
          label="Browser"
          hint="Reads that browser's saved cookies directly. Close the browser first if it won't let AeroFetch read them."
        >
          <Select
            value={cookiesBrowser}
            options={COOKIE_BROWSER_OPTIONS}
            onChange={(v) => update({ cookiesBrowser: v as CookieBrowser })}
          />
        </Field>
      )}

      {cookieSource === 'login' && (
        <>
          <Field
            label="Site to sign in to"
            hint="Opens a sign-in window. Log in, then close the window -- your cookies are saved automatically."
          >
            <div className={styles.folderRow}>
              <Input
                className={styles.folderInput}
                value={loginUrl}
                placeholder="https://www.youtube.com"
                onChange={(_, d) => setLoginUrl(d.value)}
              />
              <Button appearance="primary" onClick={signIn} disabled={signingIn}>
                {signingIn ? 'Signing in…' : 'Sign in…'}
              </Button>
            </div>
          </Field>

          <div className={styles.folderRow}>
            <Caption1 className={styles.hint}>
              {cookiesStatus?.exists
                ? `Cookies saved ${new Date(cookiesStatus.savedAt!).toLocaleString()}.`
                : 'Not signed in yet.'}
            </Caption1>
            {cookiesStatus?.exists && (
              <Button size="small" onClick={clearSavedCookies}>
                Clear saved cookies
              </Button>
            )}
          </div>

          {loginError && <Caption1 className={errText.error}>{loginError}</Caption1>}
        </>
      )}
    </Card>
  )
}
