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

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


const Verify = () => {

  const [isLoading, setIsLoading] = useState(false);
  const [applicationId, setApplicationId] = useState('');
  const [inputValueApplication, setInputValueApplication] = useState('');
  const [applicationIds, setApplicationIds] = useState([]);
  const [selectedQuota, setSelectedQuota] = useState(0);
  const [fullName, setFullName] = useState('');
  const [fullNameError, setFullNameError] = useState('');
  const [date, setDate] = useState('');
  const [dateError, setDateError] = useState('');
  const [place, setPlace] = useState('');
  const [placeError, setPlaceError] = useState('');
  const [country, setCountry] = useState('');
  const [countryError, setCountryError] = useState('');
  const [isMobile, setIsMobile] = useState(false);

  // Fungsi untuk menangani perubahan pada NPWP
  const handleFullNameChange = (e) => {
    setFullName(e.target.value);
  };
  const handleDateChange = (e) => {
    setDate(e.target.value);
  };
  const handlePlaceChange = (e) => {
    setPlace(e.target.value);
  };
  const handleCountryChange = (e) => {
    setCountry(e.target.value);
  };

  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);
        setSelectedQuota(selectedApp.quota); // Set the selected quota
      }
    }
  };

  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 handleClick = () => {
    setSelectedQuota(prevQuota => prevQuota - 1); // Mengurangi nilai selectedQuota
    console.log('Click Check Now!');  // Tampilkan log pada klik
  };  

  
  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',      
    },
    breadcrumb: {
      marginBottom: '1rem',
      fontSize: '0.9rem',
    },
    breadcrumbLink: {
      textDecoration: 'none',
      color: '#0542cc',
    },
    tabLink: {
      padding: '10px 20px',
    },
    welcomeCard: {
      backgroundColor: '#E2FBEA',
      borderLeft: '4px solid #0542CC',
      borderRadius: '5px',
      marginBottom: '20px',
    },
    createButton: {
      backgroundColor: '#0542CC',
    },
    section: {
      padding: '20px',
      border: '0.1px solid rgba(0, 0, 0, 0.2)',
      borderLeft: '4px solid #0542CC',
      borderRadius: '10px',
      width: '100%',
    },
    tabLink: {
      padding: '10px 20px',
    },
    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 (
    <>
      <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">
              <i className="fas fa-warning fa-bold me-3"></i>Alert
            </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 className="d-flex flex-row mt-3">
              <Link to="/createApps" style={{ textDecoration: 'none' }}>
                <button className="btn d-flex justify-content-center align-items-center me-2" style={styles.createButton}>
                  <i className="fas fa-plus text-white me-2"></i>
                  <p className="text-white mb-0">Create New App ID</p>
                </button>
              </Link>
            </div>
          </div>
        </div>
        
        <div style={styles.section}>
          <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}>{selectedQuota}</span>
                <span style={styles.timesText}>(times)</span>
              </div>
            </div>
          </div>

          {/* Nik and Date Row */}
          <div className="form-group row align-items-center">
            {/* Kolom untuk input email */}
            <div className="col-md-6 mt-4">
              <div className="input-wrapper">
                <input
                  type="fullName"
                  id="fullName"
                  className="form-control"
                  value={fullName}
                  onChange={handleFullNameChange}
                  placeholder="Full Name"
                />
              </div>
              {/* Menampilkan error jika ada */}
              {fullNameError && <small style={styles.SelfieImageError}>{fullNameError}</small>}
            </div>

            {/* Kolom untuk input tanggal */}
            <div className="col-md-6">
              <div className="input-wrapper">
                <label htmlFor="date" style={{ display: 'block', marginBottom: '5px' }}>
                  Date of Birth
                </label>
                <input
                  type="date"
                  id="date"
                  className="form-control"
                  value={date}
                  onChange={handleDateChange}
                />
              </div>
              {/* Menampilkan error jika ada */}
              {dateError && <small style={styles.SelfieImageError}>{dateError}</small>}
            </div>
          </div>

          {/* Name and Phone */}
          <div className="form-group row align-items-center my-4">
            <div className="col-md-6">
              <div className="input-wrapper">
                <input
                  type="place"
                  id="place"
                  className="form-control"
                  value={place}
                  onChange={handlePlaceChange}
                  placeholder="Place of Birth"
                />
              </div>
              {/* Menampilkan error jika ada */}
              {placeError && <small style={styles.SelfieImageError}>{placeError}</small>}
            </div>

            <div className="col-md-6">
              <div className="input-wrapper">
                <input
                  type="country"
                  id="country"
                  className="form-control"
                  value={country}
                  onChange={handleCountryChange}
                  placeholder="Country"
                />
              </div>
              {/* Menampilkan error jika ada */}
              {countryError && <small style={styles.SelfieImageError}>{countryError}</small>}
            </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 a Demo</p>
            </button>
          </div>
        </div>      
      </div>
    </div>
    </>
  );
};

export default Verify;

