import type { SidebarItem } from "@/components/layout/types";
import type { RuleEngineResourceSlug } from "@/types/rule-engine";

export type RuleEngineNavCategory = "configuration" | "rules";

export type ColumnFormat =
  | "text"
  | "code"
  | "boolean"
  | "activeBadge"
  | "rateStatus"
  | "date"
  | "number"
  | "entityLabel"
  | "rateLabel";

export type FormFieldType = "text" | "number" | "boolean" | "date" | "select" | "textarea";

export interface ResourceColumn {
  id: string;
  header: string;
  accessorKey: string;
  format?: ColumnFormat;
}

/** Radix Select cannot use empty string as an item value; use this for optional "none" choices. */
export const RULE_ENGINE_SELECT_NONE = "__none__";

export interface FormFieldDef {
  name: string;
  label: string;
  type: FormFieldType;
  required?: boolean;
  optional?: boolean;
  options?: { label: string; value: string }[];
  placeholder?: string;
}

export interface RuleEngineResourceConfig {
  slug: RuleEngineResourceSlug;
  label: string;
  subtitle: string;
  category: RuleEngineNavCategory;
  searchPlaceholder: string;
  columns: ResourceColumn[];
  formFields: FormFieldDef[];
  supportsSearch?: boolean;
  /** Primary line on card view (inferred from columns when omitted). */
  cardTitleKey?: string;
  /** Secondary line under title on card view (inferred when omitted). */
  cardSubtitleKey?: string;
  /** Code badge on card header (inferred from code column when omitted). */
  cardCodeKey?: string;
}

export const RULE_ENGINE_CATEGORY_BASE_PATH: Record<RuleEngineNavCategory, string> = {
  configuration: "/dashboard/configuration",
  rules: "/dashboard/rules",
};

const TRADE_DIRECTIONS = [
  { label: "Import", value: "IMPORT" },
  { label: "Export", value: "EXPORT" },
  { label: "Both", value: "BOTH" },
];

const APPROVAL_ROLES = [
  { label: "Line staff", value: "LINE_STAFF" },
  { label: "Director", value: "DIRECTOR" },
  { label: "CEO", value: "CEO" },
];

const SURCHARGE_TRIGGERS = [
  { label: "Hazardous cargo", value: "CARGO_FLAG_HAZARDOUS" },
  { label: "Reefer cargo", value: "CARGO_FLAG_REEFER" },
  { label: "VGM exceeds limit", value: "VGM_EXCEEDS_LIMIT" },
  { label: "Shipping line mapped", value: "SHIPPING_LINE_MAPPED" },
  { label: "Consolidation enabled", value: "CONSOLIDATION_ENABLED" },
];

const RATE_TYPES = [
  "CONTAINER_IMPORT",
  "CONTAINER_EXPORT",
  "BULK_IMPORT",
  "BULK_EXPORT",
  "INTERCITY_BULK",
  "INTERCITY_CONTAINER",
  "FIRST_MILE",
  "LAST_MILE",
  "DEMURRAGE",
  "LASHING",
  "DOUBLE_HANDLING",
  "CONTAINER_WITH_RETURN",
  "CANCELLATION_FEE",
  "OVERWEIGHT_PER_TON",
  "HAZARD_SURCHARGE",
  "REEFER_SURCHARGE",
  "PIL_EXTRA_FEE",
].map((v) => ({ label: v.replace(/_/g, " "), value: v }));

const RATE_UNITS = ["PER_WAGON", "PER_TON", "PER_CONTAINER", "PER_KM", "FLAT"].map((v) => ({
  label: v.replace(/_/g, " "),
  value: v,
}));

const CURRENCIES = [
  { label: "ETB", value: "ETB" },
  { label: "USD", value: "USD" },
];

const codeColumn = (key: string, header = "Code"): ResourceColumn => ({
  id: key,
  header,
  accessorKey: key,
  format: "code",
});

const activeColumn: ResourceColumn = {
  id: "isActive",
  header: "Status",
  accessorKey: "isActive",
  format: "activeBadge",
};

