import { computed, type ComputedRef, type Ref } from "vue";
import { usePermissions } from "./usePermissions";
import type { FieldDefinition } from "../components/fields/types";

export type FormField = {
  name: string;
  label: string;
  component: string;
  rules: string[];
  default: unknown;
  hint: string | null;
  readonly: boolean;
  viewPermission: string | null;
  updatePermission: string | null;
  translatable: boolean;
  generateFrom: string | null;
  fields?: FieldDefinition[] | null;
  maxRows?: number | null;
  minRows?: number | null;
};

export type FormSection = {
  key: string;
  label: string;
  description: string | null;
  collapsible: boolean;
  priority: number;
  sidebar: boolean;
  tabGroup: string | null;
  fields: FormField[];
  viewPermission: string | null;
  updatePermission: string | null;
};

export type FormResourceDefinition = {
  slug: string;
  label: string;
  singularLabel: string;
  sections: FormSection[];
  showTimestamps: boolean;
  duplicatable: boolean;
  isHierarchical: boolean;
  isPublic: boolean;
  publicUrlBase: string;
  parentField: string;
  isRevisable: boolean;
};

export type FormSectionsState = {
  sectionsWithFields: ComputedRef<FormSection[]>;
  visibleSections: ComputedRef<FormSection[]>;
  mainSections: ComputedRef<FormSection[]>;
  sidebarSections: ComputedRef<FormSection[]>;
  hasSidebarSections: ComputedRef<boolean>;
};

export function useFormSections(
  resource: Ref<FormResourceDefinition>,
  currentLocale: Ref<string | null>,
): FormSectionsState {
  const { can } = usePermissions();

  const sectionsWithFields = computed<FormSection[]>(
    () => resource.value.sections,
  );

  const visibleSections = computed<FormSection[]>(() =>
    sectionsWithFields.value.filter((s) => can(s.viewPermission)),
  );

  const mainSections = computed<FormSection[]>(() =>
    visibleSections.value.filter((s) => !s.sidebar),
  );

  const sidebarSections = computed<FormSection[]>(() =>
    visibleSections.value.filter((s) => s.sidebar),
  );

  const hasSidebarSections = computed(() => sidebarSections.value.length > 0);

  return {
    sectionsWithFields,
    visibleSections,
    mainSections,
    sidebarSections,
    hasSidebarSections,
  };
}
