import React, { useState, useEffect } from 'react';
import '../App.css';
import SearchBar from '../components/SearchBar';
import MedicineResults from '../components/MedicineResults';
import PharmacyList from '../components/PharmacyList';

function PublicView() {
  const [searchQuery, setSearchQuery] = useState('');
  const [medicines, setMedicines] = useState([]);
  const [selectedMedicine, setSelectedMedicine] = useState(null);
  const [pharmacies, setPharmacies] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const searchMedicines = async () => {
      if (searchQuery.trim().length < 2) {
        setMedicines([]);
        setSelectedMedicine(null);
        setPharmacies([]);
        return;
      }

      setLoading(true);
      try {
        const response = await fetch(`/api/medicines/search?q=${encodeURIComponent(searchQuery)}`);
        const data = await response.json();
        setMedicines(data);
      } catch (error) {
        console.error('Error searching medicines:', error);
      } finally {
        setLoading(false);
      }
    };

    const timeoutId = setTimeout(searchMedicines, 300);
    return () => clearTimeout(timeoutId);
  }, [searchQuery]);

  useEffect(() => {
    const fetchPharmacies = async () => {
      if (!selectedMedicine) {
        setPharmacies([]);
        return;
      }

      setLoading(true);
      try {
        const response = await fetch(`/api/medicines/${selectedMedicine.id}/pharmacies`);
        const data = await response.json();
        setPharmacies(data);
      } catch (error) {
        console.error('Error fetching pharmacies:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchPharmacies();
  }, [selectedMedicine]);

  return (
    <>
      <header className="app-header">
        <h1>💊 FarmaFinder</h1>
        <p>Find your medicine at nearby pharmacies</p>
      </header>

      <main className="app-main">
        <SearchBar 
          value={searchQuery}
          onChange={setSearchQuery}
          placeholder="Search for a medicine..."
        />

        {loading && <div className="loading">Searching...</div>}

        {searchQuery && !selectedMedicine && (
          <MedicineResults 
            medicines={medicines}
            onSelect={setSelectedMedicine}
            query={searchQuery}
          />
        )}

        {selectedMedicine && (
          <div className="selected-medicine-section">
            <div className="medicine-info">
              <h2>{selectedMedicine.name}</h2>
              <div className="medicine-details">
                <span><strong>Active Ingredient:</strong> {selectedMedicine.active_ingredient}</span>
                <span><strong>Dosage:</strong> {selectedMedicine.dosage}</span>
                <span><strong>Form:</strong> {selectedMedicine.form}</span>
              </div>
              <button 
                className="back-button"
                onClick={() => {
                  setSelectedMedicine(null);
                  setPharmacies([]);
                }}
              >
                ← Back to search
              </button>
            </div>

            <PharmacyList 
              pharmacies={pharmacies}
              loading={loading}
            />
          </div>
        )}
      </main>
    </>
  );
}

export default PublicView;

