import axios from 'axios';
import { getHttpClient, apiErrorMessage } from './http';
import { cleanCrmText } from '../utils/propertyDisplay';

function isMissingEndpoint(err: unknown): boolean {
  return axios.isAxiosError(err) && (err.response?.status === 404 || err.response?.status === 405);
}

export interface PropertyFormOptions {
  propertyTypes: { id: number; name: string; name_slug?: string | null }[];
  /** Subtypes are scoped by property_type_id — filter in UI when type changes. */
  propertySubTypes: { id: number; name: string; property_type_id: number }[];
  features: { id: number; name: string }[];
  statuses: { id: number; name: string; color?: string | null }[];
  defaultStatusId: number | null;
  /** Achat / Location / Location saisonnière (CRM vocation). */
  vocations: { id: number; name: string; name_slug?: string | null }[];
  /** Account settings devise (ISO code, e.g. TND, SDG). */
  currency?: string | null;
}

export interface PropertyListItem {
  id: number;
  reference: string;
  /** CRM business reference (« Ref254Ta ») — shown next to `reference`. */
  referenceImmo?: string | null;
  title: string;
  price: number | null;
  currency?: string | null;
  statusId?: number | null;
  statusName?: string | null;
  projectName?: string | null;
  typeId?: number | null;
  typeName?: string | null;
  blockId?: number | null;
  blockName?: string | null;
  thumbnailUrl?: string | null;
  updatedAt?: string | null;
  rooms?: number | null;
  /** Bedrooms (chambres) — preferred over total pieces for list display */
  bedrooms?: number | null;
  floor?: string | number | null;
  surface?: number | null;
  /** False when this agent may see the bien but not edit it. */
  canUpdate?: boolean;
  canPublish?: boolean;
}

export interface PropertyListMeta {
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
}

export interface PropertyGalleryImage {
  id: number;
  url: string;
  fullUrl: string;
  position: number;
  /** Cover photo (CRM « image principale »). */
  isMain?: boolean;
}

export interface PropertyDetail {
  id: number;
  reference: string;
  /** CRM business reference (« Ref254Ta ») — shown next to `reference`. */
  referenceImmo?: string | null;
  title: string;
  description?: string | null;
  price: number | null;
  /** Property currency, or the account devise when the property has none. */
  currency?: string | null;
  surface?: number | null;
  rooms?: number | null;
  bedrooms?: number | null;
  bathrooms?: number | null;
  city?: string | null;
  address?: string | null;
  statusId?: number | null;
  statusName?: string | null;
  statusColor?: string | null;
  propertyTypeId?: number | null;
  propertyTypeName?: string | null;
  propertySubTypeId?: number | null;
  propertySubTypeName?: string | null;
  /** Legacy CRM may attach several subtypes (ManyToMany). */
  propertySubTypeNames?: string[];
  projectId?: number | null;
  projectName?: string | null;
  vocationId?: number | null;
  vocationName?: string | null;
  paysId?: number | null;
  gouvernoratId?: number | null;
  delegationId?: number | null;
  localiteId?: number | null;
  districtId?: number | null;
  features: { id: number; name: string }[];
  gallery: PropertyGalleryImage[];
  thumbnailUrl?: string | null;
  updatedAt?: string | null;
  canUpdate: boolean;
  /** CRM « publish » right (agents may need approval). */
  canPublish?: boolean;
  /** Published on the agency website. */
  published?: boolean;
  /** Published on the portal feeds. */
  publishedFeed?: boolean;
  /** Per-portal feed choices — editable in the CRM only. */
  publishedFeedAdvanced?: boolean;
  /** Owner / tenant contact — CRM gates it by agent role + settings. */
  canSeeOwner?: boolean;
  ownerClientId?: number | null;
  ownerName?: string | null;
  ownerPhone?: string | null;
  /** Owner exists on the bien but his client record is private for this agent. */
  ownerHidden?: boolean;
  /** property = bien record, transaction / rent = derived from the sale or the rental. */
  ownerSource?: 'property' | 'transaction' | 'rent' | 'topay' | null;
  tenantClientId?: number | null;
  tenantName?: string | null;
  tenantPhone?: string | null;
  tenantHidden?: boolean;
  tenantSource?: 'property' | 'transaction' | 'rent' | 'topay' | null;
  /** Active rent contract (état de loyer) when the bien is rented. */
  rental?: {
    active: boolean;
    startDate?: string | null;
    endDate?: string | null;
    amount?: number | null;
    reference?: string | null;
  } | null;
  contactName?: string | null;
  contactPhone?: string | null;
  keysAtAgency?: boolean | null;
  /** Exact address + map: hidden when the CRM flags the bien and the user cannot edit it. */
  canSeeExactLocation?: boolean;
  latitude?: number | null;
  longitude?: number | null;
  /** Coarse centre + uncertainty radius sent instead of the exact point. */
  approxLatitude?: number | null;
  approxLongitude?: number | null;
  approxRadiusKm?: number | null;
  /** masked = exact point hidden by rights, geo = bien without GPS centred on its locality. */
  approxSource?: 'masked' | 'geo' | null;
  /** Geo level used for the fallback centre (quartier / localité / délégation…). */
  approxPlace?: string | null;
  /** Informations supplémentaires */
  floor?: string | number | null;
  yearBuilt?: string | number | null;
  coOwnershipCharge?: number | null;
  caution?: number | null;
  conditions?: string | null;
  note?: string | null;
  mark?: string | null;
}

