import React, { useState, useEffect } from 'react';
import { useNavigate } from "react-router-dom";
import styles from './LinktreePage.module.css';
import { loginUser, getAllCafeOwner, createCafeOwner } from "../helpers/userHelpers";
import { getOwnedCafes, createCafe, updateCafe } from "../helpers/cafeHelpers";
import { getMyTransactions } from "../helpers/transactionHelpers";
import { unsubscribeUser } from "../helpers/subscribeHelpers.js";
import { getLocalStorage, removeLocalStorage } from "../helpers/localStorageHelpers";
import { ThreeDots } from "react-loader-spinner";
import Header from '../components/Header';
import CircularDiagram from "./CircularDiagram";

const LinktreePage = ({ user, setModal }) => {
  const navigate = useNavigate();
  const [inputtingPassword, setInputtingPassword] = useState(false);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const [items, setItems] = useState([]);
  const [isCreating, setIsCreating] = useState(false);
  const [newItem, setNewItem] = useState({ name: "", type: "" });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [expanded, setIsExpand] = useState(false);
  const [expandedCafeId, setExpandedCafeId] = useState(null);
  const [selectedItemId, setSelectedItemId] = useState(0);

  // Handle expand/collapse of cafe details
  const handleToggleExpand = (cafeId) => {
    setExpandedCafeId(expandedCafeId === cafeId ? null : cafeId);
  };

  // Handle user transactions
  const handleMyTransactions = async () => {
    try {
      setError(false);
      setLoading(true);
      const response = await getMyTransactions();
      if (response) {
        setItems(response);
      } else {
        setError(true);
      }
    } catch (error) {
      setError(true);
    } finally {
      setLoading(false);
      console.log(items);
    }
  };

  // Handle login
  const handleLogin = async () => {
    try {
      setError(false);
      setLoading(true);
      const response = await loginUser(username, password);
      if (response.success) {
        localStorage.setItem('auth', response.token);
        window.location.href = response.cafeId ? `/${response.cafeId}` : '/';
      } else {
        setError(true);
      }
    } catch (error) {
      setError(true);
    } finally {
      setLoading(false);
    }
  };

  // Handle logout
  const handleLogout = () => {
    removeLocalStorage("auth");
    unsubscribeUser();
    navigate(0);
  };

  // Fetch data when the user changes
  useEffect(() => {
    if (user) {
      setLoading(true);
      switch (user.roleId) {
        case 0:
          getAllCafeOwner().then(setItems).catch(console.error).finally(() => setLoading(false));
          break;
        case 1:
          getOwnedCafes(user.userId).then(setItems).catch(console.error).finally(() => setLoading(false));
          break;
        case 3:
          handleMyTransactions();
          break;
        default:
          setLoading(false);
          break;
      }
    }

    console.log(items);
  }, [user]);

  // Handle create item (admin or cafe owner)
  const handleCreateItem = async () => {
    try {
      if (user.roleId < 1) {
        const newOwner = await createCafeOwner(newItem.email, newItem.username, newItem.password);
        setItems([...items, { userId: newOwner.userId, name: newOwner.username }]);
      } else {
        const newCafe = await createCafe(newItem.name);
        setItems([...items, { cafeId: newCafe.cafeId, name: newCafe.name }]);
      }
      setIsCreating(false);
      setNewItem({ name: "", type: "" });
    } catch (error) {
      console.error("Error creating item:", error);
    }
  };

  const formatIncome = (amount) => {
    if (amount >= 1_000_000_000) {
      // Format for billions
      const billions = amount / 1_000_000_000;
      return billions.toFixed(0) + "b"; // No decimal places for billions
    } else if (amount >= 1_000_000) {
      // Format for millions
      const millions = amount / 1_000_000;
      return millions.toFixed(2).replace(/\.00$/, "") + "m"; // Two decimal places, remove trailing '.00'
    } else if (amount >= 1_000) {
      // Format for thousands
      const thousands = amount / 1_000;
      return thousands.toFixed(1).replace(/\.0$/, "") + "k"; // One decimal place, remove trailing '.0'
    } else {
      // Less than a thousand
      if (amount != null) return amount.toString();
    }
  };
  return (
    <>
      {user && user.roleId < 2 ? (
        <div className={styles.nonCenteredLinktreePage}>

          <div className={styles.dashboard}>
            <div className={styles.header}>

              <Header
                HeaderText={"selamat siang " + user.username}
                isEdit={() => setIsModalOpen(true)}
                isLogout={handleLogout}
                user={user}
                showProfile={true}
                setModal={setModal}
                HeaderMargin='0px'
              />
            </div>
            <div className={styles.headerCardWrapper}>
              <div className={styles.headerCard}>
                <h1>Total pemasukan</h1>
              </div>
            </div>

          </div>

          <div style={{ flex: 1 }}>
            <CircularDiagram segments={[]} />
          </div>

          <div style={{ flex: 1 }}>
            <CircularDiagram segments={[]} />
          </div>
          <div className={styles.cafeListWrapper}>
            <div className={styles.cafeListHeader}>
              Semua {user.roleId < 1 ? 'penyewa' : 'kedai yang dikau miliki'}
            </div>
            <div className={styles.cafeList}>
            </div>

            {user.roleId < 1 &&
              <div className={styles.rectangle}
                style={{ backgroundColor: selectedItemId == -1 ? 'rgb(69, 69, 69)' : 'rgb(114, 114, 114)' }}
                onClick={() => setSelectedItemId(selectedItemId == 0 ? -1 : 0)}
              >
                Tambah penyewa
              </div>
            }
            {
              items && Array.isArray(items.tenants) && items.tenants.length > 0 ? (
                items.tenants.map((tenant, tenantIndex) => (
                  <>
                  <div key={tenant.userId} onClick={() => setSelectedItemId(selectedItemId == tenant.userId ? 0 : tenant.userId)} style={{ backgroundColor: selectedItemId == tenant.userId ? 'rgb(69, 69, 69)' : 'rgb(114, 114, 114)' }} className={styles.rectangle}>
                    <h3>{tenant.username}</h3>
                    <div>
                      Total Pendapatan: {formatIncome(tenant.totalIncome)} {/* Total Income for the tenant */}
                    </div>

                  </div>
                  
                  {selectedItemId == tenant.userId && tenant.cafes && tenant.cafes.length > 0 && tenant.cafes.map((cafe, cafeIndex) => (
                      <div>
                        <h5 >↳</h5>
                      <div key={cafe.cafeId} className={styles.subRectangle}
                        onClick={() => setSelectedItemId(selectedItemId === cafe.cafeId ? -1 : cafe.cafeId)}
                        style={{
                          backgroundColor: selectedItemId === cafe.cafeId ? 'rgb(69, 69, 69)' : 'rgb(114, 114, 114)'
                        }}
                      >
                        {cafe.name}
                        &nbsp;pendapatan {formatIncome(cafe.report?.totalIncome || 0)}
                      </div>
                      </div>
                    ))}
                  </>
                ))
              ) : (
                <div>No tenants available</div>
              )
            }

            {user.roleId > 0 &&
              <div className={styles.rectangle}

                style={{ backgroundColor: selectedItemId == 0 ? 'rgb(69, 69, 69)' : 'rgb(114, 114, 114)' }}
                onClick={() => { setSelectedItemId(selectedItemId == 0 ? -1 : 0); setModal('create-cafe'); }}
              >
                Tambah kedai
              </div>
            }
          </div>
        </div>
      ) : (
        <div className={styles.centeredLinktreePage}>
          <div className={styles.dashboardLine}></div>
          <div className={styles.dashboardContainer}>
            <div className={styles.mainHeading}>
              COBA KEDAIMASTER
              <div className={styles.swipeContainer}>
                <div className={styles.swipeContent}>
                  {['pemesanan langsung dari meja', 'pengelolaan pesanan dan keuangan', 'tentukan suasana musik', 'pengelolaan stok dan manajemen', 'jangan pernah ragukan pelanggan'].map((item, index) => (
                    <div key={index} className={styles.swipeItem}>{item}</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>

            {getLocalStorage('auth') == null && (
              <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 })} 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>
                <a
                  target="_blank"
                  rel="noreferrer"
                  className={styles.signupButton}
                  onClick={() => setModal('join')}
                >
                  Daftarkan kedaimu
                </a>
              </div>
              <div className={styles.footerImage}>
                <img
                  style={{ height: '226px', width: '150px', objectFit: 'cover' }}
                  src="/kedai.png"
                  alt="Linktree visual"
                  onError={(e) => e.target.src = '/fallback-image.png'}
                />
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default LinktreePage;
