import React, { useState, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { FaChevronLeft, FaChevronRight, FaFastBackward, FaFastForward, FaSort, FaSortUp, FaSortDown, FaTrash, FaEdit } from 'react-icons/fa'; // Icons for sorting
import { NoAvailable } from '../../assets/icon';
import { useLocation, useNavigate } from 'react-router-dom';
import dataMenu from '../../components/Sidebar/dataMenu';

const AddUser = () => {
  
  const location = useLocation();
  const navigate = useNavigate();
  const [buttonState, setButtonState] = useState({
    isHovered: false,
    isActive: false,
  });
  const [inputValue, setInputValue] = useState('');
  const [error, setError] = useState('');


  const Breadcrumb = ({ path }) => {
    return (
      <nav style={styles.breadcrumb}>
        {path.map((item, index) => (
          <span key={index}>
            {index > 0 && <span style={{ color: '#808080' }}>{' > '}</span>}
            <a
              href={item.link}
              style={{
                ...styles.breadcrumbLink,
                fontWeight: location.pathname === item.link ? 'bold' : 'normal',
                color: index === 0 ? '#808080' : '#0542cc',
                textDecoration: 'none'
              }}
            >
              {item.name}
            </a>
          </span>
        ))}
      </nav>
    );
  };
  
  
  const breadcrumbPath = [
    { name: 'User', link: '/company-access' },
    { name: 'Add New User' },
  ];
   

  const handleMouseEnter = () => setButtonState({ ...buttonState, isHovered: true });
  const handleMouseLeave = () => setButtonState({ ...buttonState, isHovered: false, isActive: false });
  const handleMouseDown = () => setButtonState({ ...buttonState, isActive: true });
  const handleMouseUp = () => setButtonState({ ...buttonState, isActive: false });

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
    if (error) setError(''); // Clear error when user starts typing
  };

  const handleSubmit = (e) => {
    e.preventDefault();
  
    // Basic empty check
    if (!inputValue.trim()) {
      setError('Email is required.');
      return;
    }
  
    // Comprehensive email validation regex
    const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    
    if (!emailRegex.test(inputValue)) {
      setError('Please enter a valid email address.');
      return;
    }
  
    // Common email domain validation
    const domain = inputValue.split('@')[1];
    const commonDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com'];
    
    if (!commonDomains.includes(domain)) {
      setError('Please use a common email domain.');
      return;
    }
  
    // Success case
    console.log('Email validation passed:', inputValue);
    alert('Email validation successful!');
    navigate(-1);
  };
  

  const styles = {
    container: {
        marginTop: '0.5rem',
        width: '100%',
        margin: '0',
        boxSizing: 'border-box',
    },
    wrapper: {
        display: 'flex',
        flexDirection: 'column',
        border: '1px solid #ddd',
        borderRadius: '8px',
        padding: '1.5rem',
        boxShadow: '0 2px 5px rgba(0, 0, 0, 0.1)',
        borderLeft: '5px solid #0542cc',
        backgroundColor: '#fff',
    },
    form: {
        display: 'flex',
        flexDirection: 'column',
    },
    header: {
        marginBottom: '1rem',
        fontSize: '1.5rem',
        textAlign: 'flex-start',
    },
    input: {
        width: '100%',
        padding: '0.75rem',
        marginBottom: '1rem',
        borderRadius: '6px',
        border: '1px solid #ccc',
        boxSizing: 'border-box',
        fontStyle: 'italic',
    },
    button: {
        padding: '0.5rem 1rem', // Ubah ukuran padding tombol untuk resize
        alignSelf: 'flex-start', // Menempatkan tombol di flex-start
        color: '#fff',
        border: 'none',
        borderRadius: '6px',
        cursor: 'pointer',
        transition: 'background-color 0.3s ease',
    },
    buttonText: {
        color: '#fff',
        fontWeight: '500',
    },
    breadcrumb: {
        marginBottom: '1rem',
        fontSize: '14px',
        display: 'flex',
        justifyContent: 'flex-start',
    },
    breadcrumbLink: {
        color: '#000',
        textDecoration: 'none',
    },
    error: {
        color: 'red',
        fontSize: '12px',
        marginTop: '-8px',
        marginBottom: '10px',
    },
  };

  return (
    <>
      <div style={styles.container}>        
        <Breadcrumb path={breadcrumbPath} />
        <h2 style={styles.header}>Invite New User</h2>
        <form onSubmit={handleSubmit} style={styles.form}>
          <div className='col mb-3'>
            <input
              type="email"
              value={inputValue}
              onChange={handleInputChange}
              placeholder="Enter your email address"
              style={styles.input}
              className="italic-placeholder"
            />
            {error && <span style={styles.error}>{error}</span>}
          </div>
          <button
            type="submit"
            style={{
              ...styles.button,
              backgroundColor: buttonState.isActive
                ? '#4BA5E7'
                : buttonState.isHovered
                ? '#1A6FD9'
                : '#0542cc',
            }}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
            onMouseDown={handleMouseDown}
            onMouseUp={handleMouseUp}
          >
            <span style={styles.buttonText}>Add New User</span>
          </button>
        </form>
        <style>
          {`
            input::placeholder {
              font-style: italic;
            }

            @media (max-width: 600px) {
              .col {
                padding: 0;
              }
            }
          `}
        </style>
      </div>
    </>
  )
}

