import React, { useEffect, useMemo, useRef, useState } from "react";
import { useAuth } from "../../context/AuthContext.jsx";
import { formatPermitValidity, usePermitValidity } from "../../context/PermitValidityContext.jsx";
import PageHeader from "../../components/common/PageHeader.jsx";
import DataTable from "../../components/common/DataTable.jsx";
import EntityModal from "../../components/common/EntityModal.jsx";
import ErrorBanner from "../../components/common/ErrorBanner.jsx";
import FileUploadField from "../../components/common/FileUploadField.jsx";
import useMasterData from "../../hooks/useMasterData.js";
import {
  createPermit,
  createSubmission,
  deletePermit,
  listPermits,
  listSubmissions,
  updatePermit
} from "../../services/permitsApi.js";
import { listForms } from "../../services/formsApi.js";
import { listLocations } from "../../services/masterApi.js";
import { getUser } from "../../services/usersApi.js";
import {
  buildSpecializedFormOptions,
  storeResumeIntent
} from "../../utils/ptwPermitResume.js";
import {
  DASHBOARD_FILTER_LABELS,
  filterPermitsByDashboardFilter
} from "../../utils/dashboardHelpers.js";
import {
  PERMIT_DATE_PRESETS,
  buildCountryNameById,
  buildLocationCountryById,
  buildLocationFilterOptions,
  buildLocationNameById,
  buildPermitJobTypeMap,
  filterPermitsByPageFilters,
  findJobTypeIdByName,
  formatPermitJobTypes,
  normalizeCountryRow,
  resolveCountryIdFromUserLocation,
  resolvePermitDateRange
} from "../../utils/permitFilters.js";
import { parseNavFromHash, writeNavHash } from "../../utils/ptwNavUrl.js";

function permitStatusTone(statusId, statusName) {
  const name = String(statusName || "").toLowerCase();
  if (name.includes("closed") || Number(statusId) === 3) return "closed";
  if (name.includes("active") || Number(statusId) === 2) return "active";
  return "draft";
}

