import React from 'react'
import { useState } from '@wordpress/element'
import { Button, Spinner, Notice } from '@wordpress/components'
import apiFetch from '@wordpress/api-fetch'
import { __ } from '@wordpress/i18n'

interface GenerateButtonProps {
  postId: number
  fetchStatus: () => void
  status: string | null
  activate_critical_css: string | boolean
}

const GenerateButton: React.FC<GenerateButtonProps> = ({ postId, fetchStatus, status, activate_critical_css }) => {
  const [loading, setLoading] = useState(false)
  const [message, setMessage] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  const handleGenerateClick = async () => {
    setLoading(true)
    setError(null)
    setMessage(null)

    try {
      const response = await apiFetch({
        path: `/easy-critical-css/v1/generate`,
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ identifier: postId })
      })

      if (!response || (response as any).code) {
        throw new Error((response as any).message || __('An error occurred.', 'easy-critical-css'))
      }

      setMessage(__('Critical CSS generation started successfully.', 'easy-critical-css'))

      fetchStatus()
    } catch (err) {
      console.error(err)
      if (err && typeof err === 'object' && 'message' in err) {
        setError((err as any).message)
      } else {
        setError(__('An unknown error occurred.', 'easy-critical-css'))
      }
    }

    setLoading(false)
  }

  const getButtonText = () => {
    if (loading) return <Spinner />
    if (status === 'completed' || status === 'expired') {
      return __('Re-Generate Critical CSS', 'easy-critical-css')
    }
    return __('Generate Critical CSS', 'easy-critical-css')
  }

  if (status === 'paused' || !activate_critical_css) {
    return null
  }

  return (
    <div style={{ marginTop: '10px' }}>
      {error && <div style={{ marginBottom: '10px' }}><Notice status="error" isDismissible onRemove={() => setError(null)}>{error}</Notice></div>}
      {message && <div style={{ marginBottom: '10px' }}><Notice status="success" isDismissible onRemove={() => setMessage(null)}>{message}</Notice></div>}

      <Button
        onClick={handleGenerateClick}
        variant='primary'
        style={{ width: '100%', justifyContent: 'center' }}
      >
        {getButtonText()}
      </Button>
    </div>
  )
}

export default GenerateButton
