import { useEffect, useState } from 'react'
import type { CookiesStatus } from '@shared/ipc'
import { logError } from '../../reportError'

export interface CookiesCardController {
  cookiesStatus: CookiesStatus | null
  loginUrl: string
  setLoginUrl: (url: string) => void
  signingIn: boolean
  loginError: string | null
  signIn: () => Promise<void>
  clearSavedCookies: () => Promise<void>
}

/**
 * View-model for the Cookies card (L93/CC13): owns the saved-cookies status and
 * the sign-in-window orchestration so the card stays presentational.
 */
export function useCookiesCard(): CookiesCardController {
  const [cookiesStatus, setCookiesStatus] = useState<CookiesStatus | null>(null)
  const [loginUrl, setLoginUrl] = useState('https://www.youtube.com')
  const [signingIn, setSigningIn] = useState(false)
  const [loginError, setLoginError] = useState<string | null>(null)

  useEffect(() => {
    window.api.cookiesStatus().then(setCookiesStatus).catch(logError('cookiesStatus'))
  }, [])

  async function signIn(): Promise<void> {
    setSigningIn(true)
    setLoginError(null)
    try {
      const result = await window.api.cookiesLogin(loginUrl)
      if (result.ok && result.cookieCount === 0) {
        // Window closed without capturing anything -- don't imply success (L50).
        setLoginError('No cookies were captured -- did you sign in before closing the window?')
      } else if (result.ok) {
        setCookiesStatus(await window.api.cookiesStatus())
      } else {
        setLoginError(result.error ?? 'Sign-in failed.')
      }
    } catch (e) {
      setLoginError(e instanceof Error ? e.message : String(e))
    } finally {
      setSigningIn(false)
    }
  }

  async function clearSavedCookies(): Promise<void> {
    await window.api.cookiesClear()
    setCookiesStatus({ exists: false })
  }

  return { cookiesStatus, loginUrl, setLoginUrl, signingIn, loginError, signIn, clearSavedCookies }
}
