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

const OBS_TIME_OPTIONS = [
  { value: "all", label: "All time" },
  { value: "7d", label: "Last 7 days" },
  { value: "30d", label: "Last 30 days" },
  { value: "90d", label: "Last 90 days" },
];

const ObservationsOpenClosedPage = () => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const periodFromUrl = searchParams.get("period") || "all";
  const [timePeriod, setTimePeriod] = useState(() =>
    OBS_TIME_OPTIONS.some((o) => o.value === periodFromUrl) ? periodFromUrl : "all"
  );
  const [openList, setOpenList] = useState([]);
  const [closedList, setClosedList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchOpen, setSearchOpen] = useState("");
  const [searchClosed, setSearchClosed] = useState("");

  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);
      const params = timePeriod && timePeriod !== "all" ? { params: { period: timePeriod } } : {};
      const response = await axiosInstance.get(DASHBOARD_OBSERVATIONS_OPEN_CLOSED_LIST_URL, params);
      if (response.data?.success && response.data?.data) {
        setOpenList(response.data.data.open || []);
        setClosedList(response.data.data.closed || []);
      } else {
        setOpenList([]);
        setClosedList([]);
      }
    } catch (err) {
      console.error("Error fetching observations:", err);
      setError("Failed to load observations. Please try again.");
      setOpenList([]);
      setClosedList([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const urlPeriod = searchParams.get("period") || "all";
    if (OBS_TIME_OPTIONS.some((o) => o.value === urlPeriod)) setTimePeriod(urlPeriod);
  }, [searchParams]);

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

  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 filterList = (list, query) => {
    const q = (query || "").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 filteredOpen = filterList(openList, searchOpen);
  const filteredClosed = filterList(closedList, searchClosed);

  const ObservationRow = ({ row, status }) => (
    <tr>
      <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>
        <span className={`obs-oc-badge obs-oc-badge-${status}`}>{status}</span>
      </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>
  );

  return (
    <div className="audit-status-container obs-oc-page">
      <div className="audit-status-header">
        <h1 className="audit-status-title">Observations: Open vs Closed</h1>
        <div className="audit-status-actions obs-oc-actions">
          <div className="obs-oc-time-filter">
            <label htmlFor="obs-oc-page-period" className="obs-oc-time-filter-label">Time period</label>
            <select
              id="obs-oc-page-period"
              value={timePeriod}
              onChange={(e) => {
                const value = e.target.value;
                setTimePeriod(value);
                if (value === "all") {
                  setSearchParams({});
                } else {
                  setSearchParams({ period: value });
                }
              }}
              className="obs-oc-time-select"
              aria-label="Filter observations by time period"
              disabled={loading}
            >
              {OBS_TIME_OPTIONS.map(({ value, label }) => (
                <option key={value} value={value}>{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>

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

      {loading ? (
        <div className="audit-status-loading">
          <p>Loading observations…</p>
        </div>
      ) : (
        <>
          <section className="obs-oc-section">
            <h2 className="obs-oc-section-title">
              Open observations <span className="obs-oc-count">({filteredOpen.length})</span>
            </h2>
            <div className="audit-status-filters">
              <input
                type="text"
                className="audit-status-search-input"
                placeholder="Search open observations…"
                value={searchOpen}
                onChange={(e) => setSearchOpen(e.target.value)}
              />
            </div>
            <div className="obs-oc-table-wrap">
              {filteredOpen.length === 0 ? (
                <p className="obs-oc-empty">No open observations.</p>
              ) : (
                <table className="obs-oc-table">
                  <thead>
                    <tr>
                      <th>Submission</th>
                      <th>Audit</th>
                      <th>Form</th>
                      <th>Submitter</th>
                      <th>Date</th>
                      <th>Status</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredOpen.map((row) => (
                      <ObservationRow key={`open-${row.submission_id}`} row={row} status="Open" />
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </section>

          <section className="obs-oc-section">
            <h2 className="obs-oc-section-title">
              Closed observations <span className="obs-oc-count">({filteredClosed.length})</span>
            </h2>
            <div className="audit-status-filters">
              <input
                type="text"
                className="audit-status-search-input"
                placeholder="Search closed observations…"
                value={searchClosed}
                onChange={(e) => setSearchClosed(e.target.value)}
              />
            </div>
            <div className="obs-oc-table-wrap">
              {filteredClosed.length === 0 ? (
                <p className="obs-oc-empty">No closed observations.</p>
              ) : (
                <table className="obs-oc-table">
                  <thead>
                    <tr>
                      <th>Submission</th>
                      <th>Audit</th>
                      <th>Form</th>
                      <th>Submitter</th>
                      <th>Date</th>
                      <th>Status</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredClosed.map((row) => (
                      <ObservationRow key={`closed-${row.submission_id}`} row={row} status="Closed" />
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </section>
        </>
      )}
    </div>
  );
};

export default ObservationsOpenClosedPage;
