import React, { useState, useEffect } from "react";
import styles from "./Dashboard.module.css"; // Import module CSS for styling
import Header from "../components/Header";
import { useNavigate } from "react-router-dom";
import AccountUpdateModal from "../components/AccountUpdateModal";
import { removeLocalStorage } from "../helpers/localStorageHelpers";
import { getAnalytics, createCafeOwner } from "../helpers/userHelpers";
import { getOwnedCafes, createCafe, updateCafe } from "../helpers/cafeHelpers";

import { ThreeDots } from "react-loader-spinner";
import { unsubscribeUser } from "../helpers/subscribeHelpers.js";

const Dashboard = ({ user, setModal }) => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [items, setItems] = useState([]);
  const [isCreating, setIsCreating] = useState(false);
  const [newItem, setNewItem] = useState({ name: "", type: "" });

  useEffect(() => {
    if (user && user.roleId < 2) {
      setLoading(true);
      getAnalytics()
        .then((data) => {
          setItems(data);
          console.log(data)
          setLoading(false);
        })
        .catch((error) => {
          console.error("Error fetching cafe owners:", error);
          setLoading(false);
        });
    }
  }, [user]);

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

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

  const handleCreateItem = () => {
    if (user.roleId < 1) {
      // Create admin functionality
      createCafeOwner(newItem.email, newItem.username, newItem.password)
        .then((newitem) => {
          setItems([...items, { userId: newitem.userId, name: newitem.username }]);
          setIsCreating(false);
          setNewItem({ name: "", type: "" });
        })
        .catch((error) => {
          console.error("Error creating admin:", error);
        });
    } else {
      // Create cafe functionality
      createCafe(newItem.name)
        .then((newitem) => {
          setItems([...items, { cafeId: newitem.cafeId, name: newitem.name }]);
          setIsCreating(false);
          setNewItem({ name: "", type: "" });
        })
        .catch((error) => {
          console.error("Error creating cafe:", error);
        });
    }
  };
//   function calculateCafeMetrics(cafes) {
//     let totalIncomeThisMonth = 0;
//     let totalIncomeLastMonth = 0;

//     cafes.forEach(cafe => {
//         const currentIncome = cafe.totalIncome;
//         const growth = cafe.growthIncome / 100;

//         // Hitung keuntungan bulan lalu
//         const lastMonthIncome = currentIncome / (1 + growth);
        
//         // Tambahkan ke total
//         totalIncomeThisMonth += currentIncome;
//         totalIncomeLastMonth += lastMonthIncome;
//     });

//     // Hitung growth total
//     const totalGrowth = ((totalIncomeThisMonth - totalIncomeLastMonth) / totalIncomeLastMonth) * 100;

//     return {
//         totalIncomeThisMonth,
//         totalIncomeLastMonth: totalIncomeLastMonth.toFixed(2),
//         totalGrowth: totalGrowth.toFixed(2)
//     };
// }

  return (
    <>
      <Header
        HeaderText={"kedaimaster"}
        isEdit={() => setIsModalOpen(true)}
        isLogout={handleLogout}
        user={user}
        showProfile={true}
        setModal={setModal}
      />
      {user && user.roleId < 2 && (
        <div className={styles.dashboard}>
          {loading && <ThreeDots />}
          {items.map((item, index) => (
            <div
              key={index}
              onClick={() => navigate("/" + item.cafeId)}
              className={styles.rectangle}
            >
              <h1>{item.name || item.username}</h1>
              <div><h1>{item.report?.totalIncome}</h1></div>
            </div>
          ))}
          {user && user.roleId < 1 ? (
            <div
              className={styles.rectangle}
              onClick={() => setIsCreating(true)}
            >
              Create Client
            </div>
          ) : (
            <div
              className={styles.rectangle}
              onClick={() => setIsCreating(true)}
            >
              +
            </div>
          )}
        </div>
      )}

      {user.username && (
        <AccountUpdateModal
          user={user}
          isOpen={isModalOpen}
          onClose={handleModalClose}
        />
      )}

      {isCreating && (
        <div className={styles.createModal}>
          <h2>Create New {user.roleId < 1 ? "Admin" : "Cafe"}</h2>
          {user.roleId < 1 ?<>
          <input
            type="email"
            value={newItem.email}
            onChange={(e) => setNewItem({ ...newItem, email: e.target.value })}
            placeholder="email"
          />
          <input
            type="text"
            value={newItem.username}
            onChange={(e) => setNewItem({ ...newItem, username: e.target.value })}
            placeholder="username"
          />
          <input
            type="password"
            value={newItem.password}
            onChange={(e) => setNewItem({ ...newItem, password: e.target.value })}
            placeholder="Password"
          /></> : 
          <input
            type="text"
            value={newItem.name}
            onChange={(e) => setNewItem({ ...newItem, name: e.target.value })}
            placeholder="Name"
          />}
          <button onClick={handleCreateItem}>Create</button>
          <button onClick={() => setIsCreating(false)}>Cancel</button>
        </div>
      )}
    </>
  );
};

export default Dashboard;
