import { useCallback, useEffect, useMemo, useState } from 'react';
import { deleteOracFormDetail, fetchOracFormDetailsList } from '../../api.js';
import { formAllowedForNewUse, isTruthyFlag } from '../../utils/oracFormDetails.js';
import './admin-shared.css';
import './AdminFormBuilderPage.css';
import './AdminFormsCompositionPage.css';
import './AdminFormsListPage.css';

function ViewEyeIcon() {
  return (
    <svg className="admin-forms-view-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden>
      <path
        d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2" />
    </svg>
  );
}

function formatShortDate(val) {
  if (val == null || val === '') return 'Not set';
  try {
    const d = new Date(val);
    if (Number.isNaN(d.getTime())) return 'Not set';
    return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
  } catch {
    return 'Not set';
  }
}

function formSubtitle(row) {
  return `ID #${row.form_id}`;
}

function statusBadge(row) {
  if (isTruthyFlag(row.is_archived)) {
    return { className: 'admin-forms-view__badge--archived', label: 'Archived' };
  }
  if (isTruthyFlag(row.has_child_version)) {
    return { className: 'admin-forms-view__badge--superseded', label: 'Superseded' };
  }
  return { className: 'admin-forms-view__badge--opened', label: 'Active' };
}

const MODE_COPY = {
  list: {
    pageTitle: 'View Forms',
    sectionHeading: 'Forms by version'
  },
  edit: {
    pageTitle: 'Edit form',
    sectionHeading: 'Choose a form'
  }
};

/**
 * @param {{ mode?: 'list' | 'edit', onOpenForm: (formId: number | string) => void, onBackToDashboard?: () => void }} props
 */
