import { useState, useEffect } from 'react';
import { AtomSpinner } from 'react-epic-spinners';
import { glassmorphic, neuromorphicInput2, glassButton } from "../../../styles/tailwindStyles";
import { getItemById } from './UniversalCrudHelpers';
import React from 'react';

const GetItemById = ({ model, id, endpoint , token}) => {

  const [formData, setFormData] = useState({
    model: model || '',
    id: id || "LeumasAPI" || '',
    endpoint: endpoint || ''
  });
  const [itemData, setItemData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);


  useEffect(() => {
    if (!token) {
      // Handle unauthenticated scenario here
    }
  }, [token]);

  const handleChange = (e) => {
    setFormData(prevState => ({ ...prevState, [e.target.name]: e.target.value }));
  }

  const handleGetById = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const item = await getItemById(formData.model, formData.id, formData.endpoint, token);
      setItemData(item);
      setIsLoading(false);
    } catch (error) {
      setIsLoading(false);
      setError("Failed to fetch the item by ID.");
      console.error("Failed to fetch the item by ID:", error);
    }
  };

  return (
    <div className='flex flex-col gap-2'>
      {
        (!model || !id || !endpoint) && (
          <div className={glassmorphic + " p-4 space-y-4 max-w-xs text-xs"} >
            <input className={neuromorphicInput2} name="model" placeholder="Model" value={formData.model} onChange={handleChange} />
            <input className={neuromorphicInput2} name="id" placeholder="ID" value={formData.id} onChange={handleChange} />
            <input className={neuromorphicInput2} name="endpoint" placeholder="Endpoint" value={formData.endpoint} onChange={handleChange} />
          </div>
        )
      }
      <button className={glassButton} onClick={handleGetById}>Fetch ID</button>

      {isLoading && (
        <div className="mt-4 flex justify-center">
          <AtomSpinner color="blue" />
        </div>
      )}

      {error && (
        <div className="mt-4 bg-red-200 text-red-700 p-3 rounded-md">
          {error}
        </div>
      )}

      {itemData && (
        <div>
          {/* Display the fetched item data. Adjust accordingly based on the structure of your data */}
          <pre>{JSON.stringify(itemData, null, 2)}</pre>
        </div>
      )}
    </div>
  )
}

export default GetItemById;
