import React, { useState, useEffect, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import axiosInstance from "../../../utils/axiosConfig";
import { FORMS_URL, FORMS_TYPE_URL } from "../../../utils/config";
import Pagination from "../../common/Pagination";
import "../activitylog/styles/ActivityLogControls.css";
import "./styles/CreateForm.css";
import "./styles/ViewForm.css";

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

const ViewForm = () => {
  const navigate = useNavigate();
  const [existingForms, setExistingForms] = useState([]);
  const [formTypes, setFormTypes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [viewMode, setViewMode] = useState("versions"); // "versions" | "flat"
  const [statusFilter, setStatusFilter] = useState("opened"); // "opened" | "archive"
  const [searchText, setSearchText] = useState("");
  const [filterTypeId, setFilterTypeId] = useState(""); // "" = all types
  const [filterVersion, setFilterVersion] = useState(""); // "" = all versions
  const [currentPage, setCurrentPage] = useState(1);
  const [entriesPerPage, setEntriesPerPage] = useState(DEFAULT_ENTRIES_PER_PAGE);

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

  // Fetch existing forms on component mount
  useEffect(() => {
    const fetchForms = async () => {
      try {
        setLoading(true);
        setError(null);
        const [formsRes, formTypesRes] = await Promise.all([
          axiosInstance.get(FORMS_URL),
          axiosInstance.get(FORMS_TYPE_URL),
        ]);

        const formsData = formsRes?.data?.data ?? formsRes?.data;
        const typesData = formTypesRes?.data?.data ?? formTypesRes?.data;
        setExistingForms(Array.isArray(formsData) ? formsData : []);
        setFormTypes(Array.isArray(typesData) ? typesData : []);
      } catch (err) {
        console.error("Error fetching forms:", err);
        const message = err.response?.data?.message || err.message;
        setError(message || "Failed to load forms. Please refresh the page.");
      } finally {
        setLoading(false);
      }
    };

    fetchForms();
  }, []);

  // Group forms by version family (root = form_parent_id || form_id); use backend version when present
  const formsByVersion = useMemo(() => {
    const raw = existingForms;
    if (!raw.length) return [];

    const rootId = (form) => form.form_parent_id ?? form.form_id;
    const byRoot = {};
    raw.forEach((form) => {
      const id = rootId(form);
      if (!byRoot[id]) byRoot[id] = [];
      byRoot[id].push(form);
    });

    const withVersion = [];
    Object.values(byRoot).forEach((group) => {
      const sorted = [...group].sort(
        (a, b) =>
          (Number(a.version) || 0) - (Number(b.version) || 0) ||
          new Date(a.created_date || 0) - new Date(b.created_date || 0) ||
          (a.form_id - b.form_id)
      );
      sorted.forEach((form, index) => {
        const backendVersion = form.version != null ? Number(form.version) : null;
        withVersion.push({
          ...form,
          _versionNumber: backendVersion ?? index + 1,
          _rootId: rootId(form),
        });
      });
    });

    return withVersion.sort(
      (a, b) =>
        String(a._rootId).localeCompare(String(b._rootId)) ||
        (a._versionNumber - b._versionNumber) ||
        new Date(a.created_date || 0) - new Date(b.created_date || 0)
    );
  }, [existingForms]);

  const handleViewForm = (formId) => {
    navigate(`/form-preview/${formId}`);
  };

  const getFormTypeName = (typeId) => {
    const formType = formTypes.find((t) => t.form_type_id === typeId);
    return formType ? formType.form_type : "Unknown";
  };

  const formatDate = (dateString) => {
    if (!dateString) return "Not set";
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  const baseDisplayForms = viewMode === "versions" ? formsByVersion : existingForms;

  // Unique version numbers for filter dropdown (from formsByVersion)
  const availableVersions = useMemo(() => {
    if (viewMode !== "versions" || !formsByVersion.length) return [];
    const versions = new Set(
      formsByVersion.map((f) => Number(f._versionNumber ?? f.version ?? 1))
    );
    return Array.from(versions).sort((a, b) => a - b);
  }, [viewMode, formsByVersion]);

  // Apply filters (status + search + form type + version)
  const displayForms = useMemo(() => {
    let list = baseDisplayForms;
    // Status filter: opened vs archive — only treat explicit true/1 as archived so open forms don't appear in Archive tab
    const isArchived = (form) => form.is_archived === true || form.is_archived === 1;
    if (statusFilter === "opened") {
      list = list.filter((form) => !isArchived(form));
    } else if (statusFilter === "archive") {
      list = list.filter((form) => isArchived(form));
    }
    const search = (searchText || "").trim().toLowerCase();
    if (search) {
      list = list.filter(
        (form) =>
          (form.title || "").toLowerCase().includes(search) ||
          (form.description || "").toLowerCase().includes(search) ||
          (getFormTypeName(form.form_type_id) || "").toLowerCase().includes(search)
      );
    }
    if (filterTypeId !== "") {
      const typeId = Number(filterTypeId);
      list = list.filter((form) => form.form_type_id === typeId);
    }
    if (filterVersion !== "") {
      const versionNum = Number(filterVersion);
      list = list.filter(
        (form) => Number(form._versionNumber ?? form.version ?? 1) === versionNum
      );
    }
    return list;
  }, [baseDisplayForms, statusFilter, searchText, filterTypeId, filterVersion, formTypes]);

  const totalEntries = displayForms.length;
  const totalPages = Math.max(1, Math.ceil(totalEntries / entriesPerPage));
  const paginatedForms = useMemo(() => {
    const start = (currentPage - 1) * entriesPerPage;
    return displayForms.slice(start, start + entriesPerPage);
  }, [displayForms, currentPage, entriesPerPage]);

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

  const hasActiveFilters = !!(searchText?.trim() || filterTypeId || filterVersion);
  const activeFilterCount = [searchText?.trim(), filterTypeId, filterVersion].filter(Boolean).length;
  const clearAllFilters = () => {
    setSearchText("");
    setFilterTypeId("");
    setFilterVersion("");
  };

  if (loading && !existingForms.length) {
    return (
      <div className="view-form-container">
        <div className="loading-state">
          <div className="loading-spinner"></div>
          <p>Loading forms...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="view-form-container">
      <div className="view-form-header">
        <h1 className="view-form-title">View Forms</h1>
        <button
          className="btn btn-secondary"
          onClick={() => navigate("/dashboard")}
        >
          Back to Dashboard
        </button>
      </div>

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

      {/* Forms List Table */}
      <div className="forms-list-section">
        {/* Opened / Archive filter tabs */}
        <div className="status-filter-tabs">
          <button
            type="button"
            className={`status-tab ${statusFilter === "opened" ? "active" : ""}`}
            onClick={() => setStatusFilter("opened")}
            aria-pressed={statusFilter === "opened"}
            aria-label="Show opened forms only"
          >
            Opened
          </button>
          <button
            type="button"
            className={`status-tab ${statusFilter === "archive" ? "active" : ""}`}
            onClick={() => setStatusFilter("archive")}
            aria-pressed={statusFilter === "archive"}
            aria-label="Show archived forms only"
          >
            Archive
          </button>
        </div>

        <div className="section-header-view">
          <h2 className="section-title-view">
            {viewMode === "versions" ? "Forms by Version" : "All Forms"}
          </h2>
          <div className="section-header-actions">
            <div className="view-mode-toggle">
              <button
                type="button"
                className={`toggle-btn ${viewMode === "versions" ? "active" : ""}`}
                onClick={() => setViewMode("versions")}
                title="Group by version family"
              >
                By version
              </button>
              <button
                type="button"
                className={`toggle-btn ${viewMode === "flat" ? "active" : ""}`}
                onClick={() => setViewMode("flat")}
                title="Show flat list"
              >
                All forms
              </button>
            </div>
            <span className="count-badge">{displayForms.length} Forms</span>
          </div>
        </div>

        {/* Filters */}
        <div className="forms-filter-wrapper">
          <div className="forms-filter-bar">
            <div className="filter-bar-header">
              <span className="filter-bar-title">Filter forms</span>
              {hasActiveFilters && (
                <span className="filter-result-summary">
                  Showing {displayForms.length} of {baseDisplayForms.length} forms
                </span>
              )}
            </div>
            <div className="filter-controls">
              <div className="filter-group filter-search-wrap">
                <label htmlFor="form-search" className="filter-label">
                  Search by name or type
                </label>
                <div className="filter-input-wrap">
                  <input
                    id="form-search"
                    type="text"
                    className="filter-input"
                    placeholder="e.g. Safety, Audit..."
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    aria-label="Search forms by name or type"
                  />
                  {searchText && (
                    <button
                      type="button"
                      className="filter-clear-input"
                      onClick={() => setSearchText("")}
                      aria-label="Clear search"
                      title="Clear search"
                    >
                      ×
                    </button>
                  )}
                </div>
              </div>
              <div className="filter-group">
                <label htmlFor="form-type-filter" className="filter-label">
                  Form type
                </label>
                <select
                  id="form-type-filter"
                  className="filter-select"
                  value={filterTypeId}
                  onChange={(e) => setFilterTypeId(e.target.value)}
                  aria-label="Filter by form type"
                >
                  <option value="">All form types</option>
                  {formTypes.map((t) => (
                    <option key={t.form_type_id} value={t.form_type_id}>
                      {t.form_type}
                    </option>
                  ))}
                </select>
              </div>
              {viewMode === "versions" && availableVersions.length > 0 && (
                <div className="filter-group">
                  <label htmlFor="form-version-filter" className="filter-label">
                    Version
                  </label>
                  <select
                    id="form-version-filter"
                    className="filter-select"
                    value={filterVersion}
                    onChange={(e) => setFilterVersion(e.target.value)}
                    aria-label="Filter by version"
                  >
                    <option value="">All versions</option>
                    {availableVersions.map((v) => (
                      <option key={v} value={v}>
                        v{v}
                      </option>
                    ))}
                  </select>
                </div>
              )}
              {hasActiveFilters && (
                <button
                  type="button"
                  className="btn-clear-filters"
                  onClick={clearAllFilters}
                  aria-label={`Clear ${activeFilterCount} filter${activeFilterCount > 1 ? "s" : ""}`}
                >
                  Clear {activeFilterCount > 1 ? `${activeFilterCount} filters` : "filters"}
                </button>
              )}
            </div>
          </div>
          {hasActiveFilters && (
            <div className="filter-chips">
              {searchText?.trim() && (
                <span className="filter-chip">
                  Search: &quot;{searchText.trim()}&quot;
                  <button type="button" onClick={() => setSearchText("")} aria-label="Remove search filter">×</button>
                </span>
              )}
              {filterTypeId && (
                <span className="filter-chip">
                  Type: {getFormTypeName(Number(filterTypeId))}
                  <button type="button" onClick={() => setFilterTypeId("")} aria-label="Remove type filter">×</button>
                </span>
              )}
              {filterVersion && (
                <span className="filter-chip">
                  Version: v{filterVersion}
                  <button type="button" onClick={() => setFilterVersion("")} aria-label="Remove version filter">×</button>
                </span>
              )}
            </div>
          )}
        </div>

        {displayForms.length > 0 && (
          <div className="activity-log-controls-bar view-forms-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>
        )}

        {displayForms.length === 0 ? (
          <div className="empty-state-view">
            <span className="empty-icon">📋</span>
            <p>
              {searchText || filterTypeId || filterVersion
                ? "No forms match your filters. Try different search, type, or version."
                : statusFilter === "archive"
                  ? "No archived forms."
                  : "No opened forms."}
            </p>
          </div>
        ) : (
          <>
            <div className="forms-table-wrapper">
              <table className="forms-table">
                <thead>
                  <tr>
                    <th>Form Name</th>
                    {viewMode === "versions" && <th>Version</th>}
                    <th>Type</th>
                    <th>Start Date</th>
                    <th>End Date</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {paginatedForms.map((form) => (
                  <tr key={form.form_id}>
                    <td className="form-name-cell" data-label="Form Name">
                      <div className="form-name-and-description">
                        <span className="form-title">{form.title}</span>
                        {form.description && (
                          <span className="form-description-preview" title={form.description}>
                            {form.description}
                          </span>
                        )}
                      </div>
                      {(form.is_archived === true || form.is_archived === 1) ? (
                        <span className="archived-badge" title="Parent form – view only, cannot be updated or added to audits">
                          Archived
                        </span>
                      ) : (
                        <span className="opened-badge" title="Active form – can be updated and added to audits">
                          Opened
                        </span>
                      )}
                      {viewMode === "flat" && form.version && (
                        <span className="version-badge">v{form.version}</span>
                      )}
                    </td>
                    {viewMode === "versions" && (
                      <td data-label="Version">
                        <span className="version-badge version-col">
                          v{Number(form._versionNumber ?? form.version ?? 1)}
                        </span>
                      </td>
                    )}
                    <td data-label="Type">
                      <span className="type-badge">
                        {form.form_type || getFormTypeName(form.form_type_id)}
                      </span>
                    </td>
                    <td data-label="Start Date">{formatDate(form.created_date)}</td>
                    <td data-label="End Date">{formatDate(form.end_date)}</td>
                    <td className="actions-cell" data-label="Actions">
                      <button
                        className="btn-action btn-view"
                        onClick={() => handleViewForm(form.form_id)}
                        title={
                          form._versionNumber
                            ? `View v${form._versionNumber}`
                            : "View Form"
                        }
                      >
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          xmlns="http://www.w3.org/2000/svg"
                        >
                          <path
                            d="M1 12C1 12 5 4 12 4C19 4 23 12 23 12C23 12 19 20 12 20C5 20 1 12 1 12Z"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                          <circle
                            cx="12"
                            cy="12"
                            r="3"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                        </svg>
                        View
                      </button>
                    </td>
                  </tr>
                  ))}
                </tbody>
              </table>
            </div>

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

export default ViewForm;