const AddRoles = () => {
  
  const location = useLocation();
  const navigate = useNavigate();
  const [buttonState, setButtonState] = useState({
    isHovered: false,
    isActive: false,
  });
  const [inputValue, setInputValue] = useState('');
  const [error, setError] = useState('');


  const Breadcrumb = ({ path }) => {
    return (
      <nav style={styles.breadcrumb}>
        {path.map((item, index) => (
          <span key={index}>
            {index > 0 && <span style={{ color: '#808080' }}>{' > '}</span>}
            <a
              href={item.link}
              style={{
                ...styles.breadcrumbLink,
                fontWeight: location.pathname === item.link ? 'bold' : 'normal',
                color: index === 0 ? '#808080' : '#0542cc',
                textDecoration: 'none'
              }}
            >
              {item.name}
            </a>
          </span>
        ))}
      </nav>
    );
  };
  
  
  const breadcrumbPath = [
    { name: 'Add Role', link: '/company-access' },
    { name: 'Add New Role' },
  ];
   

  const handleMouseEnter = () => setButtonState({ ...buttonState, isHovered: true });
  const handleMouseLeave = () => setButtonState({ ...buttonState, isHovered: false, isActive: false });
  const handleMouseDown = () => setButtonState({ ...buttonState, isActive: true });
  const handleMouseUp = () => setButtonState({ ...buttonState, isActive: false });

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
    if (error) setError(''); // Clear error when user starts typing
  };

  const handleSubmit = (e) => {
    e.preventDefault();
  
    // Basic empty check
    if (!inputValue.trim()) {
      setError('Role is required.');
      return;
    }
    alert('Role validation successful!');
    navigate(-1);
  };
  

  const styles = {
    container: {
        marginTop: '0.5rem',
        width: '100%',
        margin: '0',
        boxSizing: 'border-box',
    },
    wrapper: {
        display: 'flex',
        flexDirection: 'column',
        border: '1px solid #ddd',
        borderRadius: '8px',
        padding: '1.5rem',
        boxShadow: '0 2px 5px rgba(0, 0, 0, 0.1)',
        borderLeft: '5px solid #0542cc',
        backgroundColor: '#fff',
    },
    form: {
        display: 'flex',
        flexDirection: 'column',
    },
    header: {
        marginBottom: '1rem',
        fontSize: '1.5rem',
        textAlign: 'flex-start',
    },
    input: {
        width: '100%',
        padding: '0.75rem',
        marginBottom: '1rem',
        borderRadius: '6px',
        border: '1px solid #ccc',
        boxSizing: 'border-box',
        fontStyle: 'italic',
    },
    button: {
        padding: '0.5rem 1rem', // Ubah ukuran padding tombol untuk resize
        alignSelf: 'flex-start', // Menempatkan tombol di flex-start
        color: '#fff',
        border: 'none',
        borderRadius: '6px',
        cursor: 'pointer',
        transition: 'background-color 0.3s ease',
    },
    buttonText: {
        color: '#fff',
        fontWeight: '500',
    },
    breadcrumb: {
        marginBottom: '1rem',
        fontSize: '14px',
        display: 'flex',
        justifyContent: 'flex-start',
    },
    breadcrumbLink: {
        color: '#000',
        textDecoration: 'none',
    },
    error: {
        color: 'red',
        fontSize: '12px',
        marginTop: '-8px',
        marginBottom: '10px',
    },
  };

  return (
    <>
      <div style={styles.container}>        
        <Breadcrumb path={breadcrumbPath} />
        <h2 style={styles.header}>Create New Role</h2>
        <form onSubmit={handleSubmit} style={styles.form}>
          <div className='col mb-3'>
            <input
              type="email"
              value={inputValue}
              onChange={handleInputChange}
              placeholder="Input role name"
              style={styles.input}
              className="italic-placeholder"
            />
            {error && <span style={styles.error}>{error}</span>}
          </div>
          <button
            type="submit"
            style={{
              ...styles.button,
              backgroundColor: buttonState.isActive
                ? '#4BA5E7'
                : buttonState.isHovered
                ? '#1A6FD9'
                : '#0542cc',
            }}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
            onMouseDown={handleMouseDown}
            onMouseUp={handleMouseUp}
          >
            <span style={styles.buttonText}>Add New Role</span>
          </button>
        </form>
        <style>
          {`
            input::placeholder {
              font-style: italic;
            }

            @media (max-width: 600px) {
              .col {
                padding: 0;
              }
            }
          `}
        </style>
      </div>
    </>
  )
}

