import React, { useState, useEffect } from 'react';
import styles from './Login.module.css'; // Import the module.css file
import { loginUser } from "../helpers/userHelpers";
import { ThreeDots } from "react-loader-spinner";
import { useNavigate } from "react-router-dom";

const LinktreePage = ({ user, setModal }) => {
  const [inputtingPassword, setInputtingPassword] = useState(false);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleLogin = async () => {
    try {
      setError(false);
      setLoading(true);
      const response = await loginUser(username, password);

      if (response.success) {
        localStorage.setItem('auth', response.token);

        if (response.cafeId !== null) {
          window.location.href = response.cafeId;
        } else {
          let destination = '/';
          window.location.href = destination;
        }
      } else {
        setError(true); // Trigger error state in the button
        console.error('Login failed');
      }
    } catch (error) {
      setError(true);
      console.error('Error occurred while logging in:', error.message);
    } finally {
      setLoading(false); // Ensure loading state is cleared
    }
  };

  const handleModalClose = () => {
    setIsModalOpen(false);
  };

  return (
    <div className={styles.linktreePage}>

          <div className={styles.dashboardContainer}>
            <div className={styles.mainHeading}>
              COBA KEDAIMASTER
              <div className={styles.swipeContainer}>
                <div className={styles.swipeContent}>
                  <div className={styles.swipeItem}>pemesanan langsung dari meja</div>
                  <div className={styles.swipeItem}>pengelolaan pesanan dan keuangan</div>
                  <div className={styles.swipeItem}>tentukan suasana musik</div>
                  <div className={styles.swipeItem}>pengelolaan stok dan manajemen</div>
                  <div className={styles.swipeItem}>jangan pernah ragukan pelanggan</div>
                </div>
              </div>
              diskon 0%
            </div>

            <div className={styles.subHeading}>
              Solusi berbasis web untuk memudahkan pengelolaan kedai, dengan fitur yang mempermudah pemilik, kasir, dan tamu berinteraksi.
            </div>
              <div className={styles.LoginForm}>
                <div className={`${styles.FormUsername} ${inputtingPassword ? styles.animateForm : styles.reverseForm}`}>
                  <label htmlFor="username" className={styles.usernameLabel}>
                    ---- masuk -------------------------------
                  </label>
                  <input
                    id="username"
                    placeholder="username"
                    maxLength="30"
                    className={!error ? styles.usernameInput : styles.usernameInputError}
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                  />
                  <button onClick={() => setInputtingPassword(true)} className={styles.claimButton}>
                    <span>➜</span>
                  </button>
                </div>

                <div className={`${styles.FormPassword} ${inputtingPassword ? styles.animateForm : styles.reverseForm}`}>
                  <span>
                    <label onClick={() => setInputtingPassword(false)} htmlFor="password" className={styles.usernameLabel}>
                      &lt;--- &lt;-- kembali
                    </label><label htmlFor="password" className={styles.usernameLabel}>
                      &nbsp; ------ &nbsp;
                    </label><label onClick={() => setModal('reset-password', { username: username })} htmlFor="password" className={styles.usernameLabel}>
                      lupa password? -
                    </label></span>
                  <input
                    id="password"
                    placeholder="password"
                    type="password"
                    maxLength="30"
                    className={!error ? styles.usernameInput : styles.usernameInputError}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                  <button
                    onClick={handleLogin}
                    className={`${styles.claimButton} ${loading ? styles.loading : ''}`}
                    disabled={loading}
                  >
                    <span>{loading ? 'Loading...' : 'Masuk'}</span>
                  </button>
                </div>
              </div>
            <div className={styles.footer}>
              <div className={styles.footerLinks}>
                <a
                  href="https://linktr.ee/discover/trending"
                  target="_blank"
                  rel="noreferrer"
                  className={styles.footerLink}
                >
                  Pelajari lebih lanjut
                </a>
                <a
                  href="https://linktr.ee"
                  target="_blank"
                  rel="noreferrer"
                  className={styles.footerLink}
                >
                  Tentang kedaimaster.com
                </a>
              </div>
            </div>
          </div>
          </div>
  );
};

export default LinktreePage;
