import React, { useState, useEffect } from 'react';
import Select from 'react-select';

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

const Otp = () => {
  const [isSelectOpen, setIsSelectOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [applicationId, setApplicationId] = useState('');
  const [expiryId, setExpiryId] = useState(0);
  const [otpId, setOtpId] = useState('');
  const [messageId, setMessageId] = useState('');
  const [phoneId, setPhoneId] = 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) => {
    setApplicationId(selectedOption.value);
  };

  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 handleFocus = () => {
    setIsSelectOpen(true);
  };

  const handleBlur = () => {
    setIsSelectOpen(false);
  };

  const handleClick = () => {
    console.log('Make OTP Demo');
  };

  
const styles = {
    text: {
      fontSize: '16px',
      fontWeight: '400',
      margin: '0',
      marginTop: '8px',
    },
    remainingQuotaWrapper: {
      marginTop: '2vh',
    },
    remainingQuota: {
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'center',
      marginTop: '4px',
    },
    quotaText: {
      fontSize: '40px',
      color: '#0542cc',
      fontWeight: '600',
    },
    timesText: {
      marginLeft: '8px',
      verticalAlign: 'super',
      fontSize: '20px',
    },
    submitButton: {
      marginLeft: 'auto',
      marginTop: '4rem',
      textAlign: 'start',
      position: 'relative',
      zIndex: 1,
    },
    submitBtn: {
      backgroundColor: '#0542CC',
    },
    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',
    },
    OtpId: {
        marginTop: isMobile ? '2vh' : '0',
    },
    PhoneNumber: {
      marginTop: isMobile ? '2vh' : '-12vh',
    },
    textarea: {
      width: '100%',
      height: '200px',
      resize: 'none',
      border: '1px solid #ccc',
      outline: 'none',
    },
    characterCount: {
      display: 'flex',
      justifyContent: 'flex-end',
      marginTop: '8px',
    },
  };

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

      {isLoading && (
        <div style={styles.loadingOverlay}>
          <div style={styles.spinner}></div>
        </div>
      )}

      <div className="form-group row align-items-center">
        <div className="col-md-6">
          <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 className="col-md-6" style={styles.remainingQuotaWrapper}>
          <p style={styles.text}>Remaining Quota</p>
          <div style={styles.remainingQuota}>
            <span style={styles.quotaText}>0</span>
            <span style={styles.timesText}>(times)</span>
          </div>
        </div>
      </div>

      <div className="form-group row align-items-center">
        <div className="col-md-6">
          <input
            type="number"
            id="expiryId"
            className="form-control"
            style={styles.select}
            value={expiryId}
            onChange={(e) => setExpiryId(parseInt(e.target.value) || 0)}
            onFocus={handleFocus}
            onBlur={handleBlur}
            placeholder="Expiry Time"
          />
        </div>

        <div className="col-md-6" style={styles.OtpId}>
          <input
            type="text"
            id="otpId"
            className="form-control"
            placeholder="OTP Length"
            value={otpId}
            onChange={(e) => setOtpId(e.target.value)}
          />
        </div>
      </div>

      <div className="form-group row align-items-center mt-4">
        <div className="col-md-6">
          <textarea
            id="messageId"
            className="form-control"
            style={styles.textarea}
            value={messageId}
            onChange={(e) => setMessageId(e.target.value)}
            onFocus={handleFocus}
            onBlur={handleBlur}
            placeholder="Message Info"
          />
          <div style={styles.characterCount}>
            <p style={styles.text}>Character: 0 (Max. 459), SMS Count: 0</p>
          </div>
        </div>

        <div className="col-md-6">
          <div className="input-group" style={styles.PhoneNumber}>
            <span className="input-group-prepend">
              <span className="input-group-text">+62</span>
            </span>
            <input
              type="text"
              id="phoneId"
              className="form-control"
              placeholder="Phone Number"
              value={phoneId}
              onChange={(e) => setPhoneId(e.target.value)}
            />
          </div>
        </div>
      </div>

      <div style={styles.submitButton}>
        <button onClick={handleClick} className="btn d-flex justify-content-center align-items-center me-2" style={styles.submitBtn}>
          <p className="text-white mb-0">Make OTP Demo</p>
        </button>
      </div>
    </div>
  );
};

export default Otp;

