import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export interface Property extends RowDataPacket {
  id: number;
  reference: string;
  title: string;
  slug: string;
  description: string | null;
  transaction_type: 'SALE' | 'RENT';
  property_type: 'APARTMENT' | 'VILLA' | 'LAND' | 'OFFICE' | 'SHOP' | 'BUILDING' | 'HOUSE' | 'OTHER' | 'PENTHOUSE' | 'DUPLEX';
  price: number;
  rent_period: 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'YEARLY' | null;
  price_per_night: number | null;
  min_nights: number | null;
  monthly_price: number | null;
  currency: string;
  surface: number;
  rooms: number;
  bedrooms: number;
  bathrooms: number;
  floor: number | null;
  total_floors: number | null;
  construction_year: number | null;
  furnished: boolean;
  is_colocation: boolean;
  is_budget_friendly: boolean;
  duration_type: string | null;
  condition_status: string | null;
  property_status: 'AVAILABLE' | 'RESERVED' | 'SOLD' | 'RENTED' | 'DRAFT' | 'ARCHIVED';
  featured: boolean;
  address: string | null;
  city: string;
  commune: string | null;
  district: string | null;
  latitude: number | null;
  longitude: number | null;
  agent_id: number | null;
  published_at: string | null;
  created_at: string;
  updated_at: string;
  has_guest_toilet: boolean;
  has_private_parking: boolean;
  has_balcony_or_terrace: boolean;
  has_garden: boolean;
  has_pool: boolean;
  pet_friendly: boolean;
  kitchen_type: 'NONE' | 'EQUIPPED' | 'SEMI_EQUIPPED' | 'FURNISHED';
  advance_rent_amount: number;
  security_deposit_amount: number;
  commission_amount: number;
  is_indirect: boolean;
  partner_name: string | null;
  partner_phone: string | null;
  google_maps_link: string | null;
  has_sea_view: boolean;
  is_waterfront: boolean;
}

export interface PropertyFilters {
  page?: number;
  limit?: number;
  search?: string;
  transaction_type?: string;
  property_type?: string;
  property_status?: string;
  category?: string;
  is_colocation?: boolean;
  is_budget_friendly?: boolean;
  city?: string;
  commune?: string;
  district?: string;
  min_price?: number;
  max_price?: number;
  min_surface?: number;
  max_surface?: number;
  rooms?: number;
  bedrooms?: number;
  bathrooms?: number;
  furnished?: boolean;
  featured?: boolean;
  agent_id?: number;
  sort?: string;
  order?: 'ASC' | 'DESC';
  amenity_ids?: number[];
  ids?: number[];
}