const AccessMenu = () => {
  const headerData = [
    "Accessibility",
    "Search",
    "Details",
    "Edit",
    "Action/Add Button",
    "Export Data",
    "Delete",
  ];

  // Fungsi untuk merender baris tabel
  const renderTableRows = (menuItems, isSubMenu = false) => {
    if (!Array.isArray(menuItems)) return null;

    return menuItems.map((menu, index) => (
      <React.Fragment key={index}>
        <tr
          style={{
            backgroundColor: isSubMenu ? "#f9f9f9" : "#ffffff", // Beri warna latar berbeda
            fontStyle: isSubMenu ? "italic" : "normal", // Submenu ditandai dengan gaya miring
          }}
        >
          <td style={{ border: "1px solid #ddd", padding: "8px" }}>
            {isSubMenu ? `↳ ${menu.name}` : menu.name} {/* Tambahkan tanda panah untuk submenu */}
          </td>
          {headerData.map((header, funcIndex) => (
            <td key={funcIndex} style={{ border: "1px solid #ddd", padding: "8px" }}>
              <input type="checkbox" />
            </td>
          ))}
        </tr>
        {/* Render subMenus jika ada */}
        {menu.subMenus && renderTableRows(menu.subMenus, true)}
      </React.Fragment>
    ));
  };

  return (
    <div style={{ padding: "20px", fontFamily: "Arial, sans-serif" }}>
      <table
        style={{
          width: "100%",
          borderCollapse: "collapse",
          textAlign: "left",
          border: "1px solid #ddd",
        }}
      >
        {/* Header Table */}
        <thead>
          <tr>
            <th style={{ border: "1px solid #ddd", padding: "8px" }}>
              Access Name
            </th>
            {headerData.map((header, index) => (
              <th key={index} style={{ border: "1px solid #ddd", padding: "8px" }}>
                {header}
              </th>
            ))}
          </tr>
        </thead>
        {/* Body Table */}
        <tbody>
          {dataMenu.map((item, index) => (
            <React.Fragment key={index}>
              {item.items && renderTableRows(item.items)} {/* Validasi item.items */}
            </React.Fragment>
          ))}
        </tbody>
      </table>
    </div>
  );
};


