'use client';

import { createContext, useContext, useState, useCallback } from 'react';

const PropertyContext = createContext();

export const useProperties = () => {
  const context = useContext(PropertyContext);
  if (!context) {
    throw new Error('useProperties must be used within PropertyProvider');
  }
  return context;
};

export const PropertyProvider = ({ children }) => {
  const [properties, setProperties] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const addProperty = useCallback(async (propertyData) => {
    setLoading(true);
    try {
      const newProperty = {
        id: Date.now().toString(),
        ...propertyData,
        createdAt: new Date().toISOString(),
        status: 'available',
        bookings: [],
        commission: {
          rate: propertyData.commissionRate || 5,
          type: propertyData.commissionType || 'from_owner',
          isActive: true
        }
      };
      
      setProperties(prev => [...prev, newProperty]);
      return newProperty;
    } catch (err) {
      setError(err.message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const updateProperty = useCallback(async (id, updates) => {
    setLoading(true);
    try {
      setProperties(prev => 
        prev.map(p => p.id === id ? { ...p, ...updates } : p)
      );
    } catch (err) {
      setError(err.message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const deleteProperty = useCallback(async (id) => {
    setLoading(true);
    try {
      setProperties(prev => prev.filter(p => p.id !== id));
    } catch (err) {
      setError(err.message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const checkAvailability = useCallback((propertyId, startDate, endDate) => {
    const property = properties.find(p => p.id === propertyId);
    if (!property) return false;
    
    return !property.bookings?.some(booking => {
      const bookingStart = new Date(booking.startDate);
      const bookingEnd = new Date(booking.endDate);
      const checkStart = new Date(startDate);
      const checkEnd = new Date(endDate);
      
      return (
        (checkStart >= bookingStart && checkStart <= bookingEnd) ||
        (checkEnd >= bookingStart && checkEnd <= bookingEnd) ||
        (checkStart <= bookingStart && checkEnd >= bookingEnd)
      );
    });
  }, [properties]);

  return (
    <PropertyContext.Provider value={{
      properties,
      loading,
      error,
      addProperty,
      updateProperty,
      deleteProperty,
      checkAvailability
    }}>
      {children}
    </PropertyContext.Provider>
  );
};