import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

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

  const location = useLocation();
  const navigate = useNavigate();
  const [buttonState, setButtonState] = useState({
    isHovered: false,
    isActive: false,
  });
  const [inputValue, setInputValue] = useState('');
  const [error, setError] = useState('');

  const Breadcrumb = ({ path }) => {
    return (
      <nav style={styles.breadcrumb}>
        {path.map((item, index) => (
          <span key={index}>
            {index > 0 && ' > '}
            <a
              href={item.link}
              style={{
                ...styles.breadcrumbLink,
                fontWeight: location.pathname === item.link ? 'bold' : 'normal',
              }}
            >
              {item.name}
            </a>
          </span>
        ))}
      </nav>
    );
  };

  const breadcrumbPath = [
    { name: 'Application', link: '/application' },
    { name: 'Create Application ID', link: '/createApps' },
  ];

  const handleMouseEnter = () => setButtonState({ ...buttonState, isHovered: true });
  const handleMouseLeave = () => setButtonState({ ...buttonState, isHovered: false, isActive: false });
  const handleMouseDown = () => setButtonState({ ...buttonState, isActive: true });
  const handleMouseUp = () => setButtonState({ ...buttonState, isActive: false });

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
    if (error) setError(''); // Clear error when user starts typing
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!inputValue) {
      setError('Application name is required.');
    } else {
      const requestData = {
        name: inputValue,
        quota: 100,
        mode_id: 9,
        status_id: 1,
      };
  
      try {
        const response = await fetch(`${BASE_URL}/application/add`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'accept': 'application/json',
            'x-api-key': `${API_KEY}`,
          },
          body: JSON.stringify(requestData),
        });
  
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
  
        const result = await response.json();
        console.log('Form submitted successfully:', result);
  
        // Tampilkan pesan sukses
        alert('Application ID created successfully!');
        
        navigate(-1);
  
      } catch (error) {
        console.error('Error creating application ID:', error);
        setError(`Application ID already exists`);
      }
    }
  };  

  return (
    <div style={styles.container}>
      <div style={styles.wrapper}>
        <Breadcrumb path={breadcrumbPath} />
        <h2 style={styles.header}>Create Application ID</h2>
        <form onSubmit={handleSubmit} style={styles.form}>
          <div className='col mb-3'>
            <input
              type="text"
              value={inputValue}
              onChange={handleInputChange}
              placeholder="Input your application name"
              style={styles.input}
              className="italic-placeholder"
              maxLength={15}
            />
            {error && <span style={styles.error}>{error}</span>}
          </div>
          <button
            type="submit"
            style={{
              ...styles.button,
              backgroundColor: buttonState.isActive
                ? '#4BA5E7'
                : buttonState.isHovered
                ? '#1A6FD9'
                : '#0542cc',
            }}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
            onMouseDown={handleMouseDown}
            onMouseUp={handleMouseUp}
          >
            <span style={styles.buttonText}>Create App ID</span>
          </button>
        </form>
      </div>
      <style>
        {`
          input::placeholder {
            font-style: italic;
          }

          @media (max-width: 600px) {
            .col {
              padding: 0;
            }
          }
        `}
      </style>
    </div>
  );
};

const styles = {
    container: {
        padding: '1rem',
        width: '100%',
        margin: '0',
        boxSizing: 'border-box',
    },
    wrapper: {
        display: 'flex',
        flexDirection: 'column',
        border: '1px solid #ddd',
        borderRadius: '8px',
        padding: '1.5rem',
        boxShadow: '0 2px 5px rgba(0, 0, 0, 0.1)',
        borderLeft: '5px solid #0542cc',
        backgroundColor: '#fff',
    },
    form: {
        display: 'flex',
        flexDirection: 'column',
    },
    header: {
        marginBottom: '1rem',
        fontSize: '1.5rem',
        textAlign: 'flex-start',
    },
    input: {
        width: '100%',
        padding: '0.75rem',
        marginBottom: '1rem',
        borderRadius: '6px',
        border: '1px solid #ccc',
        boxSizing: 'border-box',
        fontStyle: 'italic',
    },
    button: {
        padding: '0.5rem 1rem', // Ubah ukuran padding tombol untuk resize
        alignSelf: 'flex-start', // Menempatkan tombol di flex-start
        color: '#fff',
        border: 'none',
        borderRadius: '6px',
        cursor: 'pointer',
        transition: 'background-color 0.3s ease',
    },
    buttonText: {
        color: '#fff',
        fontWeight: '500',
    },
    breadcrumb: {
        marginBottom: '1rem',
        fontSize: '14px',
        display: 'flex',
        justifyContent: 'flex-start',
    },
    breadcrumbLink: {
        color: '#000',
        textDecoration: 'none',
    },
    error: {
        color: 'red',
        fontSize: '12px',
        marginTop: '-8px',
        marginBottom: '10px',
    },
};
  
  

export default CreateApps;
