"use client";

// Form building blocks shared by the page editors under Admin → Pages
// (Working at Singh, About Us, Benefits).

import { FolderKanban } from "lucide-react";

import AdvancedCropperImageField from "@/components/admin/advanced-cropper-image-field";
import { post } from "@/lib/api";
import { getApiAssetUrl } from "@/lib/api-asset-url";

type ApiResponse<T> = {
  statusCode: number;
  success: boolean;
  data: T;
  message: string;
};

export const DEFAULT_PAGE_IMAGE = "/panel-placeholder-image.png";

export const inputClass =
  "h-11 rounded-2xl border-0 bg-[#F7F2EC] shadow-none focus-visible:ring-0";

export const textareaClass =
  "rounded-2xl border-0 bg-[#F7F2EC] shadow-none focus-visible:ring-0";

// The edit popup stays inside the screen: header and footer are fixed and
// only the form body scrolls.
export const editorDialogClass =
  "max-h-[calc(100dvh-2rem)] gap-0 overflow-hidden rounded-[24px] border-0 bg-[#FFFCF9] p-0 shadow-[0_24px_60px_rgba(58,45,39,0.16)] sm:max-w-4xl";
export const editorFormClass =
  "grid max-h-[calc(100dvh-2rem)] min-h-0 grid-rows-[auto_minmax(0,1fr)_auto]";
export const editorBodyClass =
  "min-h-0 min-w-0 space-y-4 overflow-y-auto overflow-x-hidden px-6 py-5";

let rowKeyCounter = 0;
export const nextRowKey = () => `row-${++rowKeyCounter}`;

export function getApiErrorMessage(error: unknown, fallback: string) {
  if (!(error instanceof Error)) return fallback;

  const details = (error as Error & { errors?: unknown }).errors;

  if (details && typeof details === "object") {
    const messages = Object.values(details).flatMap((value) =>
      Array.isArray(value)
        ? value.filter((item): item is string => typeof item === "string")
        : typeof value === "string"
          ? [value]
          : [],
    );

    if (messages.length > 0) return messages[0];
  }

  return error.message || fallback;
}

export async function uploadPageImage(pageId: number, file: File) {
  const payload = new FormData();
  payload.append("career_group_id", String(pageId));
  payload.append("image", file);

  const response = await post<ApiResponse<{ path?: string }>>(
    "/career-groups/page-image",
    payload,
  );

  if (!response.data?.path) {
    throw new Error("Image upload did not return a file path.");
  }

  return response.data.path;
}

// Fixed website pages (e.g. Benefits) store their images separately from
// career group pages.
export async function uploadSitePageImage(slug: string, file: File) {
  const payload = new FormData();
  payload.append("slug", slug);
  payload.append("image", file);

  const response = await post<ApiResponse<{ path?: string }>>(
    "/site-pages/image",
    payload,
  );

  if (!response.data?.path) {
    throw new Error("Image upload did not return a file path.");
  }

  return response.data.path;
}

export function moveItem<T>(items: T[], from: number, to: number) {
  if (to < 0 || to >= items.length) return items;

  const next = [...items];
  const [item] = next.splice(from, 1);
  next.splice(to, 0, item);
  return next;
}

export function splitParagraphs(value: string) {
  return value
    .split(/\n\s*\n/)
    .map((paragraph) => paragraph.trim())
    .filter(Boolean);
}

export function SectionHeading({ children }: { children: string }) {
  return (
    <p className="border-t border-[#EEE4DA] pt-4 text-xs font-semibold uppercase tracking-[0.16em] text-[#B08D57] first:border-t-0 first:pt-0">
      {children}
    </p>
  );
}

export function Field({
  label,
  htmlFor,
  hint,
  children,
}: {
  label: string;
  htmlFor: string;
  hint?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-2">
      <label htmlFor={htmlFor} className="text-sm font-medium text-[#4D3D35]">
        {label}
      </label>
      {children}
      {hint && <p className="text-xs text-[#8A7A6D]">{hint}</p>}
    </div>
  );
}

export function ImageField({
  label,
  currentImage,
  hasNewFile,
  crop,
  fieldKey,
  disabled,
  compact,
  onChange,
}: {
  label: string;
  currentImage: string;
  hasNewFile: boolean;
  crop: { width: number; height: number };
  fieldKey: string;
  disabled: boolean;
  compact?: boolean;
  onChange: (file: File | null) => void;
}) {
  return (
    <div className="space-y-2">
      <span className="text-sm font-medium text-[#4D3D35]">{label}</span>
      {!hasNewFile && currentImage && (
        <div className="space-y-1">
          <img
            src={getApiAssetUrl(currentImage, DEFAULT_PAGE_IMAGE)}
            alt={`Current ${label.toLowerCase()}`}
            className={`${compact ? "h-28 w-40" : "h-36 w-full"} rounded-2xl object-cover ring-1 ring-[#EEE4DA]`}
          />
          <p className="text-xs text-[#8A7A6D]">
            Current image. Upload a new one below to replace it.
          </p>
        </div>
      )}
      <AdvancedCropperImageField
        key={fieldKey}
        disabled={disabled}
        cropWidth={crop.width}
        cropHeight={crop.height}
        label="page"
        onChange={(file) => onChange(file)}
      />
    </div>
  );
}

export function IconButton({
  label,
  tone,
  disabled,
  onClick,
  children,
}: {
  label: string;
  tone?: "danger";
  disabled?: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      aria-label={label}
      title={label}
      disabled={disabled}
      onClick={onClick}
      className={`inline-flex size-9 shrink-0 items-center justify-center rounded-xl transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${
        tone === "danger"
          ? "bg-[#F6E9E6] text-[#8D4F48] hover:bg-[#EFD9D5]"
          : "bg-[#F3E8DE] text-[#7D6254] hover:bg-[#EAD9C9]"
      }`}
    >
      {children}
    </button>
  );
}

export function Metric({
  icon: Icon,
  label,
  value,
  tone,
}: {
  icon: typeof FolderKanban;
  label: string;
  value: number;
  tone: "total" | "active" | "inactive";
}) {
  const colors = {
    total: "bg-[#E8E1D0] text-[#7D6254]",
    active: "bg-[#E7F4EA] text-[#2F8A4C]",
    inactive: "bg-[#F6E9E6] text-[#8D4F48]",
  };
  const badgeColors = {
    total: "bg-[#B5A169]",
    active: "bg-[#2F8A4C]",
    inactive: "bg-[#8D4F48]",
  };

  return (
    <div className="flex items-center gap-3 rounded-2xl bg-[#F7F2EC] px-4 py-2.5">
      <span className={`flex size-9 items-center justify-center rounded-xl ${colors[tone]}`}>
        <Icon className="size-4" />
      </span>
      <span className="text-sm font-medium text-[#6F6056]">{label}</span>
      <span className={`rounded-full px-2.5 py-1 text-xs font-semibold text-white ${badgeColors[tone]}`}>
        {value}
      </span>
    </div>
  );
}
