import React, { useState } from 'react';
import DateDisplay from './DateDisplay';

const StyledTable = ({ 
  data = [], 
  columns = [], 
  itemsPerPage = 4,
  showEdit = true,
  title = "Styled Table",
  onView = null,
  onEdit = () => {},
  onDelete = () => {},
  onToggleStatus = null,
  noDataText = "No data available",
  disablePagination = false,
  serverPagination = null, // { current_page, last_page, from, to, total, links }
  onPageChange = null, // Function to handle page changes
  itemType = "items", // Type of items for pagination text
  customActions = null, // Function that returns extra <li> elements for actions
}) => {
  const [currentPage, setCurrentPage] = useState(1);
  
  // Ensure data is an array
  const safeData = Array.isArray(data) ? data : [];
  
  // Use all data if pagination is disabled, otherwise paginate
  const currentData = disablePagination ? safeData : (() => {
    const totalPages = Math.ceil(safeData.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    return safeData.slice(startIndex, endIndex);
  })();
  
  const totalPages = Math.ceil(safeData.length / itemsPerPage);

  return (
    <div className="col-12 mt-2">
      <div className="card">
        <div className="card-body">
          <h4 className="header-title">{title}</h4>
          <div className="single-table">
            <div className="table-responsive">
              <table className="table table-hover text-center">
                <thead className="bg-light text-capitalize">
                  <tr>
                    {columns.map((column, index) => (
                      <th key={index} scope="col">{column.header}</th>
                    ))}
                    <th scope="col">action</th>
                  </tr>
                </thead>
                <tbody>
                  {currentData.length > 0 ? (
                    currentData.map((row, index) => (
                      <tr key={index}>
                        {columns.map((column, colIndex) => {
                          //displaying download button
                          if (column.key === 'file') {
                            const filePath = row[column.key];
                            return (
                              <td key={colIndex}>
                                {filePath ? (
                                  <a 
                                    href={`/storage/${filePath}`} 
                                    download 
                                    className="badge badge-primary"
                                  >
                                    Download File
                                  </a>
                                ) : (
                                  <span className="text-muted">No file available</span>
                                )}
                              </td>
                            );
                          } 
                          
                          //displaying dates
                          if (column.key === 'created_at' || column.key === 'updated_at') {
                            return (
                              <td key={colIndex}>
                                <DateDisplay date={row[column.key]} />
                              </td>
                            );
                          }
                          
                          //displaying image columns in table
                          if (column.key === 'photo' || column.key === 'logo') {
                            return (
                                <td key={colIndex}>
                                    {row[column.key] ? (
                                        <img 
                                            src={`/storage/${row[column.key]}`} 
                                            alt={row[column.key]} 
                                            className="img-fluid zoom"
                                            style={{ maxWidth: '80px' }}
                                        />
                                    ) : null} {/* Display nothing if photo or logo is null */}
                                </td>
                            );
                        }                        

                          //tags and categories 
                          if ( column.key === 'categories') {
                            const items = row[column.key];
                            const type = column.key === 'tags' ? 'tag' : 'category';
                            
                            return (
                                <td key={colIndex}>
                                    {items && items.length > 0 ? (
                                        items.map((item, index) => (
                                            <span 
                                                key={index} 
                                                className={`badge ${type === 'tag' ? 'badge-primary' : 'badge-light'} mr-1`}
                                            >
                                                {item.title}
                                            </span>
                                        ))
                                    ) : (
                                        <span className="text-muted">
                                            No {type} available
                                        </span>
                                    )}
                                </td>
                            );
                        }

                        //tags
                        if (column.key === 'tags') {
                          const items = row[column.key];
                          const type = column.key === 'tag';
                          
                          return (
                              <td key={colIndex}>
                                  {items && items.length > 0 ? (
                                      items.map((item, index) => (
                                          <span 
                                              key={index} 
                                              className={`badge ${type === 'tag' ? 'badge-primary' : 'badge-light'} mr-1`}
                                          >
                                              {item}
                                          </span>
                                      ))
                                  ) : (
                                      <span className="text-muted">
                                          No {type} available
                                      </span>
                                  )}
                              </td>
                          );
                      }

                        if (column.key === 'is_featured') {
                          const isFeatured = row[column.key];
                          return (
                            <td key={colIndex} className="text-center">
                              {isFeatured === 1 || isFeatured === '1' ? (
                                <span className="text-success">✅</span>
                              ) : (
                                <span className="text-danger">❌</span>
                              )}
                            </td>
                          );
                        }                        

                          //displaying products
                          if (column.key === 'products') {
                            const products = row[column.key];
                            return (
                              <td key={colIndex}>
                                {products && products.length > 0 ? (
                                  products.map((product, index) => (
                                    <span key={index} className="badge badge-primary mr-1">
                                      {product.name}
                                    </span>
                                  ))
                                ) : (
                                  <span className="text-muted">No product available</span>
                                )}
                              </td>
                            );
                          }
                          
                          //status badges
                          if (column.key === 'status') {
                            return (
                           <td key={colIndex}>
                            <span className={`badge ${
                              row[column.key] === 'active' 
                                ? 'badge-success' 
                                : row[column.key] === 'inactive'
                                ? 'badge-warning'
                                : 'badge-danger'
                            }`}>
                              {row[column.key].charAt(0).toUpperCase() + row[column.key].slice(1)}
                            </span>
                           </td>
                            );
                           }

                          //is_active status for chatbot
                          if (column.key === 'is_active') {
                            return (
                              <td key={colIndex}>
                                <span className={`badge ${row[column.key] ? 'badge-success' : 'badge-danger'}`}>
                                  {row[column.key] ? 'Active' : 'Inactive'}
                                </span>
                              </td>
                            );
                          }

                          //keywords display for chatbot
                          if (column.key === 'keywords') {
                            const keywords = row[column.key];
                            return (
                              <td key={colIndex}>
                                {keywords && keywords.length > 0 ? (
                                  keywords.slice(0, 3).map((keyword, index) => (
                                    <span key={index} className="badge badge-light mr-1">
                                      {keyword}
                                    </span>
                                  ))
                                ) : (
                                  <span className="text-muted">No keywords</span>
                                )}
                                {keywords && keywords.length > 3 && (
                                  <span className="badge badge-light">+{keywords.length - 3} more</span>
                                )}
                              </td>
                            );
                          }

                          //category display for chatbot
                          if (column.key === 'category') {
                            return (
                              <td key={colIndex}>
                                <span className="badge badge-info">
                                  {row[column.key]}
                                </span>
                              </td>
                            );
                          }

                          //priority display for chatbot
                          if (column.key === 'priority') {
                            return (
                              <td key={colIndex}>
                                <span className="badge badge-secondary">
                                  {row[column.key]}
                                </span>
                              </td>
                            );
                          }
                          return <td key={colIndex}>{row[column.key]}</td>;
                        })}
                        <td>
                          <ul className="d-flex justify-content-center align-items-center list-unstyled mb-0" style={{ gap: '8px' }}>
                            {onView && (
                              <li>
                                <a
                                  href="#"
                                  className="text-info"
                                  onClick={(e) => {
                                    e.preventDefault();
                                    onView(row);
                                  }}
                                  title="View"
                                  style={{ fontSize: '16px', display: 'inline-block' }}
                                >
                                  <i className="fa fa-eye"></i>
                                </a>
                              </li>
                            )}
                            {showEdit && (
                              <li>
                                <a
                                  href="#"
                                  className="text-warning"
                                  onClick={(e) => {
                                    e.preventDefault();
                                    onEdit(row);
                                  }}
                                  title="Edit"
                                  style={{ fontSize: '16px', display: 'inline-block' }}
                                >
                                  <i className="fa fa-edit"></i>
                                </a>
                              </li>
                            )}
                            {onToggleStatus && (
                              <li>
                                <a
                                  href="#"
                                  className={row.is_active ? "text-secondary" : "text-success"}
                                  onClick={(e) => {
                                    e.preventDefault();
                                    onToggleStatus(row);
                                  }}
                                  title={row.is_active ? "Deactivate" : "Activate"}
                                  style={{ fontSize: '16px', display: 'inline-block' }}
                                >
                                  <i className={`fa fa-${row.is_active ? 'pause' : 'play'}`}></i>
                                </a>
                              </li>
                            )}
                            {customActions && customActions(row)}
                            <li>
                              <a 
                                href="#" 
                                className="text-danger"
                                onClick={(e) => {
                                  e.preventDefault();
                                  onDelete(row);
                                }}
                                title="Delete"
                                style={{ fontSize: '16px', display: 'inline-block' }}
                              >
                                <i className="fa fa-trash"></i>
                              </a>
                            </li>
                          </ul>
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={columns.length + 1} className="text-center py-4">
                        <i className="ti-info-alt mr-2"></i>
                        {noDataText}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

          {/* Client-side pagination */}
          {!disablePagination && !serverPagination && safeData.length > 0 && totalPages > 1 && (
            <div className="col-lg-12 mt-3">
              <nav aria-label="Page navigation example">
                <ul className="pagination">
                  <li className={`page-item ${currentPage === 1 ? 'disabled' : ''}`}>
                    <a 
                      className="page-link" 
                      href="#"
                      onClick={(e) => {
                        e.preventDefault();
                        if (currentPage > 1) setCurrentPage(currentPage - 1);
                      }}
                      aria-label="Previous"
                    >
                      <span aria-hidden="true">&laquo;</span>
                      <span className="sr-only">Previous</span>
                    </a>
                  </li>
                  
                  {[...Array(totalPages)].map((_, i) => (
                    <li 
                      key={i} 
                      className={`page-item ${currentPage === i + 1 ? 'active' : ''}`}
                    >
                      <a 
                        className="page-link" 
                        href="#"
                        onClick={(e) => {
                          e.preventDefault();
                          setCurrentPage(i + 1);
                        }}
                      >
                        {i + 1}
                      </a>
                    </li>
                  ))}

                  <li className={`page-item ${currentPage === totalPages ? 'disabled' : ''}`}>
                    <a 
                      className="page-link" 
                      href="#"
                      onClick={(e) => {
                        e.preventDefault();
                        if (currentPage < totalPages) setCurrentPage(currentPage + 1);
                      }}
                      aria-label="Next"
                    >
                      <span aria-hidden="true">&raquo;</span>
                      <span className="sr-only">Next</span>
                    </a>
                  </li>
                </ul>
              </nav>
            </div>
          )}

          {/* Server-side pagination */}
          {serverPagination && serverPagination.last_page > 1 && (
            <div className="col-lg-12 mt-2">
              <div className="d-flex justify-content-between align-items-center">
                {/* Pagination info */}
                <div className="pagination-info">
                  <span className="text-muted">
                    Showing <strong>{serverPagination.from}</strong> to <strong>{serverPagination.to}</strong> of <strong>{serverPagination.total}</strong> {itemType}
                  </span>
                </div>
                
                {/* Pagination controls */}
                <nav aria-label="Page navigation">
                  <ul className="pagination pagination-sm mb-0">
                    <li className={`page-item ${serverPagination.current_page === 1 ? 'disabled' : ''}`}>
                      <a 
                        className="page-link" 
                        href="#"
                        onClick={(e) => {
                          e.preventDefault();
                          if (serverPagination.current_page > 1 && onPageChange) {
                            onPageChange(serverPagination.current_page - 1);
                          }
                        }}
                        aria-label="Previous"
                      >
                        <span aria-hidden="true">&laquo;</span>
                        <span className="sr-only">Previous</span>
                      </a>
                    </li>
                    
                    {serverPagination.links && serverPagination.links.map((link, i) => {
                      if (link.label === '&laquo; Previous' || link.label === 'Next &raquo;') {
                        return null;
                      }
                      
                      return (
                        <li 
                          key={i}
                          className={`page-item ${link.active ? 'active' : ''} ${!link.url ? 'disabled' : ''}`}
                        >
                          <a 
                            className="page-link" 
                            href="#"
                            onClick={(e) => {
                              e.preventDefault();
                              if (link.url && onPageChange) {
                                const url = new URL(link.url);
                                const page = url.searchParams.get('page') || 1;
                                onPageChange(page);
                              }
                            }}
                          >
                            {link.label}
                          </a>
                        </li>
                      );
                    })}

                    <li className={`page-item ${serverPagination.current_page === serverPagination.last_page ? 'disabled' : ''}`}>
                      <a 
                        className="page-link" 
                        href="#"
                        onClick={(e) => {
                          e.preventDefault();
                          if (serverPagination.current_page < serverPagination.last_page && onPageChange) {
                            onPageChange(serverPagination.current_page + 1);
                          }
                        }}
                        aria-label="Next"
                      >
                        <span aria-hidden="true">&raquo;</span>
                        <span className="sr-only">Next</span>
                      </a>
                    </li>
                  </ul>
                </nav>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default StyledTable;