import { useState } from 'react'
import axios from 'axios'
import './App.css'

export default function App() {
  const [param1, setParam1] = useState('')
  const [param2, setParam2] = useState('')
  const [result, setResult] = useState(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const handleSubmit = async (e) => {
    e.preventDefault()
    setLoading(true)
    setError('')
    setResult(null)

    try {
      const response = await axios.post('/api/predict/', {
        param1: parseFloat(param1),
        param2: parseFloat(param2)
      })
      setResult(response.data)
    } catch (err) {
      setError('Error during material identification.')
      console.error(err)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="container">
      <header>
        <h1>Material Identification: Talc</h1>
        <p>Based on SciANN and Hugging Face</p>
      </header>

      <div className="card">
        <h2>Input Parameters</h2>
        <form onSubmit={handleSubmit}>
          <div className="input-group">
            <label>Parameter 1 (Stress):</label>
            <input
              type="number"
              step="0.01"
              value={param1}
              onChange={(e) => setParam1(e.target.value)}
              required
            />
          </div>
          <div className="input-group">
            <label>Parameter 2 (Strain):</label>
            <input
              type="number"
              step="0.01"
              value={param2}
              onChange={(e) => setParam2(e.target.value)}
              required
            />
          </div>
          <button type="submit" disabled={loading}>
            {loading ? 'Analyzing...' : 'Identify Material'}
          </button>
        </form>

        {error && <p className="error">{error}</p>}

        {result && (
          <div className="result">
            <h3>Result</h3>
            <p><strong>Material:</strong> {result.material}</p>
            <p><strong>Confidence:</strong> {(result.confidence * 100).toFixed(2)}%</p>
            {result.properties && (
              <div>
                <h4>Predicted Properties</h4>
                <p>Stress: {result.properties.stress.toFixed(4)}</p>
                <p>Strain: {result.properties.strain.toFixed(4)}</p>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
