import React, { useState, useEffect } from 'react';
import { createItemsBulk } from "./UniversalCrudHelpers"; // Make sure to import createItemsBulk
import { AtomSpinner } from 'react-epic-spinners';
import { glassmorphic, glassButton, neuromorphicInput2 } from "../../../styles/tailwindStyles";
import { LeumasBaseStyle } from "../../../styles/baseStyles";
import { useAuthUser } from "react-auth-kit";

const CreateBulkItem = ({ model, endpoint, propDataArray, token }) => { // Note the propDataArray, expecting an array of data for bulk creation

  const [createdItems, setCreatedItems] = useState(null);
  const [formData, setFormData] = useState({
    model: model || '',
    endpoint: endpoint || 'LeumasAPI',
    data: propDataArray || [] // Ensure this is an array
  });
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const auth = useAuthUser();

  useEffect(() => {
    if (!token) {
      // Handle unauthenticated scenario here
      console.log("No token you must login")
    }
  }, [token]);

  const handleChange = (e) => {
    // Assuming that the input for bulk data will be a JSON array string
    if (e.target.name === 'data') {
      try {
        // Attempt to parse the JSON array string from the input
        const parsedData = JSON.parse(e.target.value);
        if (Array.isArray(parsedData)) {
          setFormData(prevState => ({ ...prevState, data: parsedData }));
        } else {
          setError('Data must be a JSON array.');
        }
      } catch (err) {
        setError('Invalid JSON format for data.');
      }
    } else {
      setFormData(prevState => ({ ...prevState, [e.target.name]: e.target.value }));
    }
  };

  const [isVisible, setIsVisible] = useState(true);

  const handleCreateBulk = async () => {
    const confirmation = window.confirm("Are you sure you want to create these items in bulk?");
    if (!confirmation) {
      return; // Early return if user clicked on "Cancel"
    }

    setIsLoading(true);
    setError(null);
    setIsVisible(true); // Ensure that the message is visible initially

    try {
      const result = await createItemsBulk(`${formData.model}`, formData.endpoint || "LeumasAPI", formData.data, token);
      setIsLoading(false);
      setCreatedItems(result);
      setTimeout(() => {
        setIsVisible(false);
      }, 15000);
    } catch (error) {
      setIsLoading(false);
      setError("Failed to create the items in bulk.");
      console.error("Failed to create the items in bulk:", error);
      setTimeout(() => {
        setIsVisible(false);
      }, 15000);
    }
  };

  useEffect(() => {
    setFormData({ ...formData, data: propDataArray }); // Ensure the form data is updated with the prop data array
  }, [propDataArray]);

  return (
    <div className='flex flex-col gap-2'>
      {
        (!model || !endpoint || !propDataArray) && (
          <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="endpoint" placeholder="Endpoint" value={formData.endpoint} onChange={handleChange} />
            <textarea className={neuromorphicInput2} name="data" placeholder="Data (JSON Array)" value={JSON.stringify(formData.data, null, 2)} onChange={handleChange} />
          </div>
        )
      }
      <button className={`${LeumasBaseStyle} ${glassButton}`} onClick={handleCreateBulk}>Create Bulk</button>

      {isLoading && (
        <div className="mt-4 flex justify-center">
          <AtomSpinner color="blue" />
        </div>
      )}
      {createdItems && isVisible && (
        <div className={`relative mt-4 bg-green-200 text-green-700 max-w-[150px] min-w-full p-3 rounded-md transition-opacity duration-1000 ease-out ${isVisible ? 'opacity-100' : 'opacity-0'}`}>
          <div className="absolute top-0 right-0 h-2 w-full bg-blue-500 animate-decreaseBorder" style={{ animationDuration: '15s' }}></div>
          <pre>{JSON.stringify(createdItems, null, 2)}</pre>
        </div>
      )}
      {error && isVisible && (
        <div className={`relative mt-4 bg-red-200 text-red-700 p-3 rounded-md transition-opacity duration-1000 ease-out ${isVisible ? 'opacity-100' : 'opacity-0'}`}>
          <div className="absolute top-0 right-0 h-2 w-full bg-blue-500 animate-decreaseBorder" style={{ animationDuration: '15s' }}></div>
          {error}
        </div>
      )}
    </div>
  )
}

export default CreateBulkItem;