export interface CreatedProperty {
  id: number;
  reference: string;
  title: string;
  price: number | null;
}

export interface PropertyFilterOption {
  id: number;
  name: string;
}

export interface PropertyFilterSubTypeOption extends PropertyFilterOption {
  property_type_id: number;
}

export interface PropertyFilterLookups {
  statuses: PropertyFilterOption[];
  projects: PropertyFilterOption[];
  types: PropertyFilterOption[];
  /** Subtypes scoped by property_type_id (CRM parity). */
  subTypes?: PropertyFilterSubTypeOption[];
  blocks?: PropertyFilterOption[];
  vocations?: Array<PropertyFilterOption & { name_slug?: string | null }>;
  agents?: PropertyFilterOption[];
  currency?: string;
}

export interface PropertyListFilters {
  q?: string;
  statusId?: number | null;
  statusGroup?: 'available' | 'unavailable' | null;
  vocationId?: number | null;
  projectId?: number | null;
  typeId?: number | null;
  typeIds?: number[];
  /** Property subtype (sous-type) */
  subTypeId?: number | null;
  subTypeIds?: number[];
  macroType?: 'appartement' | 'maison' | 'bureau' | 'terrain' | 'immeuble' | null;
  blockId?: number | null;
  minPrice?: number | null;
  maxPrice?: number | null;
  /** Filter by total pieces / bedrooms */
  rooms?: number | null;
  /** Filter by floor (étage) */
  floor?: number | null;
  /** CRM offer picker: disponibles only */
  availableOnly?: boolean;
  gouvernoratId?: number | null;
  delegationId?: number | null;
  localiteId?: number | null;
  districtId?: number | null;
  geoLabel?: string | null;
  agentId?: number | null;
  reference?: string | null;
  perPage?: number;
}

export interface PropertiesPage {
  data: PropertyListItem[];
  meta: PropertyListMeta;
  filters: PropertyFilterLookups;
}

const PER_PAGE = 20;
const EMPTY_LOOKUPS: PropertyFilterLookups = {
  statuses: [],
  projects: [],
  types: [],
  subTypes: [],
  blocks: [],
  vocations: [],
  agents: [],
  currency: 'TND',
};

function normalizeFilterLookups(raw?: PropertyFilterLookups | null): PropertyFilterLookups {
  const subRaw = (raw?.subTypes ?? []) as Array<{
    id?: number;
    name?: string;
    property_type_id?: number;
    propertyTypeId?: number;
  }>;
  return {
    statuses: raw?.statuses ?? [],
    projects: raw?.projects ?? [],
    types: raw?.types ?? [],
    subTypes: subRaw
      .map((st) => ({
        id: Number(st.id ?? 0),
        name: String(st.name ?? ''),
        property_type_id: Number(st.property_type_id ?? st.propertyTypeId ?? 0),
      }))
      .filter((st) => st.id > 0 && st.property_type_id > 0),
    blocks: raw?.blocks ?? [],
    vocations: (raw?.vocations ?? []).map((v) => ({
      id: Number(v.id),
      name: String(v.name ?? ''),
      name_slug: (v as { name_slug?: string | null }).name_slug ?? null,
    })),
    agents: raw?.agents ?? [],
    currency: raw?.currency ?? 'TND',
  };
}

function legacyMediaBase(baseURL?: string): string {
  if (!baseURL) return '';
  try {
    return new URL(baseURL).origin;
  } catch {
    return '';
  }
}

