import React from "react";
import PtwMgmtPage from "../../components/admin/PtwMgmtPage.jsx";
import {
  createJobType,
  getJobType,
  listJobTypes,
  updateJobType
} from "../../services/jobTypesApi.js";
import { mgmtActionColumn } from "../../utils/ptwMgmtHelpers.jsx";

const DEFAULT_COLOUR = "#ffff00";

const blankJobType = {
  job_type_name: "",
  job_colour_code: DEFAULT_COLOUR
};

function normalizeHexColour(value) {
  const raw = String(value || "").trim();
  if (!raw) return "";
  const withHash = raw.startsWith("#") ? raw : `#${raw}`;
  if (!/^#[0-9a-fA-F]{6}$/.test(withHash)) return "";
  return withHash.toLowerCase();
}

function buildPayload(draft) {
  const payload = {};
  const name = draft.job_type_name?.trim();
  if (name) payload.job_type_name = name;
  const colour = normalizeHexColour(draft.job_colour_code);
  if (colour) payload.job_colour_code = colour;
  return payload;
}

function draftFromRow(row) {
  return {
    job_type_name: row.job_type_name ?? "",
    job_colour_code: row.job_colour_code || DEFAULT_COLOUR
  };
}

function normalizeJobTypeRow(row) {
  if (!row || typeof row !== "object") return null;
  const jobTypeId = Number(row.job_type_id);
  return {
    ...row,
    job_type_id: Number.isFinite(jobTypeId) ? jobTypeId : row.job_type_id,
    job_type_name: row.job_type_name ?? "",
    job_colour_code: row.job_colour_code || null
  };
}

function validateDraft(draft) {
  if (!draft.job_type_name?.trim()) {
    return "Job type name is required.";
  }
  const colour = String(draft.job_colour_code || "").trim();
  if (colour && !normalizeHexColour(colour)) {
    return "Colour code must be a valid hex value (e.g. #ffff00).";
  }
  return "";
}

function ColourSwatch({ colour, label }) {
  const bg = normalizeHexColour(colour) || "#e5e7eb";
  return (
    <span className="ptw-mgmt-colour-swatch" title={label || colour || "No colour"}>
      <span className="ptw-mgmt-colour-swatch__chip" style={{ backgroundColor: bg }} aria-hidden />
      <span>{label || colour || "—"}</span>
    </span>
  );
}

function JobTypeFields({ draft, setDraft }) {
  function setColour(next) {
    const normalized = normalizeHexColour(next) || next;
    setDraft((prev) => ({ ...prev, job_colour_code: normalized }));
  }

  const pickerValue = normalizeHexColour(draft.job_colour_code) || DEFAULT_COLOUR;

  return (
    <div className="ptw-mgmt-form-grid">
      <label className="ptw-mgmt-field ptw-mgmt-field--full">
        <span className="ptw-mgmt-field__label">
          Job type name <em className="ptw-mgmt-required">*</em>
        </span>
        <input
          className="ptw-mgmt-input"
          value={draft.job_type_name}
          onChange={(e) => setDraft((prev) => ({ ...prev, job_type_name: e.target.value }))}
          placeholder="e.g. Hot Work, Confined Space"
        />
      </label>
      <label className="ptw-mgmt-field ptw-mgmt-field--full">
        <span className="ptw-mgmt-field__label">Dashboard colour</span>
        <div className="ptw-mgmt-colour-input">
          <input
            type="color"
            className="ptw-mgmt-colour-input__picker"
            value={pickerValue}
            onChange={(e) => setColour(e.target.value)}
            aria-label="Pick job type colour"
          />
          <input
            className="ptw-mgmt-input"
            value={draft.job_colour_code}
            onChange={(e) => setDraft((prev) => ({ ...prev, job_colour_code: e.target.value }))}
            onBlur={(e) => {
              const normalized = normalizeHexColour(e.target.value);
              if (normalized) setColour(normalized);
            }}
            placeholder="#ffff00"
          />
        </div>
        <p className="ptw-mgmt-type-format__hint">
          Used on dashboard charts and permit filters. Leave blank to use the default theme colour.
        </p>
      </label>
    </div>
  );
}

function JobTypeDetailView({ row }) {
  return (
    <dl className="ptw-key-value ptw-mgmt-detail">
      <dt>Job type ID</dt>
      <dd>{row.job_type_id}</dd>
      <dt>Name</dt>
      <dd>{row.job_type_name || "—"}</dd>
      <dt>Colour</dt>
      <dd>
        <ColourSwatch colour={row.job_colour_code} label={row.job_colour_code} />
      </dd>
    </dl>
  );
}

export default function AdminJobTypeManagementPage() {
  return (
    <PtwMgmtPage
      title="Job Type Management"
      subtitle="Add and maintain job types used when creating PTW forms and filtering permits."
      keyField="job_type_id"
      labels={{
        createTab: "Add Job Type",
        listTab: "View All Job Types",
        createHeading: "Add a new job type",
        createDesc:
          "Job types classify permit forms (e.g. General, Hot Work). Assign them when creating forms in Form Management.",
        createSectionTitle: "Job type details",
        listHeading: "All job types",
        listDesc: "View or update job types available across Form Management and permit filters.",
        entitySingular: "job type",
        entityPlural: "job types",
        createButton: "Add job type",
        createSaving: "Saving…",
        clearButton: "Clear form",
        createSuccess: "Job type has been added successfully.",
        updateSuccess: "Job type has been updated successfully.",
        emptyList:
          "No job types yet. Switch to Add Job Type to create your first job type.",
        viewModalTitle: "View job type",
        updateModalTitle: "Update job type",
        viewLoading: "Loading job type details…"
      }}
      blankDraft={blankJobType}
      buildPayload={buildPayload}
      draftFromRow={draftFromRow}
      normalizeRow={normalizeJobTypeRow}
      listFn={listJobTypes}
      getFn={getJobType}
      createFn={createJobType}
      updateFn={updateJobType}
      validateDraft={validateDraft}
      renderFields={({ draft, setDraft }) => (
        <JobTypeFields draft={draft} setDraft={setDraft} />
      )}
      renderDetail={({ row }) => <JobTypeDetailView row={row} />}
      buildColumns={({ openView, openUpdate }) => [
        { key: "job_type_id", label: "ID" },
        {
          key: "job_type_name",
          label: "Job type",
          render: (r) => (
            <span className="ptw-mgmt-cell-clip">{r.job_type_name || "—"}</span>
          )
        },
        {
          key: "job_colour_code",
          label: "Colour",
          render: (r) => (
            <ColourSwatch
              colour={r.job_colour_code}
              label={r.job_colour_code || "Default"}
            />
          )
        },
        mgmtActionColumn({ openView, openUpdate })
      ]}
    />
  );
}
