import type { App } from '../../shared/types'
import { closeModal, openModal, rerenderModal } from '../components/modal'
import { navigate } from '../router'
import { selectedApp } from '../state'
import { Button, Form, FormActions, FormError, FormField, FormInput, FormLabel } from '../styles'
import { theme } from '../themes'

let deleteAppError = ''
let deleteAppDeleting = false
let deleteAppTarget: App | null = null

async function deleteApp(input: HTMLInputElement) {
  if (!deleteAppTarget) return

  const expected = `sudo rm ${deleteAppTarget.name}`
  const value = input.value.trim()

  if (value !== expected) {
    deleteAppError = `Type "${expected}" to confirm`
    rerenderModal()
    return
  }

  deleteAppDeleting = true
  deleteAppError = ''
  rerenderModal()

  try {
    const res = await fetch(`/api/sync/apps/${deleteAppTarget.name}`, {
      method: 'DELETE',
    })
    if (!res.ok) {
      throw new Error(`Failed to delete app: ${res.statusText}`)
    }

    // Success - close modal and navigate to dashboard
    closeModal()
    if (selectedApp === deleteAppTarget.name) {
      navigate('/')
    }
  } catch (err) {
    deleteAppError = err instanceof Error ? err.message : 'Failed to delete app'
    deleteAppDeleting = false
    rerenderModal()
  }
}

export function openDeleteAppModal(app: App) {
  deleteAppError = ''
  deleteAppDeleting = false
  deleteAppTarget = app

  const expected = `sudo rm ${app.name}`

  openModal('Delete App', () => (
    <Form onSubmit={(e: Event) => {
      e.preventDefault()
      const input = (e.target as HTMLFormElement).querySelector('input') as HTMLInputElement
      deleteApp(input)
    }}>
      <p style={{ margin: '0 0 16px', color: theme('colors-textMuted') }}>
        This will <strong style={{ color: theme('colors-error') }}>permanently delete</strong> <strong>{app.name}</strong> from the server.
      </p>
      <FormField>
        <FormLabel for="delete-confirm">Type "{expected}" to confirm</FormLabel>
        <FormInput
          id="delete-confirm"
          type="text"
          placeholder={expected}
          autofocus
        />
        {deleteAppError && <FormError>{deleteAppError}</FormError>}
      </FormField>
      <FormActions>
        <Button type="button" onClick={closeModal} disabled={deleteAppDeleting}>
          Cancel
        </Button>
        <Button type="submit" variant="danger" disabled={deleteAppDeleting}>
          {deleteAppDeleting ? 'Deleting...' : 'Delete App'}
        </Button>
      </FormActions>
    </Form>
  ))
}