const AccessUser = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [isMobile, setIsMobile] = useState(false); // State to detect mobile view
  const [transactionData, setTransactionData] = useState([]);
  const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' }); // Sorting state
  const dataPerPage = 5; // Data per page (10 data per page)
  const [showAddUser, setShowAddUser] = useState(false); // State to toggle between views
  const [newUser, setNewUser] = useState(""); // Initial state is an empty string

  // Generate 691 dummy transactions
  const generateDummyData = (numOfItems) => {
    const transactionData = [];
    
    for (let i = 1; i <= numOfItems; i++) {
      transactionData.push({
        fullName: `${['John', 'Jane', 'James', 'Maria', 'Sophia'][Math.floor(Math.random() * 5)]} ${['Doe', 'Smith', 'Johnson', 'Williams', 'Brown'][Math.floor(Math.random() * 5)]}`, // Full Name (First and Last Name)
        email: `${['john', 'jane', 'james', 'maria', 'sophia'][Math.floor(Math.random() * 5)]}${Math.floor(Math.random() * 1000)}@example.com`, // Random Email
      });    
    }
  
    
    return transactionData;
  };


  // Set the generated transaction data
  useEffect(() => {
      setTransactionData(generateDummyData(31)); // count data dummy transactions
  }, []);

  // Sorting function
  const sortData = (data, config) => {
    const { key, direction } = config;
    return [...data].sort((a, b) => {
        if (a[key] < b[key]) {
            return direction === 'asc' ? -1 : 1;
        }
        if (a[key] > b[key]) {
            return direction === 'asc' ? 1 : -1;
        }
        return 0;
    });
  };

  // Handle column header sort click
  const handleSort = (key) => {
      let direction = 'asc';
      if (sortConfig.key === key && sortConfig.direction === 'asc') {
          direction = 'desc'; // Toggle direction if the same column is clicked
      }
      setSortConfig({ key, direction });
  };

  // Get the paginated data
  const getPaginatedData = (data, page, perPage) => {
      const sortedData = sortData(data, sortConfig);
      const startIndex = (page - 1) * perPage;
      const endIndex = startIndex + perPage;
      return sortedData.slice(startIndex, endIndex);
  };

  // Handle page change
  const handlePageChange = (page) => {
      setCurrentPage(page);
  };

  // Calculate total pages based on the data and data per page
  const totalPages = Math.ceil(transactionData.length / dataPerPage);

  // Paginated data
  const paginatedData = getPaginatedData(transactionData, currentPage, dataPerPage);

  // Detect screen size and update isMobile state
  useEffect(() => {
      const handleResize = () => {
          setIsMobile(window.innerWidth <= 768); // Change 768 to your breakpoint
      };

      handleResize();
      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
  }, []);

  const handleDelete = (transactionId) => {
    console.log(`Delete transaction with ID:`);
    // Add your delete logic here
  };

  const handleAddUserClick = () => {
    setShowAddUser(true); // Switch to AddUser view when button is clicked
  };

  return (
    <div className="container">   
      {showAddUser ? (
          <AddUser/>
      ) : (
        <>
          {/* Filter Form */}
          <div className="row" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            {/* Select Dropdown for New User */}
            <div className="col-10 d-flex justify-content-start align-items-center">
              <select
                className='form-control'
                value={newUser}
                onChange={(e) => setNewUser(e.target.value)}
                style={{ marginRight: '0.6rem', padding: '0.5rem', borderRadius: '4px', border: '1px solid #ccc' }}
              >
                <option value="">New User</option>
                <option value="User1">User1</option>
                <option value="User2">User2</option>
                <option value="User3">User3</option>
              </select>
            </div>

            {/* Button for Add User */}
            <div className={`col-2 ${isMobile ? 'd-flex justify-content-end' : 'd-flex align-items-end'}`}>
              <button 
                className="btn text-white" 
                style={{ marginLeft: '0.6rem', backgroundColor: '#0542cc', width: '100%' }}
                onClick={handleAddUserClick}
              >
                Add User
              </button>
            </div>
          </div>

          {/* Table */}
          <div className="table-responsive mt-3">
            <table className="table table-bordered" style={styles.tableContainer}>
                <thead>
                    <tr>
                        <th>No.</th> {/* Kolom untuk Nomor Urut */}
                        <th>
                            <button className="btn" onClick={() => handleSort('fullName')} style={styles.buttonStyle}>
                                Full Name
                                {sortConfig.key === 'fullName' && 
                                    (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                }
                                {sortConfig.key !== 'fullName' && <FaSort style={styles.iconMarginLeft} />}
                            </button>
                        </th>
                        <th>
                            <button className="btn" onClick={() => handleSort('email')} style={styles.buttonStyle}>
                                Email
                                {sortConfig.key === 'email' && 
                                    (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                }
                                {sortConfig.key !== 'email' && <FaSort style={styles.iconMarginLeft} />}
                            </button>
                        </th>
                        <th style={{ textAlign: 'center', verticalAlign: 'middle' }}>Action</th>
                    </tr>
                </thead>

                <tbody>
                    {paginatedData.length > 0 ? (
                        paginatedData.map((transaction, index) => (
                            <tr key={index}>
                                {/* Kolom Nomor Urut */}
                                <td>{(currentPage - 1) * dataPerPage + index + 1}</td>
                                <td>{transaction.fullName}</td>
                                <td>{transaction.email}</td>
                                <td style={{ textAlign: 'center' }}>
                                  <div style={{ display: 'flex', justifyContent: 'center', gap: '10px' }}>                                    
                                      <button
                                          className="btn btn-danger"
                                          style={{ display: 'flex', alignItems: 'center' }}
                                          onClick={() => handleDelete(transaction.transactionId)}
                                      >
                                          <FaTrash style={{ marginRight: '5px' }} />
                                          Delete
                                      </button>
                                  </div>
                                </td>
                            </tr>
                        ))
                    ) : (
                        <tr>
                            <td colSpan="7" className="text-center">
                                <div className="d-flex flex-column align-items-center mt-5">
                                    <img src={NoAvailable} alt="No Data Available" className="mb-3" style={styles.iconStyle} />
                                    <p>Data not available</p>
                                </div>
                            </td>
                        </tr>
                    )}
                </tbody>
            </table>
          </div>

          {/* Pagination */}
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={handlePageChange}
          />
        </>
      )}      
    </div>
  );
};

const EditRoles = () => {
  const verifyTabs = [
    { name: "Access Menu", component: <AccessMenu /> },
    { name: "User", component: <AccessUser /> },
  ];

  const [isMobile, setIsMobile] = useState(false);
  const [activeTab, setActiveTab] = useState(verifyTabs[0]); // Default to the first tab

  // Update state isMobile berdasarkan ukuran layar
  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth <= 768);
    };

    handleResize();
    window.addEventListener("resize", handleResize);

    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const styles = {
    section: {
      padding: "20px",
      border: "0.1px solid rgba(0, 0, 0, 0.2)",
      borderLeft: "4px solid #0542CC",
      borderRadius: "10px",
      width: "100%",
    },
    tabButton: {
      cursor: "pointer",
    },
  };

  return (
    <div style={styles.section}>
      <div
        className={`d-flex ${isMobile ? "flex-column" : "flex-row"} justify-content-between align-items-center mb-3`}
      >
        <div className="d-flex flex-wrap">
          {verifyTabs.map((tab, index) => (
            <button
              key={index}
              onClick={() => setActiveTab(tab)} // Set active tab
              className={`btn ${
                activeTab.name === tab.name ? "btn-primary" : "btn-light"
              } me-2 mb-2`}
              style={styles.tabButton}
            >
              {tab.name}
            </button>
          ))}
        </div>
      </div>

      {/* Dynamic Tab Content */}
      <div>{activeTab.component}</div>
    </div>
  );
};