function AdminFormsListPage({ mode = 'list', onOpenForm, onBackToDashboard }) {
  const [forms, setForms] = useState([]);
  /** opened = not archived; archive = archived rows only */
  const [vaultTab, setVaultTab] = useState('opened');
  /** by_version = grouped families; all = flat table */
  const [layoutMode, setLayoutMode] = useState('by_version');
  const [searchQuery, setSearchQuery] = useState('');
  const [versionFilter, setVersionFilter] = useState('all');
  const [pageSize, setPageSize] = useState(10);
  const [pageIndex, setPageIndex] = useState(0);

  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');

  const copy = MODE_COPY[mode] || MODE_COPY.list;
  const openLabel = mode === 'edit' ? 'Edit' : 'View';

  const loadForms = useCallback(async () => {
    const f = await fetchOracFormDetailsList({ with_version: true }).catch(() => []);
    setForms(Array.isArray(f) ? f : []);
  }, []);

  useEffect(() => {
    setLoading(true);
    setError('');
    loadForms()
      .catch((e) => setError(e.message || 'Failed to load forms'))
      .finally(() => setLoading(false));
  }, [loadForms]);

  const versionOptions = useMemo(() => {
    const s = new Set();
    for (const f of forms) {
      if (f.version != null && f.version !== '') s.add(String(Number(f.version)));
    }
    return [...s].sort((a, b) => Number(a) - Number(b));
  }, [forms]);

  const filteredRows = useMemo(() => {
    let rows = Array.isArray(forms) ? [...forms] : [];
    if (vaultTab === 'opened') {
      rows = rows.filter((f) => !isTruthyFlag(f.is_archived));
    } else {
      rows = rows.filter((f) => isTruthyFlag(f.is_archived));
    }

    const q = searchQuery.trim().toLowerCase();
    if (q) {
      rows = rows.filter((f) => {
        const title = String(f.title || '').toLowerCase();
        const desc = String(f.description || '').toLowerCase();
        const id = String(f.form_id);
        return title.includes(q) || desc.includes(q) || id.includes(q);
      });
    }

    if (versionFilter !== 'all') {
      const vn = Number(versionFilter);
      rows = rows.filter((f) => Number(f.version) === vn);
    }

    return rows;
  }, [forms, vaultTab, searchQuery, versionFilter]);

  useEffect(() => {
    setPageIndex(0);
  }, [vaultTab, layoutMode, searchQuery, versionFilter, pageSize]);

  const totalFiltered = filteredRows.length;
  const pageCount = Math.max(1, Math.ceil(totalFiltered / pageSize));
  const safePage = Math.min(pageIndex, pageCount - 1);

  useEffect(() => {
    if (pageIndex !== safePage) setPageIndex(safePage);
  }, [pageIndex, safePage]);

  const paginatedRows = useMemo(() => {
    const start = safePage * pageSize;
    return filteredRows.slice(start, start + pageSize);
  }, [filteredRows, safePage, pageSize]);

  const groupedPage = useMemo(() => {
    const rows = paginatedRows;
    const byRoot = new Map();
    for (const f of rows) {
      const root =
        f.version_root_id != null && f.version_root_id !== ''
          ? Number(f.version_root_id)
          : f.form_parent_id != null && f.form_parent_id !== ''
            ? Number(f.form_parent_id)
            : Number(f.form_id);
      const key = Number.isFinite(root) ? root : Number(f.form_id);
      if (!byRoot.has(key)) byRoot.set(key, []);
      byRoot.get(key).push(f);
    }
    const sortedRoots = [...byRoot.keys()].sort((a, b) => a - b);
    return sortedRoots.map((rootId) => {
      const list = [...(byRoot.get(rootId) || [])].sort((a, b) => {
        const va = Number(a.version) || 0;
        const vb = Number(b.version) || 0;
        if (va !== vb) return va - vb;
        return Number(a.form_id) - Number(b.form_id);
      });
      return { rootId, rows: list };
    });
  }, [paginatedRows]);

  const showMsg = (text, isErr = false) => {
    setMessage(text);
    setError(isErr ? text : '');
    if (!isErr) {
      window.setTimeout(() => setMessage(''), 4000);
    }
  };

  const handleDelete = async (row) => {
    if (!window.confirm(`Delete form "${row.title || row.form_id}"?`)) return;
    setBusy(true);
    setError('');
    try {
      await deleteOracFormDetail(row.form_id);
      await loadForms();
      showMsg('Form deleted');
    } catch (err) {
      setError(err.message || 'Could not delete form');
    } finally {
      setBusy(false);
    }
  };

  const renderRow = (row, rowKey) => {
    const ver = row.version != null && row.version !== '' ? `v${row.version}` : '—';
    const badge = statusBadge(row);
    const canUse = formAllowedForNewUse(row);

    return (
      <tr key={rowKey ?? row.form_id}>
        <td className="admin-forms-view__name-cell">
          <div className="admin-forms-view__name-title">
            <span>{row.title || `Form ${row.form_id}`}</span>
            <span className={`admin-forms-view__badge ${badge.className}`}>{badge.label}</span>
          </div>
          <span className="admin-forms-view__name-sub">{formSubtitle(row)}</span>
        </td>
        <td>
          <span className="admin-forms-view__pill">{ver}</span>
        </td>
        <td>{formatShortDate(row.created_date)}</td>
        <td>Not set</td>
        <td className="admin-forms-view__actions">
          <button
            type="button"
            className="admin-forms-view__btn-view"
            onClick={() => onOpenForm(row.form_id)}
            disabled={busy}
            title={canUse ? undefined : 'Older or archived row — open to inspect or edit'}
          >
            <ViewEyeIcon />
            {openLabel}
          </button>
          {mode === 'list' && (
            <button
              type="button"
              className="admin-forms-view__btn-delete"
              onClick={() => handleDelete(row)}
              disabled={busy}
            >
              Delete
            </button>
          )}
        </td>
      </tr>
    );
  };

  const tableHead = (
    <thead>
      <tr>
        <th>Form name</th>
        <th>Version</th>
        <th>Start date</th>
        <th>End date</th>
        <th>Actions</th>
      </tr>
    </thead>
  );

  if (loading) {
    return (
      <main className="dashboard-main admin-dashboard admin-dashboard-v2 admin-form-builder admin-orac-page admin-forms-page">
        <div className="admin-forms-view">
          <p style={{ textAlign: 'center', padding: 48, color: 'var(--theme-gray-500)' }}>Loading…</p>
        </div>
      </main>
    );
  }

  return (
    <main className="dashboard-main admin-dashboard admin-dashboard-v2 admin-form-builder admin-orac-page admin-forms-page">
      <div className="admin-forms-view">
        <div className="admin-forms-view__top">
          <div className="admin-forms-view__title-wrap">
            <span className="admin-forms-view__accent" aria-hidden />
            <h1 className="admin-forms-view__title">{copy.pageTitle}</h1>
          </div>
          {typeof onBackToDashboard === 'function' && (
            <button type="button" className="admin-forms-view__back" onClick={onBackToDashboard}>
              Back to Dashboard
            </button>
          )}
        </div>

        <div className="admin-forms-view__tabs" role="tablist" aria-label="Form vault">
          <button
            type="button"
            role="tab"
            aria-selected={vaultTab === 'opened'}
            className={`admin-forms-view__tab ${vaultTab === 'opened' ? 'admin-forms-view__tab--active' : ''}`}
            onClick={() => setVaultTab('opened')}
          >
            Opened
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={vaultTab === 'archive'}
            className={`admin-forms-view__tab ${vaultTab === 'archive' ? 'admin-forms-view__tab--active' : ''}`}
            onClick={() => setVaultTab('archive')}
          >
            Archive
          </button>
        </div>

        <div className="admin-forms-view__toolbar">
          <div className="admin-forms-view__toolbar-left">
            <h2 className="admin-forms-view__section-title">{copy.sectionHeading}</h2>
            <span className="admin-forms-view__count-pill">
              {totalFiltered} Form{totalFiltered === 1 ? '' : 's'}
            </span>
          </div>
          <div className="admin-forms-view__seg" role="group" aria-label="Layout">
            <button
              type="button"
              className={`admin-forms-view__seg-btn ${layoutMode === 'by_version' ? 'admin-forms-view__seg-btn--active' : ''}`}
              onClick={() => setLayoutMode('by_version')}
            >
              By version
            </button>
            <button
              type="button"
              className={`admin-forms-view__seg-btn ${layoutMode === 'all' ? 'admin-forms-view__seg-btn--active' : ''}`}
              onClick={() => setLayoutMode('all')}
            >
              All forms
            </button>
          </div>
        </div>

        {error && (
          <p className="admin-form-builder-msg admin-form-builder-msg--err" role="alert">
            {error}
          </p>
        )}
        {message && !error && <p className="admin-form-builder-msg admin-form-builder-msg--ok">{message}</p>}

        <div className="admin-forms-view__filter-card">
          <p className="admin-forms-view__filter-title">Filter forms</p>
          <div className="admin-forms-view__filter-grid">
            <div className="admin-forms-view__field">
              <label htmlFor="admin-forms-search">Search by name or type</label>
              <input
                id="admin-forms-search"
                type="search"
                placeholder="e.g. Safety, Audit…"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                autoComplete="off"
              />
            </div>
            <div className="admin-forms-view__field">
              <label htmlFor="admin-forms-ver">Version</label>
              <select id="admin-forms-ver" value={versionFilter} onChange={(e) => setVersionFilter(e.target.value)}>
                <option value="all">All versions</option>
                {versionOptions.map((v) => (
                  <option key={v} value={v}>
                    v{v}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>

        <div className="admin-forms-view__table-shell">
          <div className="admin-forms-view__table-controls">
            <label>
              Show
              <select
                value={String(pageSize)}
                onChange={(e) => setPageSize(Number(e.target.value))}
                aria-label="Rows per page"
              >
                <option value="10">10</option>
                <option value="25">25</option>
                <option value="50">50</option>
              </select>
              entries
            </label>
            <span>
              {totalFiltered === 0
                ? 'No entries'
                : `Showing ${safePage * pageSize + 1}–${Math.min((safePage + 1) * pageSize, totalFiltered)} of ${totalFiltered}`}
            </span>
          </div>

          {totalFiltered === 0 ? (
            <p className="admin-forms-view__empty">
              {forms.length === 0
                ? 'No forms yet. Create one under Add form.'
                : vaultTab === 'opened' &&
                    !searchQuery.trim() &&
                    versionFilter === 'all' &&
                    forms.every((f) => isTruthyFlag(f.is_archived))
                  ? 'No non-archived forms. Open the Archive tab to see archived versions.'
                  : 'No forms match these filters.'}
            </p>
          ) : layoutMode === 'all' ? (
            <div className="admin-forms-view__table-wrap">
              <table className="admin-forms-view__table">
                {tableHead}
                <tbody>{paginatedRows.map((row, i) => renderRow(row, `form-${row.form_id}-${i}`))}</tbody>
              </table>
            </div>
          ) : (
            <div className="admin-forms-view__table-wrap" style={{ padding: '0 0 8px' }}>
              {groupedPage.map(({ rootId, rows }) => (
                <div key={rootId} className="admin-forms-view__group">
                  <table className="admin-forms-view__table">
                    {tableHead}
                    <tbody>{rows.map((row, i) => renderRow(row, `form-${row.form_id}-g${rootId}-${i}`))}</tbody>
                  </table>
                </div>
              ))}
            </div>
          )}

          {totalFiltered > pageSize && (
            <div className="admin-forms-view__table-controls" style={{ justifyContent: 'center', gap: 16 }}>
              <button
                type="button"
                className="admin-outline-button"
                disabled={safePage <= 0}
                onClick={() => setPageIndex((p) => Math.max(0, p - 1))}
              >
                Previous
              </button>
              <span style={{ fontSize: 13, color: 'var(--theme-gray-600)' }}>
                Page {safePage + 1} of {pageCount}
              </span>
              <button
                type="button"
                className="admin-outline-button"
                disabled={safePage >= pageCount - 1}
                onClick={() => setPageIndex((p) => Math.min(pageCount - 1, p + 1))}
              >
                Next
              </button>
            </div>
          )}
        </div>
      </div>
    </main>
  );
}

export default AdminFormsListPage;