export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
  {
    slug: "cargo-types",
    label: "Cargo Types",
    category: "configuration",
    subtitle: "Manage freight cargo classification and approval rules",
    searchPlaceholder: "Search cargo types by name or code...",
    supportsSearch: true,
    columns: [
      codeColumn("code"),
      { id: "cargoTypeName", header: "Name", accessorKey: "cargoTypeName" },
      {
        id: "requiresDirectorApproval",
        header: "Director approval",
        accessorKey: "requiresDirectorApproval",
        format: "boolean",
      },
      { id: "displayOrder", header: "Order", accessorKey: "displayOrder", format: "number" },
      activeColumn,
    ],
    formFields: [
      { name: "cargoTypeName", label: "Cargo type name", type: "text", required: true },
      {
        name: "parentGroupId",
        label: "Parent group",
        type: "select",
        optional: true,
        placeholder: "Select parent cargo type (optional)",
      },
      { name: "showFreeTextBox", label: "Show free text box", type: "boolean" },
      { name: "requiresDirectorApproval", label: "Requires director approval", type: "boolean" },
      { name: "isActive", label: "Active", type: "boolean" },
      { name: "displayOrder", label: "Display order", type: "number" },
    ],
  },
  {
    slug: "container-types",
    label: "Container Types",
    category: "configuration",
    subtitle: "Configure container sizes and wagon capacity",
    searchPlaceholder: "Search container types...",
    columns: [
      codeColumn("code"),
      { id: "label", header: "Label", accessorKey: "label" },
      { id: "sizeFt", header: "Size (ft)", accessorKey: "sizeFt", format: "number" },
      { id: "wagonsPerUnit", header: "Wagons / unit", accessorKey: "wagonsPerUnit", format: "number" },
      activeColumn,
    ],
    formFields: [
      { name: "label", label: "Label", type: "text", required: true },
      { name: "sizeFt", label: "Size (ft)", type: "number", required: true },
      { name: "wagonsPerUnit", label: "Wagons per unit", type: "number", required: true },
      { name: "isReefer", label: "Reefer", type: "boolean" },
      { name: "isOpenTop", label: "Open top", type: "boolean" },
      { name: "isActive", label: "Active", type: "boolean" },
      { name: "displayOrder", label: "Display order", type: "number" },
    ],
  },
  {
    slug: "wagon-types",
    label: "Wagon Types",
    category: "configuration",
    subtitle: "Configure wagon classes used for capacity and train planning",
    searchPlaceholder: "Search wagon types by name or code...",
    cardTitleKey: "name",
    columns: [
      codeColumn("code"),
      { id: "name", header: "Name", accessorKey: "name" },
      { id: "capacityTons", header: "Capacity (t)", accessorKey: "capacityTons", format: "number" },
      { id: "lengthMeters", header: "Length (m)", accessorKey: "lengthMeters", format: "number" },
      { id: "maxWagonsPerTrain", header: "Max / train", accessorKey: "maxWagonsPerTrain", format: "number" },
      {
        id: "supportedLoadTypes",
        header: "Load types",
        accessorKey: "supportedLoadTypes",
      },
      activeColumn,
    ],
    formFields: [
      { name: "name", label: "Name", type: "text", required: true },
      { name: "capacityTons", label: "Capacity (tons)", type: "number", required: true },
      { name: "lengthMeters", label: "Length (meters)", type: "number", required: true },
      {
        name: "maxWagonsPerTrain",
        label: "Max wagons per train",
        type: "number",
        optional: true,
      },
      {
        name: "supportedLoadTypes",
        label: "Supported load types",
        type: "textarea",
        optional: true,
        placeholder: "CONTAINER, BULK",
      },
      { name: "isActive", label: "Active", type: "boolean" },
    ],
  },
  {
    slug: "priority-rules",
    label: "Priority Rules",
    category: "rules",
    subtitle: "Booking priority scoring rules",
    searchPlaceholder: "Search priority rules...",
    columns: [
      codeColumn("code"),
      { id: "label", header: "Label", accessorKey: "label" },
      { id: "score", header: "Score", accessorKey: "score", format: "number" },
      { id: "conditionCurrency", header: "Currency", accessorKey: "conditionCurrency" },
      activeColumn,
    ],
    formFields: [
      { name: "label", label: "Label", type: "text", required: true },
      { name: "score", label: "Score", type: "number", required: true },
      {
        name: "conditionCurrency",
        label: "Condition currency",
        type: "select",
        optional: true,
        options: [{ label: "Any", value: RULE_ENGINE_SELECT_NONE }, ...CURRENCIES],
        placeholder: "Any currency (optional)",
      },
      { name: "isActive", label: "Active", type: "boolean" },
    ],
  },
  {
    slug: "service-types",
    label: "Service Types",
    category: "configuration",
    subtitle: "Freight service offerings and booking options",
    searchPlaceholder: "Search service types...",
    supportsSearch: true,
    columns: [
      codeColumn("code"),
      { id: "serviceName", header: "Service name", accessorKey: "serviceName" },
      { id: "priorityBonusPoints", header: "Bonus pts", accessorKey: "priorityBonusPoints", format: "number" },
      activeColumn,
    ],
    formFields: [
      { name: "serviceName", label: "Service name", type: "text", required: true },
      { name: "description", label: "Description", type: "textarea" },
      { name: "canBeBookedAlone", label: "Can be booked alone", type: "boolean" },
      { name: "includesFirstMile", label: "Includes first mile", type: "boolean" },
      { name: "includesLastMile", label: "Includes last mile", type: "boolean" },
      { name: "includesCustoms", label: "Includes customs", type: "boolean" },
      { name: "priorityBonusPoints", label: "Priority bonus points", type: "number" },
      { name: "isActive", label: "Active", type: "boolean" },
      { name: "displayOrder", label: "Display order", type: "number" },
    ],
  },
  {
    slug: "surcharge-types",
    label: "Surcharge Types",
    category: "configuration",
    subtitle: "Auto-applied surcharge definitions",
    searchPlaceholder: "Search surcharge types...",
    columns: [
      codeColumn("code"),
      { id: "label", header: "Label", accessorKey: "label" },
      { id: "triggerCondition", header: "Trigger", accessorKey: "triggerCondition" },
      { id: "rateId", header: "Rate", accessorKey: "rate", format: "rateLabel" },
      activeColumn,
    ],
    formFields: [
      { name: "label", label: "Label", type: "text", required: true },
      {
        name: "triggerCondition",
        label: "Trigger condition",
        type: "select",
        required: true,
        options: SURCHARGE_TRIGGERS,
      },
      {
        name: "rateId",
        label: "Live rate",
        type: "select",
        required: true,
        placeholder: "Select a LIVE rate",
      },
      { name: "isActive", label: "Active", type: "boolean" },
    ],
  },
  {
    slug: "weight-limit-rules",
    label: "Weight Limit Rules",
    category: "rules",
    subtitle: "VGM limits by container and trade direction",
    searchPlaceholder: "Search weight limit rules...",
    cardTitleKey: "containerType",
    cardSubtitleKey: "tradeDirection",
    columns: [
      {
        id: "containerType",
        header: "Container",
        accessorKey: "containerType",
        format: "entityLabel",
      },
      { id: "tradeDirection", header: "Direction", accessorKey: "tradeDirection" },
      { id: "maxVgmTons", header: "Max VGM (t)", accessorKey: "maxVgmTons", format: "number" },
      { id: "effectiveFrom", header: "From", accessorKey: "effectiveFrom", format: "date" },
      { id: "effectiveTo", header: "To", accessorKey: "effectiveTo", format: "date" },
    ],
    formFields: [
      {
        name: "containerTypeId",
        label: "Container type",
        type: "select",
        required: true,
        placeholder: "Select container type",
      },
      {
        name: "tradeDirection",
        label: "Trade direction",
        type: "select",
        required: true,
        options: TRADE_DIRECTIONS,
      },
      { name: "maxVgmTons", label: "Max VGM (tons)", type: "number", required: true },
      { name: "effectiveFrom", label: "Effective from", type: "date", required: true },
      { name: "effectiveTo", label: "Effective to", type: "date" },
    ],
  },
  {
    slug: "yards",
    label: "Yards",
    category: "configuration",
    subtitle: "Terminal and yard locations",
    searchPlaceholder: "Search yards...",
    columns: [
      codeColumn("code"),
      { id: "label", header: "Label", accessorKey: "label" },
      { id: "country", header: "Country", accessorKey: "country" },
      { id: "displayOrder", header: "Order", accessorKey: "displayOrder", format: "number" },
      activeColumn,
    ],
    formFields: [
      { name: "label", label: "Label", type: "text", required: true },
      { name: "country", label: "Country", type: "text", required: true },
      { name: "isActive", label: "Active", type: "boolean" },
      { name: "displayOrder", label: "Display order", type: "number" },
    ],
  },
  {
    slug: "shipping-lines",
    label: "Shipping Lines",
    category: "configuration",
    subtitle: "Shipping line codes and pricing mappings",
    searchPlaceholder: "Search shipping lines...",
    columns: [
      codeColumn("code"),
      { id: "label", header: "Label", accessorKey: "label" },
      { id: "mappedToCode", header: "Mapped to", accessorKey: "mappedToCode" },
      {
        id: "showExtraFeeNotice",
        header: "Extra fee notice",
        accessorKey: "showExtraFeeNotice",
        format: "boolean",
      },
      activeColumn,
    ],
    formFields: [
      { name: "code", label: "Code", type: "text", required: true },
      { name: "label", label: "Label", type: "text", required: true },
      { name: "mappedToCode", label: "Mapped to code", type: "text" },
      { name: "showExtraFeeNotice", label: "Show extra fee notice", type: "boolean" },
      { name: "isActive", label: "Active", type: "boolean" },
    ],
  },
  {
    slug: "rates",
    label: "Rates",
    category: "rules",
    cardTitleKey: "rateType",
    cardSubtitleKey: "currency",
    subtitle: "Freight rates and approval workflow",
    searchPlaceholder: "Search rates by type or status...",
    columns: [
      { id: "rateType", header: "Type", accessorKey: "rateType", format: "code" },
      { id: "currency", header: "Currency", accessorKey: "currency" },
      { id: "rateValue", header: "Value", accessorKey: "rateValue", format: "number" },
      { id: "rateUnit", header: "Unit", accessorKey: "rateUnit" },
      { id: "status", header: "Status", accessorKey: "status", format: "rateStatus" },
      { id: "effectiveFrom", header: "From", accessorKey: "effectiveFrom", format: "date" },
    ],
    formFields: [
      { name: "rateType", label: "Rate type", type: "select", required: true, options: RATE_TYPES },
      {
        name: "containerTypeId",
        label: "Container type",
        type: "select",
        optional: true,
        placeholder: "Select container type (optional)",
      },
      {
        name: "tradeDirection",
        label: "Trade direction",
        type: "select",
        options: TRADE_DIRECTIONS,
      },
      { name: "currency", label: "Currency", type: "select", required: true, options: CURRENCIES },
      { name: "rateValue", label: "Rate value", type: "number", required: true },
      { name: "rateUnit", label: "Rate unit", type: "select", required: true, options: RATE_UNITS },
      { name: "effectiveFrom", label: "Effective from", type: "date", required: true },
      { name: "effectiveTo", label: "Effective to", type: "date" },
    ],
  },
  {
    slug: "approval-rules",
    label: "Approval Rules",
    category: "rules",
    cardTitleKey: "actionLabel",
    cardSubtitleKey: "requiredRole",
    subtitle: "Multi-step booking approval chain",
    searchPlaceholder: "Search approval rules...",
    columns: [
      {
        id: "requiresDirectorApproval",
        header: "Director chain",
        accessorKey: "requiresDirectorApproval",
        format: "boolean",
      },
      { id: "stepOrder", header: "Step", accessorKey: "stepOrder", format: "number" },
      { id: "requiredRole", header: "Role", accessorKey: "requiredRole" },
      { id: "actionLabel", header: "Action", accessorKey: "actionLabel" },
      { id: "blocksRole", header: "Blocks", accessorKey: "blocksRole" },
    ],
    formFields: [
      { name: "requiresDirectorApproval", label: "Requires director approval chain", type: "boolean" },
      { name: "stepOrder", label: "Step order", type: "number", required: true },
      {
        name: "requiredRole",
        label: "Required role",
        type: "select",
        required: true,
        options: APPROVAL_ROLES,
      },
      { name: "actionLabel", label: "Action label", type: "text", required: true },
      {
        name: "blocksRole",
        label: "Blocks role",
        type: "select",
        optional: true,
        options: [{ label: "None", value: RULE_ENGINE_SELECT_NONE }, ...APPROVAL_ROLES],
      },
    ],
  },
];