const Pagination = ({ currentPage, totalPages, onPageChange }) => {
  const handlePrev = () => {
      if (currentPage > 1) {
          onPageChange(currentPage - 1);
      }
  };

  const handleNext = () => {
      if (currentPage < totalPages) {
          onPageChange(currentPage + 1);
      }
  };

  const handleFirst = () => {
      onPageChange(1); // Go to first page
  };

  const handleLast = () => {
      onPageChange(totalPages); // Go to last page
  };

  // Logic to display only 3 pages in pagination
  const getPaginationRange = () => {
      const range = [];
      const totalPagesCount = totalPages;

      let start = currentPage - 1;
      let end = currentPage + 1;

      // Adjust start and end if near the boundaries
      if (currentPage === 1) {
          start = 1;
          end = Math.min(3, totalPagesCount);
      } else if (currentPage === totalPages) {
          start = Math.max(totalPagesCount - 2, 1);
          end = totalPagesCount;
      }

      for (let i = start; i <= end; i++) {
          range.push(i);
      }

      return range;
  };

  const pageRange = getPaginationRange();

  return (
      <div className="pagination-container d-flex justify-content-end mt-4">
          {/* First Page Button */}
          <button
              className="btn"
              onClick={handleFirst}
              disabled={currentPage === 1}
          >
              <FaFastBackward /> {/* Double Arrow Left */}
          </button>

          <button
              className="btn"
              onClick={handlePrev}
              disabled={currentPage === 1}
          >
              <FaChevronLeft /> {/* Single Arrow Left */}
          </button>

          {/* Page Numbers */}
          {pageRange.map((pageNum) => (
              <button
                  key={pageNum}
                  className={`btn ${pageNum === currentPage ? 'btn-primary' : ''}`}
                  onClick={() => onPageChange(pageNum)}
              >
                  {pageNum}
              </button>
          ))}

          <button
              className="btn"
              onClick={handleNext}
              disabled={currentPage === totalPages}
          >
              <FaChevronRight /> {/* Single Arrow Right */}
          </button>

          {/* Last Page Button */}
          <button
              className="btn"
              onClick={handleLast}
              disabled={currentPage === totalPages}
          >
              <FaFastForward /> {/* Double Arrow Right */}
          </button>
      </div>
  );
};

