import { useEffect, useState } from 'hono/jsx'
import { getWifiConfig, saveWifiConfig } from '../api'
import { navigate } from '../router'
import {
  Button,
  DashboardInstallCmd,
  FormActions,
  FormField,
  FormInput,
  FormLabel,
  HeaderActions,
  Main,
  MainContent,
  MainHeader,
  MainTitle,
  Section,
  SectionTitle,
} from '../styles'

export function SettingsPage({ render }: { render: () => void }) {
  const [network, setNetwork] = useState('')
  const [password, setPassword] = useState('')
  const [saving, setSaving] = useState(false)
  const [saved, setSaved] = useState(false)

  useEffect(() => {
    getWifiConfig().then(config => {
      setNetwork(config.network)
      setPassword(config.password)
    })
  }, [])

  const goBack = () => {
    navigate('/')
  }

  const handleSave = async (e: Event) => {
    e.preventDefault()
    setSaving(true)
    setSaved(false)
    await saveWifiConfig({ network, password })
    setSaving(false)
    setSaved(true)
  }

  return (
    <Main>
      <MainHeader centered>
        <MainTitle>Settings</MainTitle>
        <HeaderActions>
          <Button onClick={goBack}>Back</Button>
        </HeaderActions>
      </MainHeader>
      <MainContent centered>
        <Section>
          <SectionTitle>WiFi</SectionTitle>
          <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 400 }}>
            <FormField>
              <FormLabel>Network</FormLabel>
              <FormInput
                type="text"
                value={network}
                onInput={(e: Event) => setNetwork((e.target as HTMLInputElement).value)}
                placeholder="SSID"
              />
            </FormField>
            <FormField>
              <FormLabel>Password</FormLabel>
              <FormInput
                type="password"
                value={password}
                onInput={(e: Event) => setPassword((e.target as HTMLInputElement).value)}
                placeholder="Password"
              />
            </FormField>
            <FormActions>
              {saved && <span style={{ fontSize: 13, color: '#888', alignSelf: 'center' }}>Saved</span>}
              <Button variant="primary" type="submit" disabled={saving}>
                {saving ? 'Saving...' : 'Save'}
              </Button>
            </FormActions>
          </form>
        </Section>
        <Section>
          <SectionTitle>Install CLI</SectionTitle>
          <DashboardInstallCmd>
            curl -fsSL {location.origin}/install | bash
          </DashboardInstallCmd>
        </Section>
      </MainContent>
    </Main>
  )
}