export const RULE_ENGINE_RESOURCE_MAP = Object.fromEntries(
  RULE_ENGINE_RESOURCES.map((r) => [r.slug, r]),
) as Record<RuleEngineResourceSlug, RuleEngineResourceConfig>;

export const getRuleEngineResource = (slug: string): RuleEngineResourceConfig | undefined =>
  RULE_ENGINE_RESOURCE_MAP[slug as RuleEngineResourceSlug];

export const ruleEngineResourcePath = (slug: RuleEngineResourceSlug): string => {
  const resource = RULE_ENGINE_RESOURCE_MAP[slug];
  return `${RULE_ENGINE_CATEGORY_BASE_PATH[resource.category]}/${slug}`;
};

export const getCategorySidebarChildren = (
  category: RuleEngineNavCategory,
): SidebarItem[] =>
  RULE_ENGINE_RESOURCES.filter((r) => r.category === category).map((r) => ({
    label: r.label,
    href: ruleEngineResourcePath(r.slug),
  }));

export const DEFAULT_CONFIGURATION_SLUG: RuleEngineResourceSlug = "cargo-types";
export const DEFAULT_RULES_SLUG: RuleEngineResourceSlug = "priority-rules";

/** @deprecated Use DEFAULT_CONFIGURATION_SLUG */
export const DEFAULT_RULE_ENGINE_SLUG = DEFAULT_CONFIGURATION_SLUG;
