import React, { useEffect, useState } from 'react';
import { Link, Routes, Route, useNavigate } 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 [isMobile, setIsMobile] = useState(false);  
  const [nik, setNik] = useState('');
  const [nikError, setNikError] = useState('');
  const [date, setDate] = useState('');
  const [dateError, setDateError] = useState('');
  const [name, setName] = useState('');
  const [nameError, setNameError] = useState('');
  const [phoneId, setPhoneId] = useState('');
  const [phoneError, setPhoneError] = useState('');
  const [email, setEmail] = useState('');
  const [gender, setGender] = useState('');
  const [incomeRange, setIncomeRange] = useState('');
  const [companyName, setCompanyName] = useState('');
  const [emailError, setEmailError] = useState('');
  const [genderError, setGenderError] = useState('');
  const [incomeRangeError, setIncomeRangeError] = useState('');
  const [companyNameError, setCompanyNameError] = useState('');

  // Fungsi untuk menangani perubahan pada NPWP
  const handleNikChange = (e) => {
    setNik(e.target.value);
  };
  const handleDateChange = (e) => {
    setDate(e.target.value);
  };
  const handleNameChange = (e) => {
    setName(e.target.value);
  };
  const handleEmailChange = (e) => {
    setEmail(e.target.value);
  };
  // Fungsi untuk menangani perubahan gender
  const handleGenderChange = (e) => {
    setGender(e.target.value);
  };
  // Fungsi untuk menangani perubahan income range
  const handleIncomeRangeChange = (e) => {
    setIncomeRange(e.target.value);
  };

  // Fungsi untuk menangani perubahan company name
  const handleCompanyNameChange = (e) => {
    setCompanyName(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: {
      marginTop: '3%',
      padding: '0 15px',
    },
    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 (
    <div className="container" style={styles.container}>
      <style>
        {`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        `}
      </style>

      {isLoading && (
        <div style={styles.loadingOverlay}>
          <div style={styles.spinner}></div>
        </div>
      )}
      {/* 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>

      {/* Tab Navigation */}
      <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">
            <div className="input-wrapper">
              <input
                type="nik"
                id="nik"
                className="form-control"
                value={nik}
                onChange={handleNikChange}
                placeholder="NIK"
              />
            </div>
            {/* Menampilkan error jika ada */}
            {nikError && <small style={styles.SelfieImageError}>{nikError}</small>}
          </div>

          {/* Kolom untuk input tanggal */}
          <div className="col-md-6">
            <div className="input-wrapper">
              <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">
          {/* Kolom untuk input name */}
          <div className="col-md-6">
            <div className="input-wrapper">
              <input
                type="name"
                id="name"
                className="form-control"
                value={name}
                onChange={handleNameChange}
                placeholder="Name"
              />
            </div>
            {/* Menampilkan error jika ada */}
            {nameError && <small style={styles.SelfieImageError}>{nameError}</small>}
          </div>

          <div className="col-md-6">
            <div className="input-group">
              <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>
            {/* Menampilkan error jika ada */}
            {phoneError && <small style={styles.SelfieImageError}>{phoneError}</small>}
          </div>
        </div>

        {/* Email and Gender */}
        <div className="form-group row align-items-center my-4">
          {/* Kolom untuk input email */}
          <div className="col-md-6">
            <div className="input-wrapper">
              <input
                type="email"  // Mengubah tipe input menjadi email
                id="email"
                className="form-control"
                value={email}
                onChange={handleEmailChange}  // Fungsi untuk menangani perubahan input email
                placeholder="Email"
              />
            </div>
            {/* Menampilkan error jika ada */}
            {emailError && <small style={styles.SelfieImageError}>{emailError}</small>}
          </div>

          {/* Kolom untuk Select Gender */}
          <div className="col-md-6">
            <div className="input-wrapper">
              <select
                id="gender"
                className="form-control"
                value={gender}  // State untuk gender
                onChange={handleGenderChange}  // Fungsi untuk menangani perubahan pilihan gender
              >
                <option value="">Select Gender</option>  {/* Placeholder option */}
                <option value="Male">Male</option>      {/* Pilihan Male */}
                <option value="Female">Female</option>  {/* Pilihan Female */}
                <option value="Other">Other</option>    {/* Pilihan Other */}
              </select>
            </div>
            {/* Menampilkan error jika ada */}
            {genderError && <small style={styles.SelfieImageError}>{genderError}</small>}
          </div>
        </div>

        <div className="form-group row align-items-center my-4">
          {/* Kolom untuk Select Income Range */}
          <div className="col-md-6">
            <div className="input-wrapper">
              <select
                id="incomeRange"
                className="form-control"
                value={incomeRange}  // State untuk income range
                onChange={handleIncomeRangeChange}  // Fungsi untuk menangani perubahan income range
              >
                <option value="">Select Income Range</option>
                <option value="0-50k">0 - 50k</option>
                <option value="51k-100k">51k - 100k</option>
                <option value="101k-200k">101k - 200k</option>
                <option value="201k+">201k+</option>
              </select>
            </div>
            {incomeRangeError && <small style={styles.SelfieImageError}>{incomeRangeError}</small>}
          </div>

          {/* Kolom untuk input Company Name */}
          <div className="col-md-6">
            <div className="input-wrapper">
              <input
                type="text"
                id="companyName"
                className="form-control"
                value={companyName}
                onChange={handleCompanyNameChange}  // Fungsi untuk menangani perubahan input company name
                placeholder="Company Name"
              />
            </div>
            {companyNameError && <small style={styles.SelfieImageError}>{companyNameError}</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">Check Now</p>
          </button>
        </div>
      </div>
    </div>
  );
};

export default Verify;
