import React, { useState, useMemo, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import Button from "../../../common/Button";
import Pagination from "../../../common/Pagination";
import "../../user-management/styles/AllUsersTable.css";
import "../../activitylog/styles/ActivityLogControls.css";
import "../styles/QuestionsTable.css";

const ENTRIES_PER_PAGE_OPTIONS = [10, 25, 50, 100];
const DEFAULT_ENTRIES_PER_PAGE = 10;

const QuestionsTable = ({ questions, questionTypes = [], loading, onDelete }) => {
  const navigate = useNavigate();
  const [currentPage, setCurrentPage] = useState(1);
  const [entriesPerPage, setEntriesPerPage] = useState(DEFAULT_ENTRIES_PER_PAGE);

  const typeIdToName = useMemo(() => {
    const map = {};
    (Array.isArray(questionTypes) ? questionTypes : []).forEach((t) => {
      const id = t.question_type_id != null ? t.question_type_id : t.id;
      const name = t.question_type || t.type_name || t.name || `Type ${id}`;
      if (id != null) map[String(id)] = name;
    });
    return map;
  }, [questionTypes]);

  const getTypeName = (questionTypeId) => {
    if (questionTypeId == null || questionTypeId === "") return "—";
    return typeIdToName[String(questionTypeId)] ?? String(questionTypeId);
  };

  const handleEntriesPerPageChange = (e) => {
    setEntriesPerPage(Number(e.target.value));
    setCurrentPage(1);
  };

  const list = useMemo(() => (Array.isArray(questions) ? questions : []), [questions]);
  const totalEntries = list.length;
  const totalPages = Math.max(1, Math.ceil(totalEntries / entriesPerPage));
  const paginatedQuestions = useMemo(() => {
    const start = (currentPage - 1) * entriesPerPage;
    return list.slice(start, start + entriesPerPage);
  }, [list, currentPage, entriesPerPage]);

  useEffect(() => {
    if (currentPage > totalPages) setCurrentPage(1);
  }, [totalPages, currentPage]);

  return (
    <div className="tab-content active" id="allTab">
      <div className="table-section">
        <div className="table-header">
          <h2 className="table-header-title">All Question Details</h2>
        </div>

        {!loading && (
          <div className="activity-log-controls-bar questions-table-controls">
            <div className="activity-log-controls-left">
              <div className="show-entries">
                <label>Show</label>
                <select
                  className="entries-select"
                  value={entriesPerPage}
                  onChange={handleEntriesPerPageChange}
                  aria-label="Entries per page"
                >
                  {ENTRIES_PER_PAGE_OPTIONS.map((n) => (
                    <option key={n} value={n}>{n}</option>
                  ))}
                </select>
                <span>entries</span>
              </div>
            </div>
          </div>
        )}

        {/* Desktop: table */}
        <div className="table-container questions-table-desktop">
          {loading ? (
            <div className="questions-loading-state">Loading questions...</div>
          ) : (
            <table className="user-table">
              <thead>
                <tr>
                  <th className="table-center">SI No</th>
                  <th className="table-center">Question ID</th>
                  <th className="table-center">Question</th>
                  <th className="table-center">Type</th>
                  <th className="table-center">Action</th>
                </tr>
              </thead>
              <tbody>
                {!paginatedQuestions.length ? (
                  <tr>
                    <td colSpan="5" className="all-users-table-container">
                      No questions found
                    </td>
                  </tr>
                ) : (
                  paginatedQuestions.map((q, index) => (
                    <tr key={q.question_id || q.id}>
                      <td className="table-center">{(currentPage - 1) * entriesPerPage + index + 1}</td>
                      <td className="table-center">{q.question_id || q.id}</td>
                      <td className="table-center">{q.question || "-"}</td>
                      <td className="table-center">{getTypeName(q.question_type_id)}</td>
                      <td className="table-center">
                        <div className="questions-action-buttons">
                          <Button
                            variant="update"
                            aria-label="Edit question"
                            onClick={() => navigate(`/question-profile/${q.question_id || q.id}`)}
                            icon={
                              <svg
                                viewBox="0 0 24 24"
                                fill="none"
                                xmlns="http://www.w3.org/2000/svg"
                                width="16"
                                height="16"
                              >
                                <path
                                  d="M11 4H4C3.46957 4 2.96086 4.21071 2.58579 4.58579C2.21071 4.96086 2 5.46957 2 6V20C2 20.5304 2.21071 21.0391 2.58579 21.4142C2.96086 21.7893 3.46957 22 4 22H18C18.5304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20V13"
                                  stroke="currentColor"
                                  strokeWidth="2"
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                />
                                <path
                                  d="M18.5 2.5C18.8978 2.10217 19.4374 1.87868 20 1.87868C20.5626 1.87868 21.1022 2.10217 21.5 2.5C21.8978 2.89782 22.1213 3.43739 22.1213 4C22.1213 4.56261 21.8978 5.10217 21.5 5.5L12 15L8 16L9 12L18.5 2.5Z"
                                  stroke="currentColor"
                                  strokeWidth="2"
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                />
                              </svg>
                            }
                          >
                            Edit
                          </Button>
                          <Button
                            variant="delete"
                            aria-label="Delete question"
                            onClick={() => onDelete(q.question_id || q.id)}
                            icon={
                              <svg
                                viewBox="0 0 24 24"
                                fill="none"
                                xmlns="http://www.w3.org/2000/svg"
                                width="16"
                                height="16"
                              >
                                <path
                                  d="M3 6H5H21"
                                  stroke="currentColor"
                                  strokeWidth="2"
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                />
                                <path
                                  d="M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6H19Z"
                                  stroke="currentColor"
                                  strokeWidth="2"
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                />
                              </svg>
                            }
                          >
                            Delete
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          )}
        </div>

        {/* Mobile: card list */}
        <div className="questions-mobile-cards">
          {loading ? (
            <div className="questions-loading-state">Loading questions...</div>
          ) : !paginatedQuestions.length ? (
            <div className="questions-empty-state">No questions found</div>
          ) : (
            <ul className="questions-card-list">
              {paginatedQuestions.map((q, index) => (
                <li key={q.question_id || q.id} className="questions-card">
                  <div className="questions-card-body">
                    <span className="questions-card-badge">#{q.question_id || q.id}</span>
                    <p className="questions-card-text">{q.question || "—"}</p>
                    <div className="questions-card-meta">
                      <span>Type: {getTypeName(q.question_type_id)}</span>
                    </div>
                  </div>
                  <div className="questions-action-buttons">
                    <Button
                      variant="update"
                      aria-label="Edit question"
                      onClick={() => navigate(`/question-profile/${q.question_id || q.id}`)}
                      icon={
                        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="18" height="18">
                          <path d="M11 4H4C3.46957 4 2.96086 4.21071 2.58579 4.58579C2.21071 4.96086 2 5.46957 2 6V20C2 20.5304 2.21071 21.0391 2.58579 21.4142C2.96086 21.7893 3.46957 22 4 22H18C18.5304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20V13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                          <path d="M18.5 2.5C18.8978 2.10217 19.4374 1.87868 20 1.87868C20.5626 1.87868 21.1022 2.10217 21.5 2.5C21.8978 2.89782 22.1213 3.43739 22.1213 4C22.1213 4.56261 21.8978 5.10217 21.5 5.5L12 15L8 16L9 12L18.5 2.5Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                      }
                    >
                      Edit
                    </Button>
                    <Button
                      variant="delete"
                      aria-label="Delete question"
                      onClick={() => onDelete(q.question_id || q.id)}
                      icon={
                        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="18" height="18">
                          <path d="M3 6H5H21" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                          <path d="M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6H19Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                      }
                    >
                      Delete
                    </Button>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>

        {!loading && (
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            totalEntries={totalEntries}
            entriesPerPage={entriesPerPage}
            onPageChange={setCurrentPage}
          />
        )}
      </div>
    </div>
  );
};

export default QuestionsTable;