function mapLegacyProperty(row: Record<string, unknown>, mediaBase: string): PropertyListItem {
  const paths = (row.images_paths ?? row.imagesPaths ?? null) as Record<string, string> | null;
  const rawThumb = paths?.small ?? paths?.large ?? null;
  const thumbnailUrl = rawThumb
    ? rawThumb.startsWith('http')
      ? rawThumb
      : `${mediaBase}${rawThumb}`
    : null;
  const statut = (row.statut ?? null) as Record<string, unknown> | null;
  const projet = (row.projet ?? null) as Record<string, unknown> | null;

  return {
    id: Number(row.id ?? 0),
    reference: String(row.reference ?? row.reference_immo ?? ''),
    title: cleanCrmText(String(row.name ?? row.title ?? '')) ?? '',
    price: row.prix != null ? Number(row.prix) : null,
    statusName: statut?.name != null ? String(statut.name) : null,
    projectName: projet?.name != null ? String(projet.name) : null,
    thumbnailUrl,
    updatedAt: null,
    rooms: row.rooms != null ? Number(row.rooms) : row.totalPieces != null ? Number(row.totalPieces) : null,
    bedrooms:
      row.bedrooms != null
        ? Number(row.bedrooms)
        : row.chambres != null
          ? Number(row.chambres)
          : null,
    floor:
      row.floor != null
        ? (row.floor as string | number)
        : row.etage != null
          ? (row.etage as string | number)
          : null,
    surface: row.surface != null ? Number(row.surface) : null,
  };
}

async function fetchPropertiesPageLegacyFallback(
  page: number,
  filters: PropertyListFilters,
): Promise<PropertiesPage> {
  const { client } = await getHttpClient();
  const params: Record<string, unknown> = { page, num_items_per_page: PER_PAGE };
  const reference = filters.reference?.trim() || filters.q?.trim();
  if (reference) params.reference = reference;
  if (filters.projectId) params.projet = filters.projectId;
  if (filters.rooms != null) params.chambre = filters.rooms;
  if (filters.floor != null) params.etage = filters.floor;
  if (filters.availableOnly) params.available = true;
  // Legacy search has no « every status but Disponible » filter.
  if (filters.statusGroup === 'available') params.status = [2];
  else if (filters.statusId) params.status = [filters.statusId];
  if (filters.vocationId) params.vocations = [filters.vocationId];
  const typeIds = filters.typeIds?.length ? filters.typeIds : filters.typeId ? [filters.typeId] : [];
  if (typeIds.length) params.property_types = typeIds;
  const subTypeIds = filters.subTypeIds?.length
    ? filters.subTypeIds
    : filters.subTypeId
      ? [filters.subTypeId]
      : [];
  if (subTypeIds.length) params.sub_types = subTypeIds;
  if (filters.gouvernoratId) params.gouvernorats = [filters.gouvernoratId];
  if (filters.delegationId) params.delegations = [filters.delegationId];
  if (filters.localiteId) params.localites = [filters.localiteId];
  if (filters.minPrice) params.prix_min = filters.minPrice;
  if (filters.maxPrice) params.prix_max = filters.maxPrice;
  const { data } = await client.get<Record<string, unknown>>('/properties/list', { params });
  const items = Array.isArray(data.items) ? (data.items as Record<string, unknown>[]) : [];
  const total = Number(data.totalCount ?? data.total_count ?? items.length);
  const mediaBase = legacyMediaBase(client.defaults.baseURL ?? undefined);
  return {
    data: items.map((row) => mapLegacyProperty(row, mediaBase)),
    meta: {
      current_page: page,
      last_page: Math.max(1, Math.ceil(total / PER_PAGE)),
      per_page: PER_PAGE,
      total,
    },
    filters: EMPTY_LOOKUPS,
  };
}