const TableUser = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const [isMobile, setIsMobile] = useState(false); // State to detect mobile view
    const [transactionData, setTransactionData] = useState([]);
    const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' }); // Sorting state
    const dataPerPage = 5; // Data per page (10 data per page)
    const [showAddUser, setShowAddUser] = useState(false); // State to toggle between views

    const buttonData = [
      { label: 'Copy', enabled: true },
      { label: 'CSV', enabled: true },
      { label: 'Excel', enabled: true },
      { label: 'PDF', enabled: true },
      { label: 'Print', enabled: true },
      { label: 'Column Visibility', enabled: true },
    ];
  

    // Generate 691 dummy transactions
    const generateDummyData = (numOfItems) => {
      const transactionData = [];
      
      for (let i = 1; i <= numOfItems; i++) {
        transactionData.push({
          fullName: `${['John', 'Jane', 'James', 'Maria', 'Sophia'][Math.floor(Math.random() * 5)]} ${['Doe', 'Smith', 'Johnson', 'Williams', 'Brown'][Math.floor(Math.random() * 5)]}`, // Full Name (First and Last Name)
          email: `${['john', 'jane', 'james', 'maria', 'sophia'][Math.floor(Math.random() * 5)]}${Math.floor(Math.random() * 1000)}@example.com`, // Random Email
        });    
      }
    
      
      return transactionData;
    };


    // Set the generated transaction data
    useEffect(() => {
        setTransactionData(generateDummyData(31)); // count data dummy transactions
    }, []);

    // Sorting function
    const sortData = (data, config) => {
      const { key, direction } = config;
      return [...data].sort((a, b) => {
          if (a[key] < b[key]) {
              return direction === 'asc' ? -1 : 1;
          }
          if (a[key] > b[key]) {
              return direction === 'asc' ? 1 : -1;
          }
          return 0;
      });
    };

    // Handle column header sort click
    const handleSort = (key) => {
        let direction = 'asc';
        if (sortConfig.key === key && sortConfig.direction === 'asc') {
            direction = 'desc'; // Toggle direction if the same column is clicked
        }
        setSortConfig({ key, direction });
    };

    // Get the paginated data
    const getPaginatedData = (data, page, perPage) => {
        const sortedData = sortData(data, sortConfig);
        const startIndex = (page - 1) * perPage;
        const endIndex = startIndex + perPage;
        return sortedData.slice(startIndex, endIndex);
    };

    // Handle page change
    const handlePageChange = (page) => {
        setCurrentPage(page);
    };

    // Calculate total pages based on the data and data per page
    const totalPages = Math.ceil(transactionData.length / dataPerPage);

    // Paginated data
    const paginatedData = getPaginatedData(transactionData, currentPage, dataPerPage);

    // Detect screen size and update isMobile state
    useEffect(() => {
        const handleResize = () => {
            setIsMobile(window.innerWidth <= 768); // Change 768 to your breakpoint
        };

        handleResize();
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    const handleDelete = (transactionId) => {
      console.log(`Delete transaction with ID:`);
      // Add your delete logic here
    };

    const handleAddUserClick = () => {
      setShowAddUser(true); // Switch to AddUser view when button is clicked
    };

    return (
      <div className="container">   
        {showAddUser ? (
            <AddUser/>
        ) : (
          <>
            {/* Filter Form */}
            <div className="row" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div className="col-6 d-flex justify-content-start align-items-center">
                <h1 className='text-primary'>PT.ABC</h1> {/* Title on the left */}
              </div>

              <div className={`col-md-2 ${isMobile ? 'd-flex justify-content-end' : 'd-flex align-items-end'}`}>
                <button 
                  className="btn text-white" 
                  style={{ marginLeft: '0.6rem', backgroundColor: '#0542cc', width: '100%' }}
                  onClick={handleAddUserClick}
                  >
                    Add User
                </button>
              </div>
            </div>

            {/* Action Buttons */}
            <div className="d-flex justify-content-between align-items-center my-3">
                <div>
                    {buttonData.map((button, index) =>
                      button.enabled ? (
                          <button
                              key={index}
                              className={`btn btn-light ${isMobile ? 'mb-2' : ''}`} // Add margin on mobile
                              style={styles.actionButton}
                          >
                              {button.label}
                          </button>
                      ) : null
                    )}
                </div>

                {/* Search Bar with Icon */}
                <div className="input-group" style={{ width: '250px', display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                    <input
                        type="text"
                        placeholder="Search..."
                        className="form-control"
                    />
                    <span className="input-group-text">
                        <i className="fas fa-search"></i> {/* FontAwesome search icon */}
                    </span>
                </div>
            </div>

            {/* Table */}
            <div className="table-responsive">
              <table className="table table-bordered" style={styles.tableContainer}>
                  <thead>
                      <tr>
                          <th>No.</th> {/* Kolom untuk Nomor Urut */}
                          <th>
                              <button className="btn" onClick={() => handleSort('fullName')} style={styles.buttonStyle}>
                                  Full Name
                                  {sortConfig.key === 'fullName' && 
                                      (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                  }
                                  {sortConfig.key !== 'fullName' && <FaSort style={styles.iconMarginLeft} />}
                              </button>
                          </th>
                          <th>
                              <button className="btn" onClick={() => handleSort('email')} style={styles.buttonStyle}>
                                  Email
                                  {sortConfig.key === 'email' && 
                                      (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                  }
                                  {sortConfig.key !== 'email' && <FaSort style={styles.iconMarginLeft} />}
                              </button>
                          </th>
                          <th style={{ textAlign: 'center', verticalAlign: 'middle' }}>Action</th>
                      </tr>
                  </thead>

                  <tbody>
                      {paginatedData.length > 0 ? (
                          paginatedData.map((transaction, index) => (
                              <tr key={index}>
                                  {/* Kolom Nomor Urut */}
                                  <td>{(currentPage - 1) * dataPerPage + index + 1}</td>
                                  <td>{transaction.fullName}</td>
                                  <td>{transaction.email}</td>
                                  <td style={{ textAlign: 'center' }}>
                                    <div style={{ display: 'flex', justifyContent: 'center', gap: '10px' }}>                                    
                                        <button
                                            className="btn btn-danger"
                                            style={{ display: 'flex', alignItems: 'center' }}
                                            onClick={() => handleDelete(transaction.transactionId)}
                                        >
                                            <FaTrash style={{ marginRight: '5px' }} />
                                            Delete
                                        </button>
                                    </div>
                                  </td>
                              </tr>
                          ))
                      ) : (
                          <tr>
                              <td colSpan="7" className="text-center">
                                  <div className="d-flex flex-column align-items-center mt-5">
                                      <img src={NoAvailable} alt="No Data Available" className="mb-3" style={styles.iconStyle} />
                                      <p>Data not available</p>
                                  </div>
                              </td>
                          </tr>
                      )}
                  </tbody>
              </table>
            </div>

            {/* Pagination */}
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={handlePageChange}
            />
          </>
        )}      
      </div>
    );
};

const TableRole = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [isMobile, setIsMobile] = useState(false); // State to detect mobile view
  const [transactionData, setTransactionData] = useState([]);
  const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' }); // Sorting state
  const dataPerPage = 5; // Data per page (10 data per page)
  const [showRole, setShowRole] = useState(false); // State to toggle between views
  const [editRole, setEditRole] = useState(false); // State to toggle between views

  const buttonData = [
    { label: 'Copy', enabled: true },
    { label: 'CSV', enabled: true },
    { label: 'Excel', enabled: true },
    { label: 'PDF', enabled: true },
    { label: 'Print', enabled: true },
    { label: 'Column Visibility', enabled: true },
  ];

  // Generate 691 dummy transactions
  const generateDummyData = (numOfItems) => {
    const transactionData = [];
    
    for (let i = 1; i <= numOfItems; i++) {
      transactionData.push({
        fullName: `${['John', 'Jane', 'James', 'Maria', 'Sophia'][Math.floor(Math.random() * 5)]} ${['Doe', 'Smith', 'Johnson', 'Williams', 'Brown'][Math.floor(Math.random() * 5)]}`, // Full Name (First and Last Name)
        userCount: Math.floor(Math.random() * 1000) + 1, 
      });    
    }
  
    
    return transactionData;
  };

  // Set the generated transaction data
  useEffect(() => {
      setTransactionData(generateDummyData(31)); // count data dummy transactions
  }, []);

  // Sorting function
  const sortData = (data, config) => {
    const { key, direction } = config;
    return [...data].sort((a, b) => {
        if (a[key] < b[key]) {
            return direction === 'asc' ? -1 : 1;
        }
        if (a[key] > b[key]) {
            return direction === 'asc' ? 1 : -1;
        }
        return 0;
    });
  };

  // Handle column header sort click
  const handleSort = (key) => {
      let direction = 'asc';
      if (sortConfig.key === key && sortConfig.direction === 'asc') {
          direction = 'desc'; // Toggle direction if the same column is clicked
      }
      setSortConfig({ key, direction });
  };

  // Get the paginated data
  const getPaginatedData = (data, page, perPage) => {
      const sortedData = sortData(data, sortConfig);
      const startIndex = (page - 1) * perPage;
      const endIndex = startIndex + perPage;
      return sortedData.slice(startIndex, endIndex);
  };

  // Handle page change
  const handlePageChange = (page) => {
      setCurrentPage(page);
  };

  // Calculate total pages based on the data and data per page
  const totalPages = Math.ceil(transactionData.length / dataPerPage);

  // Paginated data
  const paginatedData = getPaginatedData(transactionData, currentPage, dataPerPage);

  // Detect screen size and update isMobile state
  useEffect(() => {
      const handleResize = () => {
          setIsMobile(window.innerWidth <= 768); // Change 768 to your breakpoint
      };

      handleResize();
      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
  }, []);

  const handleDelete = (transactionId) => {
    console.log(`Delete transaction with ID:`);
    // Add your delete logic here
  };

  const handleEdit = (transactionId) => {
    console.log(`Edit transaction with ID:`);
    setEditRole(true); // Switch to EditUser view when button is clicked
    // Add your edit logic here
  };

  const handleAddRoleClick = () => {
    setShowRole(true); // Switch to AddUser view when button is clicked
  };

  return (
    <div className="container">         
      {
        showRole ? (
          <AddRoles/>
        ) : editRole ? (
          <EditRoles/>
        ) : (
          <>
            {/* Filter Form */}
            <div className="row" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div className="col-6 d-flex justify-content-start align-items-center">
                <h1 className='text-primary'>PT.ABC</h1> {/* Title on the left */}
              </div>

              <div className={`col-md-2 ${isMobile ? 'd-flex justify-content-end' : 'd-flex align-items-end'}`}>
                <button 
                  className="btn text-white" 
                  style={{ marginLeft: '0.6rem', backgroundColor: '#0542cc', width: '100%' }}
                  onClick={handleAddRoleClick}
                >
                    Add Role
                  </button>
              </div>
            </div>

            {/* Action Buttons */}
            <div className="d-flex justify-content-between align-items-center my-3">
                <div>
                    {buttonData.map((button, index) =>
                      button.enabled ? (
                          <button
                              key={index}
                              className={`btn btn-light ${isMobile ? 'mb-2' : ''}`} // Add margin on mobile
                              style={styles.actionButton}
                          >
                              {button.label}
                          </button>
                      ) : null
                    )}
                </div>

                {/* Search Bar with Icon */}
                <div className="input-group" style={{ width: '250px', display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                    <input
                        type="text"
                        placeholder="Search..."
                        className="form-control"
                    />
                    <span className="input-group-text">
                        <i className="fas fa-search"></i> {/* FontAwesome search icon */}
                    </span>
                </div>
            </div>

            {/* Table */}
            <div className="table-responsive">
              <table className="table table-bordered" style={styles.tableContainer}>
                  <thead>
                      <tr>
                          <th>No.</th> {/* Kolom untuk Nomor Urut */}
                          <th>
                              <button className="btn" onClick={() => handleSort('fullName')} style={styles.buttonStyle}>
                                  Full Name
                                  {sortConfig.key === 'fullName' && 
                                      (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                  }
                                  {sortConfig.key !== 'fullName' && <FaSort style={styles.iconMarginLeft} />}
                              </button>
                          </th>
                          <th>
                              <button className="btn" onClick={() => handleSort('userCount')} style={styles.buttonStyle}>
                                  Total User
                                  {sortConfig.key === 'userCount' && 
                                      (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                  }
                                  {sortConfig.key !== 'userCount' && <FaSort style={styles.iconMarginLeft} />}
                              </button>
                          </th>
                          <th style={{ textAlign: 'center', verticalAlign: 'middle' }}>Action</th>
                      </tr>
                  </thead>

                  <tbody>
                      {paginatedData.length > 0 ? (
                          paginatedData.map((transaction, index) => (
                              <tr key={index}>
                                  {/* Kolom Nomor Urut */}
                                  <td>{(currentPage - 1) * dataPerPage + index + 1}</td>
                                  <td>{transaction.fullName}</td>
                                  <td>{transaction.userCount}</td>
                                  <td style={{ textAlign: 'center' }}>
                                    <div style={{ display: 'flex', justifyContent: 'center', gap: '10px' }}>                                    
                                        <button
                                            className="btn btn-danger"
                                            style={{ display: 'flex', alignItems: 'center' }}
                                            onClick={() => handleDelete(transaction.transactionId)}
                                        >
                                            <FaTrash style={{ marginRight: '5px' }} />
                                            Delete
                                        </button>
                                        <button
                                            className="btn btn-primary"
                                            style={{ display: 'flex', alignItems: 'center' }}
                                            onClick={() => handleEdit(transaction.transactionId)}
                                        >
                                            <FaEdit style={{ marginRight: '5px' }} />
                                            Edit
                                        </button>
                                    </div>
                                  </td>
                              </tr>
                          ))
                      ) : (
                          <tr>
                              <td colSpan="7" className="text-center">
                                  <div className="d-flex flex-column align-items-center mt-5">
                                      <img src={NoAvailable} alt="No Data Available" className="mb-3" style={styles.iconStyle} />
                                      <p>Data not available</p>
                                  </div>
                              </td>
                          </tr>
                      )}
                  </tbody>
              </table>
            </div>

            {/* Pagination */}
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={handlePageChange}
            />
          </>
        )
      }
    </div>
  );
};

const Company = () => {
  const [activeTab, setActiveTab] = useState('user');
 
  const renderTabContent = () => {
    switch (activeTab) {
      case 'user':
        return (
          <>
            <strong style={{ marginLeft: '0.9rem' }}>Company Access Name</strong>
            <div className='pt-1 pb-5'>
              <TableUser />
            </div>
          </>
        );
      case 'roles':
        return (
          <>
            <strong style={{ marginLeft: '0.9rem' }}>Company Access Name</strong>
            <div className='pt-1 pb-5'>
              <TableRole />
            </div>
          </>
        );
      default:
        return null;
    }
  };

  return (
    <div className="container mt-5">
      <div className="row gx-5">
        {/* Tab Navigation - 3 Col */}
        <div className="col-md-3 border-end" style={styles.tabContainer}>
          <div className="nav flex-column nav-pills">
            <button
              className={`nav-link ${activeTab === 'user' ? 'active' : ''}`}
              onClick={() => setActiveTab('user')}
              style={styles.tabButton}
            >
              <i className="fas fa-users me-2"></i> User List
            </button>
            <button
              className={`nav-link ${activeTab === 'roles' ? 'active' : ''}`}
              onClick={() => setActiveTab('roles')}
              style={styles.tabButton}
            >
              <i className="fas fa-globe me-2"></i> Roles Access
            </button>
          </div>
        </div>

        {/* Content Area - 9 Col */}
        <div className="col-md-9">
          <div style={styles.contentContainer}>
            {renderTabContent()}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Company;

// Styles untuk elemen-elemen
const styles = {
  tabContainer: {
    border: '1px solid #d3d3d3',
    borderLeft: '4px solid #0542cc',
    alignItems: 'center',
    justifyContent: 'flex-start',
    display: 'flex',
    boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
  },
  tabButton: {
    display: 'flex',
    justifyContent: 'flex-start',
    alignItems: 'center',
  },
  contentContainer: {
    border: '1px solid #d3d3d3',
    height: '23rem',
    overflowY: 'auto',
    padding: '1rem 0 0 1.7rem',
    boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
  },
  inputGroup: {
    width: '200px',
  },
  errorText: {
    color: 'red',
    fontSize: '0.8rem',
  },
  tableContainer: {
    minHeight: '300px',
    maxHeight: '1500px',
    overflowY: 'auto',
  },
  iconStyle: {
      width: '50px',
      height: '50px',
  },
  // Add margin-left style for icons
  iconMarginLeft: {
    marginLeft: '0.5rem',
    verticalAlign: 'middle', 
  },
  buttonStyle: {
    display: 'inline-flex',         
    justifyContent: 'flex-start',   
    alignItems: 'center',           
    padding: '0.5rem 1rem',          
  },
  actionButton: {
    borderColor: '#000',
    border: '1px solid black',
    margin: '0 8px 8px 0', 
    padding: '8px 16px', 
  }
};
