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

function App() {
  const [address, setAddress] = useState('')
  const [loading, setLoading] = useState(false)
  const [results, setResults] = useState(null)
  const [error, setError] = useState(null)

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

    try {
      const response = await fetch('http://localhost:5001/address', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ address }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      console.log('Response data:', data) // Debug log
      setResults(data)
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="app">
      <div className="container">
        <h1>🏠 TrueDoor Property Lookup</h1>
        <p className="subtitle">Test your backend address lookup</p>

        <form onSubmit={handleSubmit} className="form">
          <div className="input-group">
            <label htmlFor="address">Enter Address:</label>
            <input
              id="address"
              type="text"
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              placeholder="e.g., 123 Main St, Miami, FL"
              disabled={loading}
              required
            />
          </div>
          <button type="submit" disabled={loading || !address.trim()}>
            {loading ? 'Looking up...' : '🔍 Lookup Property'}
          </button>
        </form>

        {error && (
          <div className="error">
            <strong>Error:</strong> {error}
          </div>
        )}

        {results && (
          <div className="results">
            <h2>Results for: {results.address}</h2>
            
            {results.estimate ? (
              <div className="estimate-card">
                <h3>🤖 AI Property Estimate</h3>
                <div className="estimate-content">
                  {results.estimate.includes('unavailable') || results.estimate.includes('Error') || results.estimate.includes('No property data') ? (
                    <p style={{color: '#c33'}}>{results.estimate}</p>
                  ) : (
                    results.estimate.split('\n').filter(line => line.trim()).map((line, index) => (
                      <p key={index} className={line.includes('Estimated Market Value') || (line.includes('$') && line.length < 100) ? 'estimate-value' : ''}>
                        {line}
                      </p>
                    ))
                  )}
                </div>
              </div>
            ) : (
              <div className="estimate-card" style={{opacity: 0.6}}>
                <h3>🤖 AI Property Estimate</h3>
                <p>No estimate available. Check console for details.</p>
              </div>
            )}
            
            {results.results && results.results.length > 0 ? (
              <div className="property-list">
                {results.results.map((property, index) => (
                  <div key={index} className="property-card">
                    <h3>Property #{index + 1}</h3>
                    <div className="property-grid">
                      <div className="property-item">
                        <span className="label">Street:</span>
                        <span className="value">{property.street || 'N/A'}</span>
                      </div>
                      <div className="property-item">
                        <span className="label">City:</span>
                        <span className="value">{property.city || 'N/A'}</span>
                      </div>
                      <div className="property-item">
                        <span className="label">State:</span>
                        <span className="value">{property.state || 'N/A'}</span>
                      </div>
                      <div className="property-item">
                        <span className="label">ZIP Code:</span>
                        <span className="value">{property.zip_code || 'N/A'}</span>
                      </div>
                      <div className="property-item">
                        <span className="label">Bedrooms:</span>
                        <span className="value">{property.beds || 'N/A'}</span>
                      </div>
                      <div className="property-item">
                        <span className="label">Bathrooms:</span>
                        <span className="value">{property.baths || 'N/A'}</span>
                      </div>
                      <div className="property-item">
                        <span className="label">Square Feet:</span>
                        <span className="value">{property.sqft ? `${property.sqft.toLocaleString()} sqft` : 'N/A'}</span>
                      </div>
                      <div className="property-item">
                        <span className="label">List Price:</span>
                        <span className="value">{property.list_price ? `$${property.list_price.toLocaleString()}` : 'N/A'}</span>
                      </div>
                      <div className="property-item">
                        <span className="label">Sold Price:</span>
                        <span className="value">{property.sold_price ? `$${property.sold_price.toLocaleString()}` : 'N/A'}</span>
                      </div>
                      {property.property_url && (
                        <div className="property-item full-width">
                          <span className="label">Property URL:</span>
                          <a href={property.property_url} target="_blank" rel="noopener noreferrer" className="link">
                            {property.property_url}
                          </a>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="no-results">
                <p>No properties found for this address.</p>
              </div>
            )}
            <div className="raw-json">
              <details>
                <summary>View Raw JSON</summary>
                <pre>{JSON.stringify(results, null, 2)}</pre>
              </details>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

export default App