export async function fetchPropertiesPage(
  page = 1,
  filters: PropertyListFilters = {},
): Promise<PropertiesPage> {
  const { client, config } = await getHttpClient();

  try {
    const { data } = await client.get<{
      data: PropertyListItem[];
      meta: PropertyListMeta;
      filters?: PropertyFilterLookups;
    }>('/mobile/properties', {
      params: {
        page,
        per_page: Math.min(Math.max(filters.perPage ?? PER_PAGE, 1), 50),
        q: filters.q?.trim() || undefined,
        reference: filters.reference?.trim() || undefined,
        status_id: filters.statusId || undefined,
        status_group: filters.statusGroup || undefined,
        vocation_id: filters.vocationId || undefined,
        project_id: filters.projectId || undefined,
        type_id: filters.typeId || undefined,
        type_ids: filters.typeIds?.length ? filters.typeIds.join(',') : undefined,
        sub_type_id: filters.subTypeId || undefined,
        sub_type_ids: filters.subTypeIds?.length ? filters.subTypeIds.join(',') : undefined,
        block_id: filters.blockId || undefined,
        min_price: filters.minPrice || undefined,
        max_price: filters.maxPrice || undefined,
        rooms: filters.rooms ?? undefined,
        floor: filters.floor ?? undefined,
        available_only: filters.availableOnly ? 1 : undefined,
        gouvernorat_id: filters.gouvernoratId || undefined,
        delegation_id: filters.delegationId || undefined,
        localite_id: filters.localiteId || undefined,
        district_id: filters.districtId || undefined,
        agent_id: filters.agentId || undefined,
      },
    });
    return {
      data: (data.data ?? []).map((p) => ({
        ...p,
        title: cleanCrmText(p.title) ?? p.title,
        rooms: p.rooms ?? null,
        bedrooms: p.bedrooms ?? null,
        floor: p.floor ?? null,
        surface: p.surface ?? null,
        currency: p.currency ?? data.filters?.currency ?? 'TND',
        blockId: p.blockId ?? null,
        blockName: p.blockName ?? null,
        typeId: p.typeId ?? null,
        typeName: p.typeName ?? null,
      })),
      meta: data.meta,
      filters: normalizeFilterLookups(data.filters),
    };
  } catch (err) {
    // Old CRM without /mobile/properties deployed yet
    if (config.mode === 'legacy' && isMissingEndpoint(err)) {
      return fetchPropertiesPageLegacyFallback(page, filters);
    }
    throw err;
  }
}

/** Imported CRM text can carry « [:fr]…[:] » language blocks — display one language. */
function cleanDetailText(detail: PropertyDetail): PropertyDetail {
  return {
    ...detail,
    title: cleanCrmText(detail.title) ?? detail.title,
    description: cleanCrmText(detail.description),
    address: cleanCrmText(detail.address),
    city: cleanCrmText(detail.city),
  };
}

export async function fetchPropertyDetail(id: number): Promise<PropertyDetail> {
  const { client, config } = await getHttpClient();
  try {
    const { data } = await client.get<{ data: PropertyDetail }>(`/mobile/properties/${id}`);
    return cleanDetailText(data.data);
  } catch (err) {
    if (config.mode === 'legacy' && isMissingEndpoint(err)) {
      throw new Error('Mise à jour du CRM requise pour voir le détail du bien.');
    }
    throw err;
  }
}

export async function updateProperty(
  id: number,
  payload: {
    title?: string;
    price?: number | null;
    description?: string | null;
    status_id?: number | null;
    published?: boolean;
    published_feed?: boolean;
    property_type_id?: number | null;
    property_sub_type_id?: number | null;
    vocation_id?: number | null;
    project_id?: number | null;
    feature_ids?: number[];
    surface?: number | null;
    rooms?: number | null;
    bedrooms?: number | null;
    bathrooms?: number | null;
    city?: string | null;
    address?: string | null;
    pays_id?: number | null;
    gouvernorat_id?: number | null;
    delegation_id?: number | null;
    localite_id?: number | null;
    district_id?: number | null;
  },
): Promise<PropertyDetail> {
  const { client, config } = await getHttpClient();
  try {
    const { data } = await client.patch<{ data: PropertyDetail }>(`/mobile/properties/${id}`, payload);
    return cleanDetailText(data.data);
  } catch (err) {
    if (config.mode === 'legacy' && isMissingEndpoint(err)) {
      throw new Error('Mise à jour du CRM requise pour modifier le bien.');
    }
    throw err;
  }
}

export async function fetchPropertyFormOptions(): Promise<PropertyFormOptions> {
  const { client, config } = await getHttpClient();
  try {
    const { data } = await client.get<{ data: PropertyFormOptions }>('/mobile/property-form-options');
    const opts = data.data;
    const rawSubs = (opts.propertySubTypes ?? []) as Array<{
      id: number;
      name: string;
      property_type_id?: number;
      propertyTypeId?: number;
    }>;
    return {
      propertyTypes: (opts.propertyTypes ?? []).map((pt) => ({
        id: Number(pt.id),
        name: pt.name,
        name_slug: pt.name_slug ?? null,
      })),
      propertySubTypes: rawSubs
        .map((s) => ({
          id: Number(s.id),
          name: s.name,
          property_type_id: Number(s.property_type_id ?? s.propertyTypeId ?? 0),
        }))
        .filter((s) => s.id > 0 && s.property_type_id > 0),
      features: opts.features ?? [],
      statuses: opts.statuses ?? [],
      defaultStatusId: opts.defaultStatusId ?? null,
      vocations: opts.vocations ?? [],
      currency: opts.currency ?? null,
    };
  } catch (err) {
    if (config.mode === 'legacy' && isMissingEndpoint(err)) {
      return {
        propertyTypes: [],
        propertySubTypes: [],
        features: [],
        statuses: [],
        defaultStatusId: null,
        vocations: [],
        currency: null,
      };
    }
    throw err;
  }
}

