// APRT - Apollinare Report Template Types

export interface AprtTemplate {
  version: string;
  meta: AprtMeta;
  resources: AprtResources;
  dataSources: Record<string, AprtDataSource>;
  sections: AprtSection[];
  pages: AprtPage[];
  elements: AprtElement[];
}

// Page definition for multi-page templates
export interface AprtPage {
  id: string;
  name: string;
  pageSize?: PageSize; // Override template default
  orientation?: PageOrientation; // Override template default
  margins?: AprtMargins; // Override template default
  backgroundColor?: string;
}

export interface AprtMeta {
  name: string;
  description?: string;
  author?: string;
  createdAt?: string;
  pageSize: PageSize;
  orientation: PageOrientation;
  margins: AprtMargins;
}

export type PageSize = "A4" | "A3" | "A5" | "Letter" | "Legal";
export type PageOrientation = "portrait" | "landscape";

export interface AprtMargins {
  top: number;
  right: number;
  bottom: number;
  left: number;
}

export interface AprtResources {
  fonts: AprtFontResource[];
  images: AprtImageResource[];
}

export interface AprtFontResource {
  id: string;
  name: string;
  url?: string;
  data?: string; // Base64
}

export interface AprtImageResource {
  id: string;
  name: string;
  url?: string;
  data?: string; // Base64
}

export interface AprtDataSource {
  type: "object" | "array";
  schema: string;
}

export interface AprtSection {
  id?: string;
  type: "header" | "body" | "detail" | "footer";
  height?: number;
  repeatOnPages?: boolean;
  dataSource?: string;
  elements: string[]; // Element IDs
}

export type ElementType =
  | "text"
  | "image"
  | "shape"
  | "table"
  | "line"
  | "barcode";

export interface AprtElement {
  id: string;
  type: ElementType;
  section?: "header" | "body" | "footer";
  pageId?: string; // ID of the page this element belongs to
  position: AprtPosition;
  style: AprtStyle;
  content?: AprtContent;
  dataSource?: string;
  columns?: AprtTableColumn[];
  imageSettings?: AprtImageSettings;
  visible: boolean;
  locked: boolean;
  name?: string;
}

export interface AprtImageSettings {
  src?: string; // URL or base64 data URI
  originalWidth?: number;
  originalHeight?: number;
  fitMode: "contain" | "cover" | "fill" | "none";
  maintainAspectRatio: boolean;
  horizontalAlign: "left" | "center" | "right";
  verticalAlign: "top" | "center" | "bottom";
  opacity: number;
  borderRadius: number;
  shadow: boolean;
  flipHorizontal: boolean;
  flipVertical: boolean;
}

export interface AprtPosition {
  x: number;
  y: number;
  width: number;
  height: number;
  rotation?: number;
}

export interface AprtStyle {
  fontFamily: string;
  fontSize: number;
  fontWeight: "normal" | "bold";
  fontStyle: "normal" | "italic";
  textDecoration?: "none" | "underline" | "line-through";
  color: string;
  backgroundColor?: string;
  textAlign: "left" | "center" | "right" | "justify";
  verticalAlign: "top" | "middle" | "bottom";
  borderWidth: number;
  borderColor: string;
  borderStyle: "solid" | "dashed" | "dotted";
  padding: number;
  lineHeight: number;
  opacity: number;
}

export interface AprtContent {
  type: "static" | "binding" | "expression" | "resource";
  value?: string;
  expression?: string;
  resourceId?: string;
  format?: "currency" | "date" | "datetime" | "number" | "percent";
  formatOptions?: Record<string, unknown>;
}

export interface AprtTableColumn {
  field: string;
  header: string;
  width: number;
  format?: string;
  align: "left" | "center" | "right";
  headerStyle?: Partial<AprtStyle>;
  cellStyle?: Partial<AprtStyle>;
}

// API DTOs
export interface ReportTemplateDto {
  id: number;
  nome: string;
  descrizione?: string;
  categoria: string;
  templateJson: string;
  thumbnailBase64?: string;
  pageSize: string;
  orientation: string;
  attivo: boolean;
  createdAt?: string;
  updatedAt?: string;
}

export interface ReportFontDto {
  id: number;
  nome: string;
  fontFamily: string;
  fontStyle: string;
  fontDataBase64?: string;
  mimeType: string;
  fileSize: number;
  attivo: boolean;
}

export interface ReportImageDto {
  id: number;
  nome: string;
  categoria: string;
  imageDataBase64?: string;
  mimeType: string;
  width: number;
  height: number;
  fileSize: number;
  attivo: boolean;
}

export interface GenerateReportRequest {
  templateId: number;
  dataContext: Record<string, unknown>;
}

export interface PreviewReportRequest {
  templateId: number;
  dataSources: DataSourceSelection[];
}

export interface DataSourceSelection {
  datasetId: string;
  entityId: number;
  alias?: string;
}

export interface DatasetTypeDto {
  id: string;
  name: string;
  description: string;
  icon: string;
  category: string;
  isVirtual?: boolean;
}

export interface EntityListItemDto {
  id: number;
  label: string;
  description: string;
  secondaryInfo?: string;
  status?: string;
}

export interface DataSchemaDto {
  entityType: string;
  datasetId: string;
  datasetName?: string;
  fields: DataFieldDto[];
  childCollections: DataCollectionDto[];
}

