import React, { useState, useEffect } from 'react';
import { FaChevronLeft, FaChevronRight, FaFastBackward, FaFastForward, FaSort, FaSortUp, FaSortDown } from 'react-icons/fa'; // Icons for sorting
import { NoAvailable } from '../../../assets/icon';
import Select from 'react-select'
import { ServerDownAnimation } from '../../../assets/images';


const BASE_URL = process.env.REACT_APP_BASE_URL;
const API_KEY = process.env.REACT_APP_API_KEY;


// Pagination Component
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 Anomaly = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const [phoneNumber, setPhoneNumber] = useState('');
    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 = 10; // Data per page (10 data per page)
    const [applicationId, setApplicationId] = useState('');
    const [applicationIds, setApplicationIds] = useState([]);
    const [inputValueApplication, setInputValueApplication] = useState('');

    const [isLoading, setIsLoading] = useState(false);
    const [isServer, setIsServer] = useState(true);
    const [errorMessage, setErrorMessage] = useState('');

    const applicationOptions = applicationIds.map(app => ({
      value: app.id,   // This is what will be sent when an option is selected
      label: app.name  // This is what will be displayed in the dropdown
    }));

    // Validation state
    const [validationErrors, setValidationErrors] = useState({
      applicationId: '',
      file: ''
    });


    const handleApplicationChange = (selectedOption) => {
      const selectedId = selectedOption.value;
      const selectedApp = applicationIds.find(app => app.id === parseInt(selectedId));

      setApplicationId(selectedOption ? selectedOption.value : '');
    };

    const handleInputChangeApplication = (inputValue) => {
      setInputValueApplication(inputValue);
    };

    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({
          date: new Date(2023, Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1).toLocaleDateString(), // Random date
          applicationId: `APP${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`, // Random Application ID
          applicationName: `App ${Math.floor(Math.random() * 5) + 1}`, // Application Name
          smsType: ['Promotional', 'Transactional'][Math.floor(Math.random() * 2)], // Random SMS Type
          phoneNumber: `+62${Math.floor(Math.random() * 900000000) + 800000000}`, // Random phone number
          tryCount: Math.floor(Math.random() * 5) + 1, // Random try count between 1 and 5
        });      
      }
    
      
      return transactionData;
    };

    useEffect(() => {
      const fetchApplicationIds = async () => {
        try {
            setIsLoading(true);
            const response = await fetch(`${BASE_URL}/application/list`, {
                method: 'GET',
                headers: {
                    'accept': 'application/json',
                    'x-api-key': API_KEY,
                },
            });
    
            if (!response.ok) {
                throw new Error('Failed to fetch application IDs');
            }
    
            const data = await response.json();
            console.log('Response Data:', data);
    
            if (data.status_code === 200) {
                setApplicationIds(data.details.data);
                setIsServer(true);
            } else {
                setIsServer(false);
                throw new Error(data.details.message || 'Failed to fetch application IDs');
            }
        } catch (error) {
            setErrorMessage(error.message || 'Error fetching application IDs');
            setIsServer(false);
        } finally {
            setIsLoading(false);
        }
      };              

      fetchApplicationIds();

      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);
    }, []);

    if (!isServer) {
      return (
          <div style={{ textAlign: 'center', marginTop: '50px' }}>
              <img 
                  src={ServerDownAnimation} 
                  alt="Server Down Animation" 
                  style={{ width: '18rem', height: '18rem', marginBottom: '20px' }} 
              />
              <h2 style={{ color: 'red' }}>Server tidak dapat diakses</h2>
              <p>{errorMessage || 'Silakan periksa koneksi internet Anda atau coba lagi nanti.'}</p>
              <button 
                  onClick={() => window.location.reload()} 
                  style={{
                      padding: '10px 20px',
                      backgroundColor: '#0542cc',
                      color: '#fff',
                      border: 'none',
                      borderRadius: '5px',
                      cursor: 'pointer'
                  }}>
                  Coba Lagi
              </button>
          </div>
      );
    }   

    return (
      <div className="container mt-5">
        {/* Inject keyframes for the spinner */}
        <style>
        {`
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `}
        </style>
        {isLoading && (
            <div style={styles.loadingOverlay}>
                <div style={styles.spinner}></div>
                <p style={styles.loadingText}>Loading...</p>
            </div>
        )}

        {/* Welcome Message */}
        <div className="row-card border-left border-primary shadow mb-4" style={{ backgroundColor: '#E2FBEA' }}>
            <div className="d-flex flex-column justify-content-start align-items-start p-4">
                <div>
                    <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>
            </div>
        </div>

        <div style={styles.contentContainer}>
          <strong>Please input the phone number first to show data</strong>
          <div className="col-md-8 mt-2">
            <div className="d-flex align-items-center">
              <div style={styles.selectWrapper}>
                <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} // Limit input length for Application ID
                />
              </div>
              {validationErrors.applicationId && <p style={styles.errorText}>{validationErrors.applicationId}</p>}
              <button className="btn text-white" style={{ backgroundColor: '#0542cc', marginLeft: '2vh', width: '20%' }}>Search</button>
            </div>
          </div>
        </div>

        <div style={styles.contentContainer}>
            {/* Filter Form */}
            <div className="card p-3 mb-4">
                <div className="row">
                    <div className={`col-12 ${isMobile ? 'mb-2' : 'col-md-2'}`}>
                        <label>Start Date</label>
                        <input type="date" className="form-control" />
                    </div>
                    <div className={`col-12 ${isMobile ? 'mb-2' : 'col-md-2'}`}>
                        <label>End Date</label>
                        <input type="date" className="form-control" />
                    </div>
                    <div className={`col-12 ${isMobile ? 'mb-2' : 'col-md-2'}`}>
                        <label>Services</label>
                        <select className="form-control">
                            <option>Select Services</option>
                            <option>Service 1</option>
                            <option>Service 2</option>
                            <option>Service 3</option>
                            <option>Service 4</option>
                            <option>Service 5</option>
                        </select>
                    </div>
                    <div className={`col-12 ${isMobile ? 'mb-2' : 'col-md-2'}`}>
                        <label>Feature</label>
                        <select className="form-control">
                            <option>Select Feature</option>
                            <option>Feature 1</option>
                            <option>Feature 2</option>
                            <option>Feature 3</option>
                        </select>
                    </div>
                    <div className={`col-12 ${isMobile ? 'd-flex justify-content-between' : 'col-md-2 d-flex align-items-end'}`} style={{ gap: '10px' }}>
                        <button className="btn btn-primary w-48">Apply</button>
                        <button className="btn btn-secondary w-48">Cancel</button>
                    </div>
                </div>
            </div>

            {/* Action Buttons */}
            <div className="d-flex justify-content-between align-items-center mb-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('applicationId')}>
                                  Application Id 
                                  {sortConfig.key === 'applicationId' && 
                                      (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                  }
                                  {sortConfig.key !== 'applicationId' && <FaSort style={styles.iconMarginLeft} />}
                              </button>
                          </th>
                          <th>
                              <button className="btn" onClick={() => handleSort('applicationName')}>
                                  Application Name 
                                  {sortConfig.key === 'applicationName' && 
                                      (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                  }
                                  {sortConfig.key !== 'applicationName' && <FaSort style={styles.iconMarginLeft} />}
                              </button>
                          </th>
                          <th>
                              <button className="btn" onClick={() => handleSort('smsType')}>
                                  SMS Type
                                  {sortConfig.key === 'smsType' && 
                                      (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                  }
                                  {sortConfig.key !== 'smsType' && <FaSort style={styles.iconMarginLeft} />}
                              </button>
                          </th>
                          <th>
                              <button className="btn" onClick={() => handleSort('phoneNumber')}>
                                  Phone Number
                                  {sortConfig.key === 'phoneNumber' && 
                                      (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                  }
                                  {sortConfig.key !== 'phoneNumber' && <FaSort style={styles.iconMarginLeft} />}
                              </button>
                          </th>
                          <th>
                              <button className="btn" onClick={() => handleSort('tryCount')}>
                                  Try Count
                                  {sortConfig.key === 'tryCount' && 
                                      (sortConfig.direction === 'asc' ? <FaSortUp style={styles.iconMarginLeft} /> : <FaSortDown style={styles.iconMarginLeft} />)
                                  }
                                  {sortConfig.key !== 'tryCount' && <FaSort style={styles.iconMarginLeft} />}
                              </button>
                          </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.applicationId}</td>
                                  <td>{transaction.applicationName}</td>
                                  <td>{transaction.smsType}</td>
                                  <td>{transaction.phoneNumber}</td>
                                  <td>{transaction.tryCount}</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>
      </div>
    );
};

export default Anomaly;

const styles = {
  contentContainer: {
      padding: '20px',
      border: '0.1px solid rgba(0, 0, 0, 0.2)',
      borderLeft: '4px solid #0542cc',
      borderRadius: '10px',
      width: '100%',
  },
  selectWrapper: {
    position: 'relative',
    display: 'inline-block',
    width: '100%',
  },
  tableContainer: {
      minHeight: '300px',
      maxHeight: '1500px',
      overflowY: 'auto',
  },
  iconStyle: {
      width: '50px',
      height: '50px',
  },
  // Add margin-left style for icons
  iconMarginLeft: {
      marginLeft: '0.7rem', // Adjust as needed
  },
  loadingOverlay: {
    position: 'fixed',  // Gunakan fixed untuk overlay penuh layar
    top: 0, 
    left: 0, 
    right: 0, 
    bottom: 0,  // Pastikan menutupi seluruh layar
    display: 'flex',
    justifyContent: 'center',  // Posisikan spinner di tengah secara horizontal
    alignItems: 'center',      // Posisikan spinner di tengah secara vertikal
    backgroundColor: 'rgba(0, 0, 0, 0.5)',  // Semitransparan di background
    color: 'white',
    fontSize: '24px',
    zIndex: 1000,  // Pastikan overlay muncul di atas konten lainnya
  },
  spinner: {
      border: '4px solid #f3f3f3', // Border gray untuk spinner
      borderTop: '4px solid #3498db', // Border biru untuk spinner
      borderRadius: '50%',  // Membuat spinner bulat
      width: '50px', // Ukuran spinner
      height: '50px', // Ukuran spinner
      animation: 'spin 2s linear infinite', // Menambahkan animasi spin
  },
  loadingText: {
      marginLeft: '20px',
  },
};