export const findAll = async (filters: PropertyFilters) => {
  const page = filters.page || 1;
  const limit = filters.limit || 20;
  const offset = (page - 1) * limit;

  let query = 'SELECT p.* FROM properties p WHERE 1=1';
  let countQuery = 'SELECT COUNT(p.id) as total FROM properties p WHERE 1=1';
  const params: any[] = [];
  const countParams: any[] = [];

  if (filters.search) {
    query += ' AND (p.title LIKE ? OR p.reference LIKE ? OR p.city LIKE ? OR p.address LIKE ?)';
    countQuery += ' AND (p.title LIKE ? OR p.reference LIKE ? OR p.city LIKE ? OR p.address LIKE ?)';
    const searchParam = `%${filters.search}%`;
    params.push(searchParam, searchParam, searchParam, searchParam);
    countParams.push(searchParam, searchParam, searchParam, searchParam);
  }

  if (filters.ids && filters.ids.length > 0) {
    query += ' AND p.id IN (?)';
    countQuery += ' AND p.id IN (?)';
    params.push(filters.ids);
    countParams.push(filters.ids);
  }

  const addFilter = (field: string, value: any, isExact = true, operator = '=') => {
    if (value !== undefined && value !== null && value !== '') {
      query += ` AND p.${field} ${operator} ?`;
      countQuery += ` AND p.${field} ${operator} ?`;
      params.push(value);
      countParams.push(value);
    }
  };

  if (filters.transaction_type) {
    if (filters.transaction_type === 'RENT_LONG') {
      query += ` AND p.transaction_type = 'RENT' AND p.rent_period IN ('MONTHLY', 'YEARLY')`;
      countQuery += ` AND p.transaction_type = 'RENT' AND p.rent_period IN ('MONTHLY', 'YEARLY')`;
    } else if (filters.transaction_type === 'RENT_SHORT') {
      query += ` AND p.transaction_type = 'RENT' AND (p.rent_period IN ('DAILY', 'WEEKLY') OR p.price_per_night IS NOT NULL)`;
      countQuery += ` AND p.transaction_type = 'RENT' AND (p.rent_period IN ('DAILY', 'WEEKLY') OR p.price_per_night IS NOT NULL)`;
    } else {
      query += ` AND p.transaction_type = ?`;
      countQuery += ` AND p.transaction_type = ?`;
      params.push(filters.transaction_type);
      countParams.push(filters.transaction_type);
    }
  }

  if (filters.category) {
    if (filters.category === 'seasonal') {
      query += ` AND (p.rent_period IN ('DAILY', 'WEEKLY') OR p.price_per_night IS NOT NULL)`;
      countQuery += ` AND (p.rent_period IN ('DAILY', 'WEEKLY') OR p.price_per_night IS NOT NULL)`;
    } else if (filters.category === 'budget') {
      query += ` AND (p.is_budget_friendly = 1 OR p.is_colocation = 1 OR (p.transaction_type = 'RENT' AND p.price <= 450000))`;
      countQuery += ` AND (p.is_budget_friendly = 1 OR p.is_colocation = 1 OR (p.transaction_type = 'RENT' AND p.price <= 450000))`;
    } else if (filters.category === 'colocation') {
      query += ` AND p.is_colocation = 1`;
      countQuery += ` AND p.is_colocation = 1`;
    } else if (filters.category === 'standing') {
      query += ` AND (p.transaction_type = 'SALE' OR (p.price > 450000 AND (p.is_colocation = 0 OR p.is_colocation IS NULL)))`;
      countQuery += ` AND (p.transaction_type = 'SALE' OR (p.price > 450000 AND (p.is_colocation = 0 OR p.is_colocation IS NULL)))`;
    }
  }

  if (filters.is_colocation !== undefined) {
    addFilter('is_colocation', filters.is_colocation ? 1 : 0);
  }
  if (filters.is_budget_friendly !== undefined) {
    addFilter('is_budget_friendly', filters.is_budget_friendly ? 1 : 0);
  }

  addFilter('property_type', filters.property_type);
  addFilter('property_status', filters.property_status);
  addFilter('city', filters.city);
  addFilter('commune', filters.commune);
  addFilter('district', filters.district);
  addFilter('agent_id', filters.agent_id);
  
  if (filters.featured !== undefined) {
    addFilter('featured', filters.featured ? 1 : 0);
  }
  if (filters.furnished !== undefined) {
    addFilter('furnished', filters.furnished ? 1 : 0);
  }

  addFilter('price', filters.min_price, false, '>=');
  addFilter('price', filters.max_price, false, '<=');
  addFilter('surface', filters.min_surface, false, '>=');
  addFilter('surface', filters.max_surface, false, '<=');
  addFilter('rooms', filters.rooms, false, '>=');
  addFilter('bedrooms', filters.bedrooms, false, '>=');
  addFilter('bathrooms', filters.bathrooms, false, '>=');

  if (filters.amenity_ids && filters.amenity_ids.length > 0) {
    query += ` AND (SELECT COUNT(*) FROM property_amenities WHERE property_id = p.id AND amenity_id IN (?)) = ?`;
    countQuery += ` AND (SELECT COUNT(*) FROM property_amenities WHERE property_id = p.id AND amenity_id IN (?)) = ?`;
    params.push(filters.amenity_ids, filters.amenity_ids.length);
    countParams.push(filters.amenity_ids, filters.amenity_ids.length);
  }

  const allowedSorts = ['price', 'surface', 'created_at', 'published_at', 'title', 'rooms', 'bedrooms'];
  const sort = filters.sort && allowedSorts.includes(filters.sort) ? filters.sort : 'created_at';
  const order = filters.order === 'ASC' ? 'ASC' : 'DESC';

  query += ` ORDER BY p.${sort} ${order} LIMIT ? OFFSET ?`;
  params.push(limit, offset);

  const [rows] = await pool.query<Property[]>(query, params);
  const [countRows] = await pool.query<RowDataPacket[]>(countQuery, countParams);
  
  const total = countRows[0].total as number;

  return {
    data: rows,
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit)
    }
  };
};

export const findById = async (id: number, connection?: any): Promise<Property | null> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM properties WHERE id = ?', [id]);
  return rows[0] || null;
};
export const getDistinctCities = async (): Promise<string[]> => {
  const [rows] = await pool.query<RowDataPacket[]>('SELECT DISTINCT city FROM properties WHERE property_status = "AVAILABLE" AND city IS NOT NULL ORDER BY city ASC');
  return rows.map(r => r.city);
};

export const getDistinctTypes = async (): Promise<string[]> => {
  const [rows] = await pool.query<RowDataPacket[]>('SELECT DISTINCT property_type FROM properties WHERE property_status = "AVAILABLE" ORDER BY property_type ASC');
  return rows.map(r => r.property_type);
};

