import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlus } from '@fortawesome/free-solid-svg-icons';

const Applications = () => {
  const BASE_URL = process.env.REACT_APP_BASE_URL;
  const API_KEY = process.env.REACT_APP_API_KEY;

  const [applications, setApplications] = useState([]);
  const [buttonStates, setButtonStates] = useState([]);
  const [copiedIndex, setCopiedIndex] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState('');
  const [errorMessage, setErrorMessage] = useState(null);
  const [isMobile, setIsMobile] = useState(window.innerWidth <= 768); // Check if mobile

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
    }, 500);
    return () => clearTimeout(timer);
  }, [searchTerm]);

  useEffect(() => {
    const fetchApplications = async () => {
      if (debouncedSearchTerm) {
        try {
          const response = await fetch(`${BASE_URL}/application/get-by-name/${debouncedSearchTerm}`, {
            method: 'GET',
            headers: {
              'accept': 'application/json',
              'x-api-key': API_KEY,
            },
          });
          
          const result = await response.json();

          if (response.ok) {
            if (result.details && result.details.data) {
              setApplications([result.details.data]);
              setButtonStates([{ isHovered: false, isActive: false }]);
              setErrorMessage(null);
            } else {
              setApplications([]);
              setErrorMessage('Data is not found.');
            }
          } else {
            setApplications([]);
            setErrorMessage('Data is not found.');
          }
        } catch (error) {
          console.error('Error fetching applications:', error);
          setApplications([]);
          setErrorMessage('Data is not found.');
        }
      } else {
        const fetchAllApplications = async () => {
          try {
            const response = await fetch(`${BASE_URL}/application/list`, {
              method: 'GET',
              headers: {
                'x-api-key': API_KEY,
              },
            });
            const result = await response.json();
            if (response.ok && result.status_code === 200) {
              setApplications(result.details.data);
              setButtonStates(result.details.data.map(() => ({ isHovered: false, isActive: false })));
              setErrorMessage(null);
            } else {
              setApplications([]);
              setErrorMessage('Error fetching data. Please try again.');
            }
          } catch (error) {
            console.error('Error fetching all applications:', error);
            setApplications([]);
            setErrorMessage('Error fetching data. Please try again.');
          }
        };

        fetchAllApplications();
      }
    };

    fetchApplications();
  }, [debouncedSearchTerm]);

  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth <= 768); // Update state based on window size
    };
    
    window.addEventListener('resize', handleResize); // Add resize event listener
    
    return () => {
      window.removeEventListener('resize', handleResize); // Cleanup event listener on unmount
    };
  }, []);

  const handleMouseEnter = (index) => {
    setButtonStates((prevStates) => {
      const newStates = [...prevStates];
      newStates[index].isHovered = true;
      return newStates;
    });
  };

  const handleMouseLeave = (index) => {
    setButtonStates((prevStates) => {
      const newStates = [...prevStates];
      newStates[index].isHovered = false;
      return newStates;
    });
  };

  const handleCopy = (index, appName) => {
    navigator.clipboard.writeText(appName)
      .then(() => {
        setCopiedIndex(index);
        setTimeout(() => setCopiedIndex(null), 2000);
      })
      .catch(err => console.error('Failed to copy: ', err));
  };

  return (
    <div style={styles.container}>
      <h1 style={styles.title}>List of Applications</h1>
      <input
        type="text"
        placeholder="Type your keywords here"
        style={styles.searchInput}
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <div style={styles.wrapperCard(isMobile)}>
        <div style={styles.createButtonContainer}>
          <Link to="/createApps" style={styles.link}>
            <button style={styles.createButton}>
              <FontAwesomeIcon icon={faPlus} style={{ marginRight: '8px' }} /> 
              Create New App ID
            </button>
          </Link>
        </div>
        {errorMessage ? (
          <p>{errorMessage}</p>
        ) : (
          <div style={styles.cardsContainer(isMobile)}>
            {applications.map((application, index) => (
              <div
                key={application.id || index}
                style={styles.card}
                onMouseEnter={() => handleMouseEnter(index)}
                onMouseLeave={() => handleMouseLeave(index)}
              >
                <h2>{application.name}</h2>
                <p><strong>Application ID:</strong> {application.id}</p>
                <p><strong>Date & Time:</strong> 
                  {application.created_at ? new Date(application.created_at).toLocaleString() : "Date not available"}
                </p>
                <button
                  onClick={() => handleCopy(index, application.name)}
                  style={styles.copyButton}
                >
                  {copiedIndex === index ? 'Copied!' : 'Copy'}
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default Applications;

const styles = {
  container: {
    padding: '20px',
    fontFamily: 'Arial, sans-serif',
    color: '#333',
  },
  title: {
    fontSize: '24px',
    color: '#003399',
    marginBottom: '10px',
  },
  searchInput: {
    width: '100%',
    padding: '10px',
    marginBottom: '20px',
    borderRadius: '5px',
    border: '1px solid #ddd',
  },
  wrapperCard: (isMobile) => ({
    border: '0.2px solid gray',
    borderLeft: '5px solid #0542cc',
    borderRadius: '5px',
    boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
    padding: isMobile ? '15px' : '22px', // Adjust padding dynamically based on device
    overflow: 'hidden',
    margin: '0 auto',
    maxWidth: '1200px',
  }),
  createButtonContainer: {
    textAlign: 'start',
    marginBottom: '20px',
  },
  createButton: {
    padding: '10px 20px',
    backgroundColor: '#003399',
    color: '#fff',
    border: 'none',
    borderRadius: '5px',
    cursor: 'pointer',
  },
  link: {
    textDecoration: 'none',
  },
  cardsContainer: (isMobile) => ({
    display: 'grid',
    gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', // Stack cards on mobile
    gap: isMobile ? '15px' : '20px', // Adjust gap based on device
    width: '100%',
    boxSizing: 'border-box',
  }),
  card: {
    padding: '15px',
    backgroundColor: '#f9f9f9',
    borderRadius: '8px',
    boxShadow: '0px 4px 8px rgba(0, 0, 0, 0.1)',
    border: '1px solid #ddd',
    maxWidth: '100%',
    boxSizing: 'border-box',
  },
  copyButton: {
    marginTop: '10px',
    padding: '8px 12px',
    backgroundColor: '#003399',
    color: '#fff',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
  },
};