export default function AdminPermitsPage({ onNavigate }) {
  const { auth } = useAuth();
  const { setActivePermit, navigateToHandover, navigateToHandback, navigateToAudit } = usePermitValidity();
  const { data } = useMasterData();
  const [permits, setPermits] = useState([]);
  const [forms, setForms] = useState([]);
  const [selected, setSelected] = useState(null);
  const [workspaceOpen, setWorkspaceOpen] = useState(false);
  const [selectedSpecializedJobTypeId, setSelectedSpecializedJobTypeId] = useState("");
  const [files, setFiles] = useState([]);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [dashFilter, setDashFilter] = useState(() => parseNavFromHash().params.dashFilter || "");
  const [userLocationId, setUserLocationId] = useState(null);
  const [locations, setLocations] = useState([]);
  const [submissions, setSubmissions] = useState([]);
  const [filterLocationId, setFilterLocationId] = useState("");
  const [filterJobTypeId, setFilterJobTypeId] = useState(() => {
    const dashJobType = parseNavFromHash().params.dashJobType || "";
    return dashJobType ? findJobTypeIdByName([], dashJobType) : "";
  });
  const [filterDatePreset, setFilterDatePreset] = useState("");
  const [filterDateFrom, setFilterDateFrom] = useState("");
  const [filterDateTo, setFilterDateTo] = useState("");
  const [filterCountryId, setFilterCountryId] = useState("");
  const [userDefaultCountryId, setUserDefaultCountryId] = useState("");
  const [userProfile, setUserProfile] = useState(null);
  const countryDefaultAppliedRef = useRef(false);

  useEffect(() => {
    function syncFilterFromHash() {
      setDashFilter(parseNavFromHash().params.dashFilter || "");
    }
    window.addEventListener("hashchange", syncFilterFromHash);
    return () => window.removeEventListener("hashchange", syncFilterFromHash);
  }, []);

  useEffect(() => {
    const userId = auth?.user?.user_id;
    if (!userId) {
      setUserProfile(null);
      return;
    }
    let mounted = true;
    getUser(userId)
      .then((row) => {
        if (mounted) setUserProfile(row || null);
      })
      .catch(() => {
        if (mounted) setUserProfile(null);
      });
    return () => {
      mounted = false;
    };
  }, [auth?.user?.user_id]);

  useEffect(() => {
    const userId = auth?.user?.user_id;
    if (!userId || dashFilter !== "location") {
      setUserLocationId(null);
      return;
    }
    const locationId =
      userProfile?.location_id != null ? Number(userProfile.location_id) : null;
    setUserLocationId(locationId);
  }, [auth?.user?.user_id, dashFilter, userProfile?.location_id]);

  useEffect(() => {
    if (!userProfile) return;
    const countryId = resolveCountryIdFromUserLocation(userProfile, locations);
    setUserDefaultCountryId(countryId);
    if (!countryDefaultAppliedRef.current && countryId) {
      setFilterCountryId(countryId);
      countryDefaultAppliedRef.current = true;
    } else if (!countryDefaultAppliedRef.current && locations.length) {
      countryDefaultAppliedRef.current = true;
    }
  }, [userProfile, locations]);

  const permitStatuses = useMemo(
    () => (Array.isArray(data.ptw_permit_status) ? data.ptw_permit_status : []),
    [data.ptw_permit_status]
  );
  const jobTypes = useMemo(
    () => (Array.isArray(data.ptw_job_type) ? data.ptw_job_type : []),
    [data.ptw_job_type]
  );
  const countries = useMemo(
    () =>
      (Array.isArray(data.country) ? data.country : [])
        .map((row) => normalizeCountryRow(row))
        .filter(Boolean)
        .sort((a, b) => a.country_name.localeCompare(b.country_name)),
    [data.country]
  );
  const countryNameById = useMemo(() => buildCountryNameById(countries), [countries]);
  const locationCountryById = useMemo(
    () => buildLocationCountryById(locations),
    [locations]
  );

  useEffect(() => {
    const dashJobType = parseNavFromHash().params.dashJobType || "";
    if (dashJobType && jobTypes.length) {
      setFilterJobTypeId((prev) => prev || findJobTypeIdByName(jobTypes, dashJobType));
    }
  }, [jobTypes]);

  const locationNameById = useMemo(
    () => buildLocationNameById(locations, permits),
    [locations, permits]
  );
  const jobTypeNameById = useMemo(
    () =>
      Object.fromEntries(
        jobTypes.map((row) => [
          String(row.job_type_id),
          row.job_type_name || `#${row.job_type_id}`
        ])
      ),
    [jobTypes]
  );
  const jobTypeMap = useMemo(
    () => buildPermitJobTypeMap(submissions, forms),
    [submissions, forms]
  );
  const activeDateRange = useMemo(
    () => resolvePermitDateRange(filterDatePreset, filterDateFrom, filterDateTo),
    [filterDatePreset, filterDateFrom, filterDateTo]
  );

  const dashFilteredPermits = useMemo(
    () =>
      filterPermitsByDashboardFilter(permits, dashFilter, {
        userId: auth?.user?.user_id,
        locationId: userLocationId
      }),
    [permits, dashFilter, auth?.user?.user_id, userLocationId]
  );

  const filteredPermits = useMemo(
    () =>
      filterPermitsByPageFilters(dashFilteredPermits, {
        countryId: filterCountryId,
        locationId: filterLocationId,
        jobTypeId: filterJobTypeId,
        dateFrom: activeDateRange.dateFrom,
        dateTo: activeDateRange.dateTo,
        jobTypeMap,
        locationCountryById
      }),
    [
      dashFilteredPermits,
      filterCountryId,
      filterLocationId,
      filterJobTypeId,
      activeDateRange.dateFrom,
      activeDateRange.dateTo,
      jobTypeMap,
      locationCountryById
    ]
  );

  const dashFilterLabel = DASHBOARD_FILTER_LABELS[dashFilter] || "";
  const hasPageFilters = Boolean(
    (filterCountryId && filterCountryId !== userDefaultCountryId) ||
      filterLocationId ||
      filterJobTypeId ||
      filterDatePreset ||
      filterDateFrom ||
      filterDateTo
  );

  const locationOptions = useMemo(
    () =>
      buildLocationFilterOptions(locations, permits, {
        countryId: filterCountryId
      }),
    [locations, permits, filterCountryId]
  );
  const jobTypeOptions = useMemo(
    () =>
      [...jobTypes].sort((a, b) =>
        String(a.job_type_name || "").localeCompare(String(b.job_type_name || ""))
      ),
    [jobTypes]
  );

  const permitStatusNameById = useMemo(
    () =>
      Object.fromEntries(
        permitStatuses.map((row) => [
          String(row.permit_status_id),
          row.permit_status_name || `#${row.permit_status_id}`
        ])
      ),
    [permitStatuses]
  );
  const specializedFormOptions = useMemo(
    () => buildSpecializedFormOptions(forms, jobTypes),
    [forms, jobTypes]
  );
  const selectedSpecializedForm = useMemo(() => {
    if (!selectedSpecializedJobTypeId) return null;
    return specializedFormOptions.find(
      (opt) => opt.jobTypeId === String(selectedSpecializedJobTypeId)
    )?.form ?? null;
  }, [selectedSpecializedJobTypeId, specializedFormOptions]);

  const canAddSpecializedForm =
    Boolean(selected?.valid_from) && Number(selected?.permit_status_id) !== 3;

  const permitStats = useMemo(() => {
    const source =
      dashFilter || hasPageFilters || filterCountryId ? filteredPermits : permits;
    const counts = { total: source.length, draft: 0, active: 0, closed: 0 };
    for (const row of source) {
      const tone = permitStatusTone(
        row.permit_status_id,
        permitStatusNameById[String(row.permit_status_id)]
      );
      counts[tone] += 1;
    }
    return counts;
  }, [permits, filteredPermits, dashFilter, hasPageFilters, filterCountryId, permitStatusNameById]);

  function clearPageFilters() {
    setFilterCountryId(userDefaultCountryId || "");
    setFilterLocationId("");
    setFilterJobTypeId("");
    setFilterDatePreset("");
    setFilterDateFrom("");
    setFilterDateTo("");
    const { id, params } = parseNavFromHash();
    if (params.dashJobType) {
      const next = { ...params };
      delete next.dashJobType;
      writeNavHash(id, next, { replace: true });
    }
  }

  function handleCountryChange(nextCountryId) {
    setFilterCountryId(nextCountryId);
    setFilterLocationId((current) => {
      if (!current) return "";
      const nextOptions = buildLocationFilterOptions(locations, permits, {
        countryId: nextCountryId
      });
      return nextOptions.some((row) => String(row.location_id) === String(current))
        ? current
        : "";
    });
  }

  const selectedStatusName = selected
    ? permitStatusNameById[String(selected.permit_status_id)] || "—"
    : "";
  const selectedStatusTone = selected
    ? permitStatusTone(selected.permit_status_id, selectedStatusName)
    : "draft";

  const permitColumns = useMemo(
    () => [
      { key: "permit_number", label: "Permit No." },
      {
        key: "permit_status_id",
        label: "Status",
        render: (row) => {
          const name =
            permitStatusNameById[String(row.permit_status_id)] ||
            row.permit_status_name ||
            "—";
          const tone = permitStatusTone(row.permit_status_id, name);
          return (
            <span className={`ptw-permits-status-chip ptw-permits-status-chip--${tone}`}>
              {name}
            </span>
          );
        }
      },
      {
        key: "location_id",
        label: "Location",
        render: (row) => {
          const locId = row.location_id != null ? String(row.location_id) : "";
          return locationNameById[locId] || (locId ? `#${locId}` : "—");
        }
      },
      {
        key: "job_types",
        label: "Job types",
        render: (row) => formatPermitJobTypes(row.permit_id, jobTypeMap, jobTypeNameById)
      },
      {
        key: "valid_until",
        label: "Valid until",
        render: (row) =>
          row.valid_until ? formatPermitValidity(row.valid_until) : "Not started"
      },
      {
        key: "created_at",
        label: "Created",
        render: (row) => {
          const raw = row.created_at;
          if (!raw) return "—";
          const d = new Date(raw);
          return Number.isNaN(d.getTime()) ? String(raw) : d.toLocaleString();
        }
      }
    ],
    [permitStatusNameById, locationNameById, jobTypeMap, jobTypeNameById]
  );

  async function load() {
    setLoading(true);
    try {
      setError("");
      const [permitsResult, formsResult, submissionsResult, locationsResult] =
        await Promise.allSettled([
          listPermits(),
          listForms(),
          listSubmissions(),
          listLocations()
        ]);

      const p = permitsResult.status === "fulfilled" ? permitsResult.value : [];
      const formRows = formsResult.status === "fulfilled" ? formsResult.value : [];
      const submissionRows =
        submissionsResult.status === "fulfilled" ? submissionsResult.value : [];
      const locationRows =
        locationsResult.status === "fulfilled" ? locationsResult.value : [];

      if (permitsResult.status === "rejected") {
        throw permitsResult.reason;
      }

      const loadWarnings = [];
      if (formsResult.status === "rejected") {
        loadWarnings.push("forms");
      }
      if (submissionsResult.status === "rejected") {
        loadWarnings.push("submissions");
      }
      if (locationsResult.status === "rejected") {
        loadWarnings.push("locations");
      }
      if (loadWarnings.length) {
        setError(
          `Loaded permits, but could not load ${loadWarnings.join(", ")} lookup data. Location names may be limited.`
        );
      }

      setPermits(p);
      setForms(Array.isArray(formRows) ? formRows : []);
      setSubmissions(Array.isArray(submissionRows) ? submissionRows : []);
      setLocations(Array.isArray(locationRows) ? locationRows : []);
      setSelected((prev) => {
        if (!prev?.permit_id) return prev;
        return p.find((row) => row.permit_id === prev.permit_id) || null;
      });
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    load();
  }, []);

  useEffect(() => {
    setSelectedSpecializedJobTypeId("");
  }, [selected?.permit_id]);

  function openWorkspace(row) {
    setSelected(row);
    setWorkspaceOpen(true);
  }

  function closeWorkspace() {
    setWorkspaceOpen(false);
  }

  function handleContinueSpecializedForm() {
    if (!selected?.permit_id) {
      setError("Select a permit first.");
      return;
    }
    if (!selectedSpecializedJobTypeId || !selectedSpecializedForm) {
      setError("Select a specialized permit form to continue.");
      return;
    }
    setError("");
    storeResumeIntent({
      permitId: selected.permit_id,
      jobTypeId: selectedSpecializedJobTypeId
    });
    setActivePermit({
      permitId: selected.permit_id,
      permitNumber: selected.permit_number,
      validFrom: selected.valid_from,
      validUntil: selected.valid_until
    });
    onNavigate?.("fill-form", {
      permitId: selected.permit_id,
      jobTypeId: selectedSpecializedJobTypeId
    });
    closeWorkspace();
  }

  const mediaMap = { 1: files };

  const workspaceContent = selected ? (
    <div className="ptw-permits-workspace__body">
      <div className="ptw-permits-workspace__summary">
        <div className="ptw-permits-workspace__summary-head">
          <span className="ptw-permits-workspace__ref">Permit #{selected.permit_id}</span>
          <span
            className={`ptw-permits-status-chip ptw-permits-status-chip--${selectedStatusTone} ptw-permits-status-chip--lg`}
          >
            {selectedStatusName}
          </span>
        </div>
        <dl className="ptw-permits-workspace__validity">
          <div className="ptw-permits-workspace__validity-item">
            <dt>Valid from</dt>
            <dd>{selected.valid_from ? formatPermitValidity(selected.valid_from) : "—"}</dd>
          </div>
          <div className="ptw-permits-workspace__validity-item">
            <dt>Valid until</dt>
            <dd>{selected.valid_until ? formatPermitValidity(selected.valid_until) : "—"}</dd>
          </div>
        </dl>
        {!selected.valid_from ? (
          <p className="ptw-permits-workspace__note">
            Validity starts when the general permit form is submitted (8-hour window).
          </p>
        ) : null}
      </div>

      <section className="ptw-permits-workspace__card">
          <div className="ptw-permits-workspace__card-head">
            <h4 className="ptw-permits-workspace__card-title">Submitted forms</h4>
            <p className="ptw-permits-workspace__card-desc">
              View every section and answer saved under this permit number.
            </p>
          </div>
          <button
            type="button"
            className="swi-btn swi-btn--primary ptw-permits-workspace__primary-btn"
            onClick={() => {
              onNavigate?.("permit-preview", { permitId: selected.permit_id });
              closeWorkspace();
            }}
          >
            View submitted forms
          </button>
        </section>

      {canAddSpecializedForm ? (
        <section className="ptw-permits-workspace__card">
          <div className="ptw-permits-workspace__card-head">
            <h4 className="ptw-permits-workspace__card-title">Add specialized form</h4>
            <p className="ptw-permits-workspace__card-desc">
              Return before expiry to add HOT WORK, HandOver, or other specialized forms.
            </p>
          </div>
          <label className="ptw-permits-workspace__field" htmlFor="ptw-permits-specialized-select">
            <span className="ptw-permits-workspace__field-label">Permit type</span>
            <select
              id="ptw-permits-specialized-select"
              className="swi-input ptw-permits-workspace__select"
              value={selectedSpecializedJobTypeId}
              onChange={(e) => setSelectedSpecializedJobTypeId(e.target.value)}
            >
              <option value="">Select a specialized permit…</option>
              {specializedFormOptions.map((opt) => (
                <option key={opt.jobTypeId} value={opt.jobTypeId} disabled={!opt.form}>
                  {opt.label}
                </option>
              ))}
            </select>
          </label>
          {selectedSpecializedJobTypeId && !selectedSpecializedForm ? (
            <p className="ptw-permits-workspace__hint ptw-permits-workspace__hint--warn">
              No form is linked to this job type. Configure one in Form Management.
            </p>
          ) : selectedSpecializedForm ? (
            <p className="ptw-permits-workspace__hint">
              Opens Form #{selectedSpecializedForm.form_id} under this permit number.
            </p>
          ) : null}
          <button
            type="button"
            className="swi-btn swi-btn--primary ptw-permits-workspace__primary-btn"
            disabled={!selectedSpecializedJobTypeId || !selectedSpecializedForm}
            onClick={handleContinueSpecializedForm}
          >
            Continue with selected form
          </button>
        </section>
      ) : null}

      {selected.valid_from && Number(selected.permit_status_id) !== 3 ? (
        <section className="ptw-permits-workspace__card">
          <h4 className="ptw-permits-workspace__card-title">Lifecycle</h4>
          <div className="ptw-permits-workspace__lifecycle">
            <button
              type="button"
              className="ptw-permits-workspace__lifecycle-btn"
              onClick={() => {
                setActivePermit({
                  permitId: selected.permit_id,
                  permitNumber: selected.permit_number,
                  validFrom: selected.valid_from,
                  validUntil: selected.valid_until
                });
                navigateToHandover(selected.permit_id);
                onNavigate?.("permit-handover");
                closeWorkspace();
              }}
            >
              <span className="ptw-permits-workspace__lifecycle-label">Handover</span>
              <span className="ptw-permits-workspace__lifecycle-desc">
                Transfer responsibility to the next holder
              </span>
            </button>
            <button
              type="button"
              className="ptw-permits-workspace__lifecycle-btn"
              onClick={() => {
                setActivePermit({
                  permitId: selected.permit_id,
                  permitNumber: selected.permit_number,
                  validFrom: selected.valid_from,
                  validUntil: selected.valid_until
                });
                navigateToAudit(selected.permit_id);
                onNavigate?.("permit-audit");
                closeWorkspace();
              }}
            >
              <span className="ptw-permits-workspace__lifecycle-label">Audit</span>
              <span className="ptw-permits-workspace__lifecycle-desc">
                Record shift audit (WHO, DATE, and follow-up actions)
              </span>
            </button>
            <button
              type="button"
              className="ptw-permits-workspace__lifecycle-btn ptw-permits-workspace__lifecycle-btn--close"
              onClick={() => {
                setActivePermit({
                  permitId: selected.permit_id,
                  permitNumber: selected.permit_number,
                  validFrom: selected.valid_from,
                  validUntil: selected.valid_until
                });
                navigateToHandback(selected.permit_id);
                onNavigate?.("permit-handback");
                closeWorkspace();
              }}
            >
              <span className="ptw-permits-workspace__lifecycle-label">Handback</span>
              <span className="ptw-permits-workspace__lifecycle-desc">
                Close out the permit and end the validity window
              </span>
            </button>
          </div>
        </section>
      ) : null}

      <section className="ptw-permits-workspace__admin">
        <h4 className="ptw-permits-workspace__admin-title">Administration</h4>
        <div className="ptw-permits-workspace__admin-actions">
          <button
            type="button"
            className="swi-btn swi-btn--ghost"
            disabled={!permitStatuses.length}
            onClick={async () => {
              if (!permitStatuses.length) {
                setError(
                  "No permit statuses configured. Run sql/migrations/seed_ptw_permit_status.sql."
                );
                return;
              }
              const currentId = Number(selected.permit_status_id) || 0;
              const ordered = [...permitStatuses].sort(
                (a, b) => Number(a.permit_status_id) - Number(b.permit_status_id)
              );
              const idx = ordered.findIndex(
                (row) => Number(row.permit_status_id) === currentId
              );
              const next = idx >= 0 ? ordered[idx + 1] : ordered[0];
              if (!next) {
                setError("Permit is already at the final configured status.");
                return;
              }
              try {
                await updatePermit(selected.permit_id, {
                  permit_status_id: next.permit_status_id
                });
                await load();
              } catch (err) {
                setError(err?.response?.data?.message || err.message);
              }
            }}
          >
            Advance status
          </button>
          <button
            type="button"
            className="swi-btn swi-btn--danger"
            onClick={async () => {
              await deletePermit(selected.permit_id);
              setSelected(null);
              closeWorkspace();
              await load();
            }}
          >
            Delete permit
          </button>
        </div>
      </section>

      <details className="ptw-permits-advanced">
        <summary>Advanced tools</summary>
        <div className="ptw-permits-advanced__body">
          <FileUploadField
            label="Upload media"
            multiple
            accept="image/*,application/pdf"
            onChange={setFiles}
          />
          <div className="ptw-permits-workspace__actions">
            <button
              type="button"
              className="swi-btn swi-btn--ghost"
              onClick={async () => {
                await createSubmission(
                  {
                    permit_id: selected.permit_id,
                    form_id: 1,
                    submission_role: "opening",
                    answers: [
                      {
                        question_id: 1,
                        is_media: files.length ? 1 : 0,
                        answer_value: "Opening checklist"
                      }
                    ]
                  },
                  mediaMap
                );
                await load();
              }}
            >
              Test opening submission
            </button>
            <button
              type="button"
              className="swi-btn swi-btn--ghost"
              onClick={async () => {
                await createSubmission(
                  {
                    permit_id: selected.permit_id,
                    form_id: 1,
                    submission_role: "closing",
                    answers: [
                      {
                        question_id: 1,
                        is_media: files.length ? 1 : 0,
                        answer_value: "Closing checklist"
                      }
                    ]
                  },
                  mediaMap
                );
                await load();
              }}
            >
              Test closing submission
            </button>
            <button
              type="button"
              className="swi-btn swi-btn--ghost"
              onClick={async () => {
                await createPermit({
                  permit_status_id: 1,
                  permit_number: `PTW-${Date.now()}`
                });
                await load();
              }}
            >
              Create blank permit
            </button>
          </div>
        </div>
      </details>
    </div>
  ) : null;

  return (
    <div className="portal-page portal-page--document-full ptw-permits-page">
      <PageHeader
        title="Permits & Submissions"
        subtitle="Review permit validity, add specialized forms, and manage audit, handover, or handback."
        actions={(
          <>
            <button
              type="button"
              className="swi-btn swi-btn--primary"
              disabled={loading}
              onClick={() => onNavigate?.("fill-form")}
            >
              Start new permit
            </button>
            <button type="button" className="swi-btn swi-btn--ghost" onClick={load} disabled={loading}>
              {loading ? "Refreshing…" : "Refresh"}
            </button>
          </>
        )}
      />
      <ErrorBanner message={error} />

      {dashFilterLabel ? (
        <div className="ptw-permits-filter-banner">
          <span>
            Showing <strong>{dashFilterLabel.toLowerCase()}</strong>
            {" "}({filteredPermits.length} permit{filteredPermits.length === 1 ? "" : "s"})
          </span>
          <button
            type="button"
            className="swi-btn swi-btn--ghost swi-btn--compact"
            onClick={() => {
              setDashFilter("");
              writeNavHash("permits-submissions", {}, { replace: true });
            }}
          >
            Clear filter
          </button>
        </div>
      ) : null}

      <section className="ptw-panel ptw-permits-filters" aria-label="Permit filters">
        <div className="ptw-permits-filters__head">
          <h3 className="ptw-panel__title">Filters</h3>
          {hasPageFilters ? (
            <button
              type="button"
              className="swi-btn swi-btn--ghost swi-btn--compact"
              onClick={clearPageFilters}
            >
              Clear filters
            </button>
          ) : null}
        </div>
        <div className="ptw-permits-filters__grid">
          <label className="ptw-permits-filters__field">
            <span className="ptw-permits-filters__label">Country</span>
            <select
              className="swi-input"
              value={filterCountryId}
              onChange={(event) => handleCountryChange(event.target.value)}
            >
              <option value="">All countries</option>
              {countries.map((row) => (
                <option key={row.country_id} value={String(row.country_id)}>
                  {row.country_name}
                </option>
              ))}
            </select>
          </label>
          <label className="ptw-permits-filters__field">
            <span className="ptw-permits-filters__label">Location</span>
            <select
              className="swi-input"
              value={filterLocationId}
              onChange={(event) => setFilterLocationId(event.target.value)}
            >
              <option value="">
                {filterCountryId ? "All locations in country" : "All locations"}
              </option>
              {locationOptions.map((row) => (
                <option key={row.location_id} value={String(row.location_id)}>
                  {row.location_name}
                </option>
              ))}
            </select>
          </label>
          <label className="ptw-permits-filters__field">
            <span className="ptw-permits-filters__label">Job type</span>
            <select
              className="swi-input"
              value={filterJobTypeId}
              onChange={(event) => setFilterJobTypeId(event.target.value)}
            >
              <option value="">All job types</option>
              {jobTypeOptions.map((row) => (
                <option key={row.job_type_id} value={row.job_type_id}>
                  {row.job_type_name || `#${row.job_type_id}`}
                </option>
              ))}
            </select>
          </label>
          <label className="ptw-permits-filters__field">
            <span className="ptw-permits-filters__label">Date range</span>
            <select
              className="swi-input"
              value={filterDatePreset}
              onChange={(event) => setFilterDatePreset(event.target.value)}
            >
              {PERMIT_DATE_PRESETS.map((option) => (
                <option key={option.value || "all"} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </label>
          {filterDatePreset === "custom" ? (
            <>
              <label className="ptw-permits-filters__field">
                <span className="ptw-permits-filters__label">From</span>
                <input
                  type="date"
                  className="swi-input"
                  value={filterDateFrom}
                  onChange={(event) => setFilterDateFrom(event.target.value)}
                />
              </label>
              <label className="ptw-permits-filters__field">
                <span className="ptw-permits-filters__label">To</span>
                <input
                  type="date"
                  className="swi-input"
                  value={filterDateTo}
                  onChange={(event) => setFilterDateTo(event.target.value)}
                />
              </label>
            </>
          ) : null}
        </div>
        {hasPageFilters || dashFilterLabel || filterCountryId ? (
          <p className="ptw-permits-filters__summary">
            Showing {filteredPermits.length} permit{filteredPermits.length === 1 ? "" : "s"}
            {dashFilterLabel ? ` (${dashFilterLabel.toLowerCase()})` : ""}
            {filterCountryId
              ? ` · country: ${countryNameById[filterCountryId] || filterCountryId}`
              : ""}
            {filterLocationId ? ` · location: ${locationNameById[filterLocationId] || filterLocationId}` : ""}
            {filterJobTypeId ? ` · job type: ${jobTypeNameById[filterJobTypeId] || filterJobTypeId}` : ""}
            {activeDateRange.dateFrom || activeDateRange.dateTo
              ? ` · created ${activeDateRange.dateFrom || "…"} to ${activeDateRange.dateTo || "…"}`
              : ""}
          </p>
        ) : null}
      </section>

      <div className="ptw-permits-stats">
        <div className="ptw-permits-stat ptw-permits-stat--total">
          <span className="ptw-permits-stat__icon" aria-hidden>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
              <path d="M4 8h16v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8z" />
              <path d="M8 8V6a4 4 0 1 1 8 0v2" />
            </svg>
          </span>
          <span className="ptw-permits-stat__value">{permitStats.total}</span>
          <span className="ptw-permits-stat__label">Total permits</span>
        </div>
        <div className="ptw-permits-stat ptw-permits-stat--draft">
          <span className="ptw-permits-stat__icon" aria-hidden>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
              <path d="M14 2v6h6" />
            </svg>
          </span>
          <span className="ptw-permits-stat__value">{permitStats.draft}</span>
          <span className="ptw-permits-stat__label">Draft</span>
        </div>
        <div className="ptw-permits-stat ptw-permits-stat--active">
          <span className="ptw-permits-stat__icon" aria-hidden>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
              <circle cx="12" cy="12" r="9" />
              <path d="M8 12l2.5 2.5L16 9" />
            </svg>
          </span>
          <span className="ptw-permits-stat__value">{permitStats.active}</span>
          <span className="ptw-permits-stat__label">Active</span>
        </div>
        <div className="ptw-permits-stat ptw-permits-stat--closed">
          <span className="ptw-permits-stat__icon" aria-hidden>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
              <rect x="3" y="11" width="18" height="10" rx="2" />
              <path d="M7 11V7a5 5 0 0 1 10 0v4" />
            </svg>
          </span>
          <span className="ptw-permits-stat__value">{permitStats.closed}</span>
          <span className="ptw-permits-stat__label">Closed</span>
        </div>
      </div>

      <div className="ptw-permits-shell">
        <section className="ptw-panel ptw-permits-list">
          <div className="ptw-permits-list__head">
            <h3 className="ptw-panel__title">All permits</h3>
            <span className="ptw-panel__meta">{filteredPermits.length} records</span>
          </div>
          <p className="ptw-permits-list__hint">Click a permit row to open the workspace.</p>
          <DataTable
            columns={permitColumns}
            rows={filteredPermits}
            keyField="permit_id"
            onRowClick={openWorkspace}
            isRowSelected={(row) => Number(row.permit_id) === Number(selected?.permit_id)}
            emptyMessage={
              hasPageFilters || dashFilterLabel
                ? "No permits match the current filters."
                : "No permits yet. Use Start new permit to create your first one."
            }
          />
        </section>
      </div>

      <EntityModal
        open={workspaceOpen && Boolean(selected)}
        title={selected ? selected.permit_number || `PTW-${selected.permit_id}` : "Permit workspace"}
        subtitle="Permit workspace"
        size="wide"
        variant="detail"
        onClose={closeWorkspace}
      >
        {workspaceContent}
      </EntityModal>
    </div>
  );
}