export async function createProperty(payload: {
  title: string;
  price?: number | null;
  type_name?: string;
  property_type_id?: number;
  property_sub_type_id?: number | null;
  vocation_id?: number | null;
  feature_names?: string[];
  feature_ids?: number[];
  description?: string | null;
  surface?: number | null;
  rooms?: number | null;
  bedrooms?: number | null;
  bathrooms?: number | null;
  city?: string | null;
  address?: string | null;
  pays_id?: number | null;
  gouvernorat_id?: number | null;
  delegation_id?: number | null;
  localite_id?: number | null;
  district_id?: number | null;
  owner_id?: number | null;
}): Promise<CreatedProperty> {
  const { client, config } = await getHttpClient();
  let data: { data: Record<string, unknown> };
  try {
    ({ data } = await client.post<{ data: Record<string, unknown> }>('/mobile/properties', payload));
  } catch (err) {
    if (config.mode === 'legacy' && isMissingEndpoint(err)) {
      throw new Error('Mise à jour du CRM requise pour créer un bien depuis le mobile.');
    }
    throw err;
  }
  const p = data.data;
  return {
    id: Number(p.id),
    reference: String(p.reference ?? ''),
    title: String(p.title ?? ''),
    price: p.price != null ? Number(p.price) : null,
  };
}

export interface PropertyPhotoLogoOptions {
  addLogo: boolean;
  logoOnAll: boolean;
  logoFirstFull: boolean;
  batchIndex: number;
}

export async function uploadPropertyPhoto(
  propertyId: number,
  uri: string,
  fileName: string,
  mimeType: string,
  logo?: PropertyPhotoLogoOptions,
): Promise<void> {
  const { client, config } = await getHttpClient();

  const safeName = fileName.toLowerCase().endsWith('.jpg') || fileName.toLowerCase().endsWith('.jpeg')
    ? fileName
    : `${fileName.replace(/\.[^.]+$/, '') || 'photo'}.jpg`;
  const form = new FormData();
  form.append('file', {
    uri,
    name: safeName,
    type: mimeType || 'image/jpeg',
  } as unknown as Blob);
  if (logo) {
    form.append('add_logo', logo.addLogo ? '1' : '0');
    form.append('logo_on_all', logo.logoOnAll ? '1' : '0');
    form.append('logo_first_full', logo.logoFirstFull ? '1' : '0');
    form.append('batch_index', String(logo.batchIndex));
  }

  try {
    // Do not set Content-Type manually — RN needs the multipart boundary.
    await client.post(`/mobile/properties/${propertyId}/photos`, form, {
      timeout: 120000,
    });
  } catch (err) {
    if (config.mode === 'legacy' && isMissingEndpoint(err)) {
      throw new Error('Mise à jour du CRM requise pour envoyer des photos.');
    }
    throw err;
  }
}

/** Route not deployed yet (HTML 404/405), as opposed to a JSON « photo introuvable ». */
function isMissingPhotoRoute(err: unknown): boolean {
  if (!isMissingEndpoint(err) || !axios.isAxiosError(err)) return false;
  const data = err.response?.data as { message?: unknown } | string | null | undefined;
  if (data && typeof data === 'object' && typeof data.message === 'string') {
    return /no route found|method not allowed/i.test(data.message);
  }
  return true;
}

/** Removes one gallery photo; returns the refreshed detail (main photo moves to the next one). */
export async function deletePropertyPhoto(
  propertyId: number,
  imageId: number,
): Promise<PropertyDetail> {
  const { client } = await getHttpClient();
  try {
    const { data } = await client.delete<{ data: PropertyDetail }>(
      `/mobile/properties/${propertyId}/photos/${imageId}`,
    );
    return cleanDetailText(data.data);
  } catch (err) {
    if (isMissingPhotoRoute(err)) {
      throw new Error('Mise à jour du CRM requise pour gérer les photos.');
    }
    throw err;
  }
}

/** Saves the gallery order — the first id becomes the main photo. */
export async function orderPropertyPhotos(
  propertyId: number,
  ids: number[],
): Promise<PropertyDetail> {
  const { client } = await getHttpClient();
  try {
    const { data } = await client.post<{ data: PropertyDetail }>(
      `/mobile/properties/${propertyId}/photos/order`,
      { ids },
    );
    return cleanDetailText(data.data);
  } catch (err) {
    if (isMissingPhotoRoute(err)) {
      throw new Error('Mise à jour du CRM requise pour gérer les photos.');
    }
    throw err;
  }
}

export { apiErrorMessage };