export const getDistinctDistricts = async (city?: string): Promise<string[]> => {
  let query = 'SELECT DISTINCT district FROM properties WHERE property_status = "AVAILABLE" AND district IS NOT NULL AND district != ""';
  const params: any[] = [];
  if (city) {
    query += ' AND city = ?';
    params.push(city);
  }
  query += ' ORDER BY district ASC';
  
  const [rows] = await pool.query<RowDataPacket[]>(query, params);
  return rows.map(r => r.district);
};

export const findBySlug = async (slug: string, connection?: any): Promise<Property | null> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM properties WHERE slug = ?', [slug]);
  return rows[0] || null;
};

export const findByReference = async (reference: string, connection?: any): Promise<Property | null> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM properties WHERE reference = ?', [reference]);
  return rows[0] || null;
};

export const create = async (data: any, connection?: any): Promise<number> => {
  const db = connection || pool;
  
  const query = `
    INSERT INTO properties (
      reference, slug, title, description, transaction_type, property_type, price,
      rent_period, price_per_night, min_nights, monthly_price, currency, surface, rooms, bedrooms, bathrooms, floor, total_floors,
      construction_year, furnished, is_colocation, is_budget_friendly, duration_type, condition_status, property_status,
      featured, address, city, commune, district, latitude, longitude, agent_id,
      has_guest_toilet, has_private_parking, has_balcony_or_terrace, has_garden,
      has_pool, pet_friendly, kitchen_type, advance_rent_amount, security_deposit_amount,
      commission_amount, is_indirect, partner_name, partner_phone, google_maps_link,
      has_sea_view, is_waterfront
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;
  
  const [result] = await db.query(query, [
    data.reference, data.slug, data.title, data.description || null, data.transaction_type,
    data.property_type, data.price, data.rent_period || null, data.price_per_night || null,
    data.min_nights !== undefined && data.min_nights !== null ? data.min_nights : 1,
    data.monthly_price || null, data.currency || 'FCFA',
    data.surface, data.rooms || 0, data.bedrooms || 0, data.bathrooms || 0,
    data.floor || null, data.total_floors || null, data.construction_year || null,
    data.furnished ? 1 : 0, data.is_colocation ? 1 : 0, data.is_budget_friendly ? 1 : 0,
    data.duration_type || null, data.condition_status || null,
    data.property_status || 'DRAFT', data.featured ? 1 : 0, data.address || null,
    data.city, data.commune || null, data.district || null,
    data.latitude || null, data.longitude || null, data.agent_id || null,
    data.has_guest_toilet ? 1 : 0, data.has_private_parking ? 1 : 0,
    data.has_balcony_or_terrace ? 1 : 0, data.has_garden ? 1 : 0,
    data.has_pool ? 1 : 0, data.pet_friendly ? 1 : 0,
    data.kitchen_type || 'NONE', data.advance_rent_amount || 0,
    data.security_deposit_amount || 0, data.commission_amount || 0,
    data.is_indirect ? 1 : 0, data.partner_name || null, data.partner_phone || null,
    data.google_maps_link || null, data.has_sea_view ? 1 : 0, data.is_waterfront ? 1 : 0
  ]);
  
  return (result as ResultSetHeader).insertId;
};

export const update = async (id: number, data: any, connection?: any): Promise<void> => {
  const db = connection || pool;
  
  const updates: string[] = [];
  const params: any[] = [];
  
  for (const [key, value] of Object.entries(data)) {
    if (value !== undefined) {
      updates.push(`${key} = ?`);
      // Gérer les booléens
      if (typeof value === 'boolean') {
        params.push(value ? 1 : 0);
      } else {
        params.push(value);
      }
    }
  }
  
  if (updates.length === 0) return;
  
  params.push(id);
  const query = `UPDATE properties SET ${updates.join(', ')} WHERE id = ?`;
  
  await db.query(query, params);
};

export const deleteById = async (id: number, connection?: any): Promise<void> => {
  const db = connection || pool;
  await db.query('DELETE FROM properties WHERE id = ?', [id]);
};

export const findSimilar = async (property: Property, limit: number = 4): Promise<Property[]> => {
  const query = `
    SELECT p.* FROM properties p 
    WHERE p.id != ? 
      AND p.property_status = 'AVAILABLE' 
      AND p.transaction_type = ? 
      AND p.property_type = ? 
      AND p.city = ?
    ORDER BY ABS(p.price - ?) ASC
    LIMIT ?
  `;
  const [rows] = await pool.query(query, [
    property.id, 
    property.transaction_type, 
    property.property_type, 
    property.city, 
    property.price, 
    limit
  ]);
  return rows as Property[];
};
