import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import axiosInstance from "../../../../utils/axiosConfig";
import { DASHBOARD_RPN_AUDITS_BY_VALUE_URL } from "../../../../utils/config";
import "../../audit-management/styles/AuditStatus.css";

const VALID_RPN_VALUES = [1, 2, 4, 8, 16, 32, 64, 128];
const VIEW_LIST = "list";
const VIEW_CARD = "card";

const RpnAuditListPage = () => {
  const navigate = useNavigate();
  const { rpnValue } = useParams();
  const rpn = rpnValue != null ? parseInt(rpnValue, 10) : null;
  const [audits, setAudits] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [viewMode, setViewMode] = useState(VIEW_CARD);

  const isValidRpn = Number.isInteger(rpn) && VALID_RPN_VALUES.includes(rpn);

  const fetchAudits = async () => {
    if (!isValidRpn) return;
    try {
      setLoading(true);
      setError(null);
      const response = await axiosInstance.get(
        `${DASHBOARD_RPN_AUDITS_BY_VALUE_URL}/${rpn}`
      );
      if (response.data?.success && Array.isArray(response.data.data)) {
        setAudits(response.data.data);
      } else {
        setAudits([]);
      }
    } catch (err) {
      console.error("Error fetching audits by RPN:", err);
      setError("Failed to load audits. Please try again.");
      setAudits([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (isValidRpn) {
      fetchAudits();
    } else {
      setLoading(false);
    }
  }, [rpn, isValidRpn]);

  const formatDate = (dateStr) => {
    if (!dateStr) return "—";
    const d = new Date(dateStr);
    return d.toLocaleDateString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const getStatusBadgeClass = (statusName) => {
    if (!statusName) return "audit-status-badge audit-status-unknown";
    const normalized = String(statusName).trim().toLowerCase();
    if (normalized === "open") return "audit-status-badge audit-status-open";
    if (normalized === "in progress") return "audit-status-badge audit-status-in-progress";
    if (normalized === "closed") return "audit-status-badge audit-status-closed";
    return "audit-status-badge audit-status-unknown";
  };

  const filteredAudits = audits.filter((audit) => {
    const query = searchQuery.trim().toLowerCase();
    return (
      !query ||
      (audit.audit_name && String(audit.audit_name).toLowerCase().includes(query)) ||
      (audit.auditor_name && String(audit.auditor_name).toLowerCase().includes(query)) ||
      (audit.location_name && String(audit.location_name).toLowerCase().includes(query)) ||
      (audit.audit_id && String(audit.audit_id).includes(query))
    );
  });

  const sortedAudits = [...filteredAudits].sort((a, b) => {
    const dateA = a.created_at ? new Date(a.created_at).getTime() : 0;
    const dateB = b.created_at ? new Date(b.created_at).getTime() : 0;
    return dateB - dateA;
  });

  if (!isValidRpn) {
    return (
      <div className="audit-status-container">
        <div className="audit-status-header">
          <h1 className="audit-status-title">Invalid RPN value</h1>
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate("/dashboard")}
          >
            Back to Dashboard
          </button>
        </div>
        <p className="critical-findings-intro">
          RPN must be one of: 1, 2, 4, 8, 16, 32, 64, 128.
        </p>
      </div>
    );
  }

  return (
    <div className="audit-status-container">
      <div className="audit-status-header">
        <h1 className="audit-status-title">Audits with RPN = {rpn}</h1>
        <div className="audit-status-actions">
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate("/dashboard")}
          >
            Back to Dashboard
          </button>
          <button
            type="button"
            className="btn btn-primary"
            onClick={fetchAudits}
            disabled={loading}
          >
            {loading ? "Loading…" : "Refresh"}
          </button>
        </div>
      </div>

      {error && (
        <div className="audit-status-error">{error}</div>
      )}

      <div className="audit-status-filters">
        <div className="audit-status-search" style={{ flex: 1 }}>
          <input
            type="text"
            className="audit-status-search-input"
            placeholder="Search by audit name, auditor, location or ID…"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
        <div className="audit-status-view-toggle" title="Switch view">
          <button
            type="button"
            className={`audit-status-view-btn ${viewMode === VIEW_LIST ? "active" : ""}`}
            onClick={() => setViewMode(VIEW_LIST)}
            title="List view"
            aria-label="List view"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="8" y1="6" x2="21" y2="6" />
              <line x1="8" y1="12" x2="21" y2="12" />
              <line x1="8" y1="18" x2="21" y2="18" />
              <line x1="3" y1="6" x2="3.01" y2="6" />
              <line x1="3" y1="12" x2="3.01" y2="12" />
              <line x1="3" y1="18" x2="3.01" y2="18" />
            </svg>
            List
          </button>
          <button
            type="button"
            className={`audit-status-view-btn ${viewMode === VIEW_CARD ? "active" : ""}`}
            onClick={() => setViewMode(VIEW_CARD)}
            title="Card view"
            aria-label="Card view"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="7" height="7" rx="1" />
              <rect x="14" y="3" width="7" height="7" rx="1" />
              <rect x="3" y="14" width="7" height="7" rx="1" />
              <rect x="14" y="14" width="7" height="7" rx="1" />
            </svg>
            Card
          </button>
        </div>
      </div>
      {console.log("filteredAudits", filteredAudits)}

      {loading ? (
        <div className="audit-status-loading">
          <p>Loading audits…</p>
        </div>
      ) : (
        <div className="audit-status-list-wrap">
          {filteredAudits.length === 0 ? (
            <div className="audit-status-empty">
              <p>
                {audits.length === 0
                  ? `No audits with RPN = ${rpn} found.`
                  : "No audits match your search."}
              </p>
              <button
                type="button"
                className="btn btn-secondary"
                onClick={() => navigate("/dashboard")}
              >
                Back to Dashboard
              </button>
            </div>
          ) : viewMode === VIEW_LIST ? (
            <div className="audit-status-table-wrap">
              <table className="audit-status-table">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>ID</th>
                    <th>Status</th>
                    <th>Auditor</th>
                    <th>Location</th>
                    <th>Created</th>
                    <th>Observed</th>
                    <th className="audit-status-table-actions">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {sortedAudits.map((audit) => (
                    <tr key={audit.audit_id}>
                      <td className="audit-status-table-name">{audit.audit_name || "—"}</td>
                      <td>#{audit.audit_id}</td>
                      <td>
                        <span className={getStatusBadgeClass(audit.audit_status_name)}>
                          {audit.audit_status_name || "N/A"}
                        </span>
                      </td>
                      <td>{audit.auditor_name || "—"}</td>
                      <td>{audit.location_name || "—"}</td>
                      <td>{formatDate(audit.created_at)}</td>
                      <td>{formatDate(audit.observed_at)}</td>
                      <td className="audit-status-table-actions">
                        <div className="audit-status-row-actions">
                          <button
                            type="button"
                            className="btn btn-sm btn-forms"
                            onClick={() => navigate(`/audit/${audit.audit_id}/forms`)}
                            title="View observations"
                          >
                            View observations
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="audit-status-cards">
              {sortedAudits.map((audit) => (
                <article key={audit.audit_id} className="audit-status-card">
                  <div className="audit-status-card-header">
                    <h3 className="audit-status-card-title">
                      {audit.audit_name || "—"}
                    </h3>
                    <span className="audit-status-card-id">#{audit.audit_id}</span>
                    <span className={getStatusBadgeClass(audit.audit_status_name)}>
                      {audit.audit_status_name || "N/A"}
                    </span>
                  </div>
                  <div className="audit-status-card-meta">
                    <div className="audit-status-card-row">
                      <span className="audit-status-card-label">Auditor</span>
                      <span className="audit-status-card-value">
                        {audit.auditor_name || "—"}
                      </span>
                    </div>
                    <div className="audit-status-card-row">
                      <span className="audit-status-card-label">Location</span>
                      <span className="audit-status-card-value">
                        {audit.location_name || "—"}
                      </span>
                    </div>
                    <div className="audit-status-card-row">
                      <span className="audit-status-card-label">Created</span>
                      <span className="audit-status-card-value">
                        {formatDate(audit.created_at)}
                      </span>
                    </div>
                    <div className="audit-status-card-row">
                      <span className="audit-status-card-label">Observed</span>
                      <span className="audit-status-card-value">
                        {formatDate(audit.observed_at)}
                      </span>
                    </div>
                  </div>
                  <div className="audit-status-card-actions">
                    <button
                      type="button"
                      className="btn btn-sm btn-forms"
                      onClick={() => navigate(`/audit/${audit.audit_id}/forms`)}
                      title="View forms and submissions in this audit"
                    >
                      View observations
                    </button>
                  </div>
                </article>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default RpnAuditListPage;
