import React, { useState, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faShieldAlt } from '@fortawesome/free-solid-svg-icons';
import Select from 'react-select';

const BASE_URL = process.env.REACT_APP_BASE_URL;
const API_KEY = process.env.REACT_APP_API_KEY;


const Admin = () => {

  const [isLoading, setIsLoading] = useState(false);
  const [applicationId, setApplicationId] = useState('');
  const [inputValueApplication, setInputValueApplication] = useState('');
  const [applicationIds, setApplicationIds] = useState([]);
  const [isMobile, setIsMobile] = useState(false);


  const applicationOptions = applicationIds.map(app => ({
    value: app.id,
    label: app.name
  }));

  const handleApplicationChange = (selectedOption) => {
    if (selectedOption) {
      const selectedId = selectedOption.value;
      const selectedApp = applicationIds.find(app => app.id === parseInt(selectedId));
      if (selectedApp) {
        setApplicationId(selectedId);
      }
    }
  };

  const handleInputChangeApplication = (newInputValue) => {
    if (newInputValue.length <= 15) {
      setInputValueApplication(newInputValue);
    }
  };

  const fetchApplicationIds = async () => {
    try {
      const response = await fetch(`${BASE_URL}/application/list`, {
        method: 'GET',
        headers: {
          'accept': 'application/json',
          'x-api-key': API_KEY,
        },
      });
      const data = await response.json();
      return data.details.data;
    } catch (error) {
      console.error('Error fetching application IDs:', error);
      return [];
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      const data = await fetchApplicationIds();
      setApplicationIds(data);
      setIsLoading(false);
    };

    fetchData();

    const checkIfMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };

    checkIfMobile();
    window.addEventListener('resize', checkIfMobile);
    return () => window.removeEventListener('resize', checkIfMobile);
  }, []); 
  
  const styles = {
    container: {
      padding: '1rem',
      width: '100%',
      margin: '0 auto',
      boxSizing: 'border-box',
    },
    wrapper: {
      display: 'flex',
      flexDirection: 'column',
      borderRadius: '8px',
      padding: '1.5rem',
      maxWidth: '1200px',
      margin: '0 auto',
    },
    wrapperMobile: {
      display: 'flex',
      flexDirection: 'column',
      borderRadius: '8px',
      padding: '1rem',      
    },
    welcomeCard: {
      backgroundColor: '#E2FBEA',
      borderLeft: '4px solid #0542CC',
      borderRadius: '5px',
      marginBottom: '20px',
    },
    section: {
      padding: '20px',
      border: '0.1px solid rgba(0, 0, 0, 0.2)',
      borderLeft: '4px solid #0542CC',
      borderRadius: '10px',
      width: '100%',
    },
    loadingOverlay: {
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(0, 0, 0, 0.2)',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      zIndex: 1000,
    },
    spinner: {
      border: '4px solid rgba(0, 0, 0, 0.1)',
      borderLeftColor: '#0542cc',
      borderRadius: '50%',
      width: '90px',
      height: '90px',
      animation: 'spin 1s ease-in-out infinite',
    },
    select: {
      width: '100%',
      paddingRight: '30px',
      fontSize: '16px',
      border: '1px solid #ccc',
      outline: 'none',
    }
  };

  return (
    <>
      <style>
        {`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        `}
      </style>

      {isLoading && (
        <div style={styles.loadingOverlay}>
          <div style={styles.spinner}></div>
        </div>
      )}
      <div style={styles.container}>
        <div style={isMobile ? styles.wrapperMobile : styles.wrapper}>        
          {/* Static Content */}
          <div className="row-card border-left border-primary shadow mb-4" style={styles.welcomeCard}>
            <div className="d-flex flex-column justify-content-start align-items-start p-4">
              <h4 className="mb-3 text-start">
                {/* Menggunakan FontAwesomeIcon */}
                <FontAwesomeIcon icon={faShieldAlt} style={{ fontWeight: 'bold', marginRight: '10px' }} />
                Stay Safe & Secure
              </h4>
              <p className="mb-0 text-start">
                Get started now by creating an Application ID and explore all the demo services available on the dashboard.
                Experience the ease and flexibility of trying out all our features firsthand.
              </p>
            </div>
          </div>
          
          <div style={styles.section}>
            <div className="form-group row align-items-center">
              <h1>Admin Settings</h1>
              <p style={{color: '#1F2D3D'}}>Manage your security by setting or updating your Application ID PIN for enhanced protection and easy access control.</p>
              <div className="col-md-8 mt-3">
                <Select
                  id="applicationId"
                  value={applicationOptions.find(option => option.value === applicationId)}
                  onChange={handleApplicationChange}
                  options={applicationOptions}
                  placeholder="Select Application ID"
                  isSearchable
                  menuPortalTarget={document.body}
                  menuPlacement="auto"
                  inputValue={inputValueApplication}
                  onInputChange={handleInputChangeApplication}
                />
              </div>
            </div>
          </div>    

        </div>
      </div>
    </>
  );
};

export default Admin;

