import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';

export type ActivityCategory = 'system' | 'user' | 'automation';

export interface PropertyActivity {
  id: string;
  property_id: string;
  user_id: string;
  type: 'email' | 'sms' | 'call' | 'system';
  direction: 'inbound' | 'outbound' | 'log';
  subject?: string | null;
  body_preview?: string | null;
  status: string;
  category: ActivityCategory;
  created_at: string;
}

export function usePropertyActivities(propertyId?: string) {
  const queryClient = useQueryClient();
  const { user } = useAuth();

  const activitiesQuery = useQuery({
    queryKey: ['property-activities', propertyId],
    queryFn: async () => {
      if (!propertyId) return [];
      
      const { data, error } = await supabase
        .from('activities')
        .select('*')
        .eq('property_id', propertyId)
        .order('created_at', { ascending: false });

      if (error) throw error;
      return data as PropertyActivity[];
    },
    enabled: !!propertyId,
  });

  const createMutation = useMutation({
    mutationFn: async (activity: Omit<PropertyActivity, 'id' | 'created_at' | 'user_id'>) => {
      if (!user) throw new Error('User not authenticated');
      
      const { data, error } = await supabase
        .from('activities')
        .insert({
          ...activity,
          user_id: user.id,
          contact_id: null, // Property activities don't have a contact
        })
        .select()
        .single();

      if (error) throw error;
      return data as PropertyActivity;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['property-activities'] });
    },
    onError: (error) => {
      toast.error('Failed to log activity: ' + error.message);
    },
  });

  return {
    activities: activitiesQuery.data ?? [],
    isLoading: activitiesQuery.isLoading,
    logActivity: createMutation.mutateAsync,
    isLogging: createMutation.isPending,
    refetch: activitiesQuery.refetch,
  };
}

/**
 * Log a property system activity
 */
export async function logPropertySystemActivity(
  userId: string,
  propertyId: string,
  subject: string,
  bodyPreview?: string
): Promise<void> {
  try {
    const { error } = await supabase.from('activities').insert({
      user_id: userId,
      property_id: propertyId,
      contact_id: null,
      type: 'system',
      direction: 'log',
      subject,
      body_preview: bodyPreview,
      status: 'logged',
      category: 'system',
    });

    if (error) {
      console.error('Failed to log property activity:', error);
    }
  } catch (error) {
    console.error('Failed to log property activity:', error);
  }
}

/**
 * Log property creation
 */
export async function logPropertyCreated(
  userId: string,
  propertyId: string,
  propertyAddress?: string
): Promise<void> {
  const subject = 'Property created';
  const bodyPreview = propertyAddress ? `Address: ${propertyAddress}` : undefined;
  return logPropertySystemActivity(userId, propertyId, subject, bodyPreview);
}

/**
 * Log property update
 */
export async function logPropertyUpdated(
  userId: string,
  propertyId: string,
  changedFields?: string[]
): Promise<void> {
  const subject = 'Property updated';
  const bodyPreview = changedFields?.length 
    ? `Updated fields: ${changedFields.join(', ')}`
    : undefined;
  return logPropertySystemActivity(userId, propertyId, subject, bodyPreview);
}

/**
 * Log property status change
 */
export async function logPropertyStatusChange(
  userId: string,
  propertyId: string,
  oldStatus: string | null,
  newStatus: string
): Promise<void> {
  const subject = oldStatus
    ? `Status changed from "${oldStatus}" to "${newStatus}"`
    : `Status set to "${newStatus}"`;
  return logPropertySystemActivity(userId, propertyId, subject);
}

/**
 * Log document added to property
 */
export async function logPropertyDocumentAdded(
  userId: string,
  propertyId: string,
  documentName: string,
  category?: string
): Promise<void> {
  const subject = 'Document added';
  const bodyPreview = category 
    ? `${documentName} (${category})`
    : documentName;
  return logPropertySystemActivity(userId, propertyId, subject, bodyPreview);
}

/**
 * Log image added to property
 */
export async function logPropertyImageAdded(
  userId: string,
  propertyId: string,
  imageName: string
): Promise<void> {
  const subject = 'Image added';
  return logPropertySystemActivity(userId, propertyId, subject, imageName);
}

/**
 * Log landlord change
 */
export async function logPropertyLandlordChange(
  userId: string,
  propertyId: string,
  landlordName?: string
): Promise<void> {
  const subject = landlordName 
    ? `Landlord assigned: ${landlordName}`
    : 'Landlord removed';
  return logPropertySystemActivity(userId, propertyId, subject);
}