export interface DataFieldDto {
  name: string;
  type: string;
  label: string;
  displayName?: string;
  group?: string;
  nestedFields?: DataFieldDto[];
}

export interface DataCollectionDto {
  name: string;
  label: string;
  description?: string;
  fields: DataFieldDto[];
}

// Editor State Types
export interface EditorState {
  template: AprtTemplate;
  selectedElementId: string | null;
  zoom: number;
  showGrid: boolean;
  snapToGrid: boolean;
  gridSize: number;
  undoStack: AprtTemplate[];
  redoStack: AprtTemplate[];
  isDirty: boolean;
}

export interface CanvasElement {
  id: string;
  fabricObject: unknown; // fabric.FabricObject - type defined in EditorCanvas
  aprtElement: AprtElement;
}

// Default values
export const defaultStyle: AprtStyle = {
  fontFamily: "Helvetica",
  fontSize: 12,
  fontWeight: "normal",
  fontStyle: "normal",
  color: "#000000",
  textAlign: "left",
  verticalAlign: "top",
  borderWidth: 0,
  borderColor: "#000000",
  borderStyle: "solid",
  padding: 0,
  lineHeight: 1.2,
  opacity: 1,
};

export const defaultImageSettings: AprtImageSettings = {
  fitMode: "contain",
  maintainAspectRatio: true,
  horizontalAlign: "center",
  verticalAlign: "center",
  opacity: 1,
  borderRadius: 0,
  shadow: false,
  flipHorizontal: false,
  flipVertical: false,
};

export const defaultMargins: AprtMargins = {
  top: 20,
  right: 15,
  bottom: 20,
  left: 15,
};

// Default page for new templates
export const defaultPage: AprtPage = {
  id: "page-1",
  name: "Pagina 1",
};

export const defaultTemplate: AprtTemplate = {
  version: "1.0",
  meta: {
    name: "Nuovo Template",
    pageSize: "A4",
    orientation: "portrait",
    margins: defaultMargins,
  },
  resources: {
    fonts: [],
    images: [],
  },
  dataSources: {},
  sections: [],
  pages: [{ ...defaultPage }],
  elements: [],
};

// Page dimensions in mm
export const pageDimensions: Record<
  PageSize,
  { width: number; height: number }
> = {
  A4: { width: 210, height: 297 },
  A3: { width: 297, height: 420 },
  A5: { width: 148, height: 210 },
  Letter: { width: 216, height: 279 },
  Legal: { width: 216, height: 356 },
};

// Helper to get page dimensions considering orientation
export function getPageDimensions(
  size: PageSize,
  orientation: PageOrientation,
): { width: number; height: number } {
  const dims = pageDimensions[size];
  if (orientation === "landscape") {
    return { width: dims.height, height: dims.width };
  }
  return dims;
}

// MM to pixels conversion (assuming 96 DPI for screen)
export const MM_TO_PX = 3.7795275591;

export function mmToPx(mm: number): number {
  return mm * MM_TO_PX;
}

export function pxToMm(px: number): number {
  return px / MM_TO_PX;
}

// ============================================
// Virtual Dataset Types
// ============================================

export interface VirtualDatasetDto {
  id: number;
  nome: string;
  displayName: string;
  descrizione?: string;
  icon: string;
  categoria: string;
  configuration?: VirtualDatasetConfiguration;
  attivo: boolean;
  createdAt?: string;
  updatedAt?: string;
}

export interface VirtualDatasetConfiguration {
  sources: VirtualDatasetSource[];
  relationships: VirtualDatasetRelationship[];
  filters: VirtualDatasetFilter[];
  outputFields: VirtualDatasetOutputField[];
  primarySourceId?: string;
}

export interface VirtualDatasetSource {
  id: string;
  datasetId: string;
  alias: string;
  isPrimary: boolean;
}

export interface VirtualDatasetRelationship {
  id: string;
  fromSourceId: string;
  fromField: string;
  toSourceId: string;
  toField: string;
  joinType: "inner" | "left" | "right";
  label?: string;
}

export interface VirtualDatasetFilter {
  id: string;
  sourceId: string;
  field: string;
  operator:
    | "eq"
    | "neq"
    | "gt"
    | "gte"
    | "lt"
    | "lte"
    | "contains"
    | "startsWith"
    | "endsWith"
    | "isNull"
    | "isNotNull";
  value?: string;
  valueType: "static" | "parameter" | "field";
  logicalOperator: "and" | "or";
  enabled: boolean;
}

export interface VirtualDatasetOutputField {
  id: string;
  sourceId: string;
  fieldName: string;
  alias?: string;
  label?: string;
  group?: string;
  order: number;
  included: boolean;
}

export interface VirtualDatasetValidationResult {
  isValid: boolean;
  errors: string[];
  warnings: string[];
}

export interface CreateVirtualDatasetRequest {
  nome: string;
  displayName: string;
  descrizione?: string;
  icon?: string;
  categoria?: string;
  configuration?: VirtualDatasetConfiguration;
}

export interface UpdateVirtualDatasetRequest {
  nome?: string;
  displayName?: string;
  descrizione?: string;
  icon?: string;
  categoria?: string;
  configuration?: VirtualDatasetConfiguration;
  attivo?: boolean;
}

// Default empty configuration
export const defaultVirtualDatasetConfiguration: VirtualDatasetConfiguration = {
  sources: [],
  relationships: [],
  filters: [],
  outputFields: [],
};
