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

const TYPES = [
  { value: "SIO", label: "SIO" },
  { value: "OIO", label: "OIO" },
  { value: "CA", label: "CA" },
  { value: "SIO_CLOSED", label: "SIO (closed)" },
];

const SioOioCaListPage = () => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const typeFromUrl = (searchParams.get("type") || "SIO").toUpperCase();
  const effectiveType = TYPES.some((t) => t.value === typeFromUrl) ? typeFromUrl : "SIO";
  const [type, setType] = useState(effectiveType);
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchQuery, setSearchQuery] = useState("");

  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await axiosInstance.get(DASHBOARD_SIO_OIO_CA_LIST_URL, {
        params: { type },
      });
      if (response.data?.success && Array.isArray(response.data?.data)) {
        setList(response.data.data);
      } else {
        setList([]);
      }
    } catch (err) {
      console.error("Error fetching SIO/OIO/CA list:", err);
      setError("Failed to load list. Please try again.");
      setList([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const urlType = (searchParams.get("type") || "SIO").toUpperCase();
    if (TYPES.some((t) => t.value === urlType)) setType(urlType);
  }, [searchParams]);

  useEffect(() => {
    fetchData();
  }, [type]);

  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 filteredList = (() => {
    const q = searchQuery.trim().toLowerCase();
    if (!q) return list;
    return list.filter(
      (row) =>
        (row.audit_name && String(row.audit_name).toLowerCase().includes(q)) ||
        (row.form_title && String(row.form_title).toLowerCase().includes(q)) ||
        (row.submitter_name && String(row.submitter_name).toLowerCase().includes(q)) ||
        (row.submission_id && String(row.submission_id).includes(q)) ||
        (row.audit_id && String(row.audit_id).includes(q))
    );
  })();

  const typeLabel = TYPES.find((t) => t.value === type)?.label || type;

  return (
    <div className="audit-status-container sio-oio-ca-list-page">
      <div className="audit-status-header">
        <h1 className="audit-status-title">SIO / OIO / CA – Audit details</h1>
        <div className="audit-status-actions obs-oc-actions">
          <div className="sio-oio-ca-type-filter">
            <label htmlFor="sio-oio-ca-type" className="obs-oc-time-filter-label">Type</label>
            <select
              id="sio-oio-ca-type"
              value={type}
              onChange={(e) => {
                const value = e.target.value;
                setType(value);
                setSearchParams({ type: value });
              }}
              className="obs-oc-time-select"
              aria-label="Filter by type"
              disabled={loading}
            >
              {TYPES.map((t) => (
                <option key={t.value} value={t.value}>{t.label}</option>
              ))}
            </select>
          </div>
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate("/dashboard")}
          >
            Back to Dashboard
          </button>
          <button
            type="button"
            className="btn btn-primary"
            onClick={fetchData}
            disabled={loading}
          >
            {loading ? "Loading…" : "Refresh"}
          </button>
        </div>
      </div>

      <p className="sio-oio-ca-intro">
        Submissions and audits for type: <strong>{typeLabel}</strong>. Click View to open the submission, or Audit to open the audit.
      </p>

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

      {loading ? (
        <div className="audit-status-loading">
          <p>Loading…</p>
        </div>
      ) : (
        <section className="obs-oc-section">
          <h2 className="obs-oc-section-title">
            {typeLabel} <span className="obs-oc-count">({filteredList.length})</span>
          </h2>
          <div className="audit-status-filters">
            <input
              type="text"
              className="audit-status-search-input"
              placeholder="Search by audit, form, submitter, ID…"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
          <div className="obs-oc-table-wrap">
            {filteredList.length === 0 ? (
              <p className="obs-oc-empty">No submissions for this type.</p>
            ) : (
              <table className="obs-oc-table">
                <thead>
                  <tr>
                    <th>Submission</th>
                    <th>Audit</th>
                    <th>Form</th>
                    <th>Submitter</th>
                    <th>Date</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredList.map((row) => (
                    <tr key={row.submission_id}>
                      <td>#{row.submission_id}</td>
                      <td>{row.audit_name || "—"}</td>
                      <td>{row.form_title || "—"}</td>
                      <td>{row.submitter_name || "—"}</td>
                      <td>{formatDate(row.created_at)}</td>
                      <td>
                        <button
                          type="button"
                          className="btn btn-sm btn-forms"
                          onClick={() => navigate(`/view-submission/${row.submission_id}`)}
                        >
                          View
                        </button>
                        <button
                          type="button"
                          className="btn btn-sm btn-secondary"
                          style={{ marginLeft: "0.35rem" }}
                          onClick={() => navigate(`/audit/${row.audit_id}/forms`)}
                        >
                          Audit
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </section>
      )}
    </div>
  );
};

export default SioOioCaListPage;
