export enum ZoneFormField {
  AreaName = 'name',
  AreaType = 'type',
  AreaId = 'id',
  AreaEnabled = 'enabled',
  AreaDescription = 'description',
  AreaConditions = 'conditions',
  AreaProvinceCode = 'province_code',
  PolygonGeometry = 'geometry',
  PolylineData = 'polyline_data',
  CircleData = 'circle_data',
}

export interface ZoneFormData {
  [ZoneFormField.AreaName]: string;
  [ZoneFormField.AreaType]: number; // API returns number
  [ZoneFormField.AreaId]: string | string[] | null;
  [ZoneFormField.AreaEnabled]: boolean;
  [ZoneFormField.AreaDescription]?: string;
  [ZoneFormField.AreaConditions]?: AreaCondition[];
  [ZoneFormField.AreaProvinceCode]: string | number; // API returns string
  [ZoneFormField.PolygonGeometry]: PolygonGeometry[];
  [ZoneFormField.PolylineData]?: string;
  [ZoneFormField.CircleData]?: CircleGeometry;
}

type MonthRangeCondition = {
  type: 'month_range';
  from: number;
  to: number;
};

type DateRangeCondition = {
  type: 'date_range';
  from: string;
  to: string;
};

type LengthLimitCondition = {
  type: 'length_limit';
  min: number;
  max: number;
};

export type AreaCondition =
  | MonthRangeCondition
  | DateRangeCondition
  | LengthLimitCondition;

export interface ZoneLocationState {
  shape?: number;
  type: 'create' | 'update';
}

export const tagPlusStyle = {
  height: 22,
  // background: "blue",
  borderStyle: 'dashed',
};

export type PolygonGeometry = {
  geometry: number[][];
  id?: string;
};

export type CircleGeometry = {
  center: [number, number];
  radius: number;
  area?: number;
};

// Geometry type mapping with API
export enum GeometryType {
  POLYGON = 1,
  LINESTRING = 2,
  CIRCLE = 3,
}

export interface DrawActionType {
  isDrawing: boolean;
  isModifying: boolean;
}

// Parse MULTIPOINT/WKT for polygon
export const parseMultiPolygonWKT = (wktString: string): number[][][] => {
  if (
    !wktString ||
    typeof wktString !== 'string' ||
    !wktString.startsWith('MULTIPOLYGON')
  ) {
    return [];
  }

  const matched = wktString.match(/MULTIPOLYGON\s*\(\(\((.*)\)\)\)/);
  if (!matched) return [];

  const polygons = matched[1]
    .split(')),((') // chia các polygon
    .map((polygonStr) =>
      polygonStr
        .trim()
        .split(',')
        .map((coordStr) => {
          const [x, y] = coordStr.trim().split(' ').map(Number);
          return [x, y];
        }),
    );
  return polygons;
};

// // Parse LINESTRING WKT
export const parseLineStringWKT = (wkt: string): number[][] => {
  if (!wkt || !wkt.startsWith('LINESTRING')) return [];

  const match = wkt.match(/LINESTRING\s*\((.*)\)/);
  if (!match) return [];

  return match[1].split(',').map((coordStr) => {
    const [x, y] = coordStr.trim().split(' ').map(Number);
    return [x, y]; // [lng, lat]
  });
};

// // Parse POINT WKT
export const parsePointWKT = (wkt: string): [number, number] | null => {
  if (!wkt || !wkt.startsWith('POINT')) return null;

  const match = wkt.match(/POINT\s*\(([-\d.]+)\s+([-\d.]+)\)/);
  if (!match) return null;

  return [parseFloat(match[1]), parseFloat(match[2])]; // [lng, lat]
};

// Format coordinates array to WKT LINESTRING
export const formatLineStringWKT = (coordinates: number[][]): string => {
  const coordStr = coordinates.map((c) => `${c[0]} ${c[1]}`).join(',');
  return `LINESTRING(${coordStr})`;
};

// Format AreaGeometry[] to WKT MULTIPOLYGON string
export const formatPolygonGeometryToWKT = (
  geometries: PolygonGeometry[],
): string => {
  const polygons = geometries.map((g) => g.geometry as number[][]);

  if (polygons.length === 0) return '';

  const polygonStrs = polygons.map((polygon) => {
    const coordStr = polygon.map((c) => `${c[0]} ${c[1]}`).join(',');
    return `(${coordStr})`;
  });

  return `MULTIPOLYGON((${polygonStrs.join('),(')}))`;
};

export const validateGeometry = (value: any) => {
  if (!value || typeof value !== 'string') {
    return Promise.reject('Dữ liệu không hợp lệ!');
  }
  try {
    const text = value.trim();
    const formattedText = text.startsWith('[[') ? text : `[${text}]`;
    const data = JSON.parse(formattedText);

    if (!Array.isArray(data)) {
      return Promise.reject('Dữ liệu không phải mảng!');
    }

    for (const item of data) {
      if (
        !Array.isArray(item) ||
        item.length !== 2 ||
        typeof item[0] !== 'number' ||
        typeof item[1] !== 'number'
      ) {
        return Promise.reject(
          'Mỗi dòng phải là [longitude, latitude] với số thực!',
        );
      }
    }

    return Promise.resolve();
  } catch (e) {
    return Promise.reject('Định dạng JSON không hợp lệ!');
  }
};

export const checkValidateGeometry = (value: string) => {
  if (!value || typeof value !== 'string') {
    return false;
  }
  try {
    const text = value.trim();
    const formattedText = text.startsWith('[[') ? text : `[${text}]`;
    const data = JSON.parse(formattedText);

    if (!Array.isArray(data)) {
      return false;
    }

    for (const item of data) {
      if (
        !Array.isArray(item) ||
        item.length !== 2 ||
        typeof item[0] !== 'number' ||
        typeof item[1] !== 'number'
      ) {
        return false;
      }
    }

    return true;
  } catch (e) {
    return false;
  }
};
