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

export interface Property {
  id: string;
  property_class: string | null;
  business_category: string | null;
  reference: string | null;
  display_address: string | null;
  address_line_1: string | null;
  address_line_2: string | null;
  town_city: string | null;
  county: string | null;
  postcode: string | null;
  country: string | null;
  is_overseas: boolean;
  headline: string | null;
  summary: string | null;
  full_description: string | null;
  branch: string | null;
  lead_staff: string | null;
  price: number | null;
  price_qualifier: string | null;
  valuation_price: number | null;
  minimum_acceptable_price: number | null;
  on_the_market: boolean;
  put_on_market: string | null;
  marketing_tag: string | null;
  virtual_tour_link: string | null;
  virtual_tour_link_2: string | null;
  link_on_website: string | null;
  rightmove_link: string | null;
  zoopla_link: string | null;
  on_the_market_link: string | null;
  epc_rating: string | null;
  epc_band: string | null;
  additional_information: string | null;
  dashboard_note: string | null;
  viewing_arrangements: string | null;
  ground_rent: number | null;
  maintenance_charge: number | null;
  exclude_from_all_portals: boolean;
  exclude_from_website: boolean;
  exclude_from_window_rotator: boolean;
  feature_on_homepage: boolean;
  local_authority: string | null;
  additional_field_1: string | null;
  additional_field_2: string | null;
  property_type: string | null;
  number_of_bedrooms: number | null;
  number_of_receptions: number | null;
  number_of_bathrooms: number | null;
  council_tax_band: string | null;
  landlord_id: string | null;
  status: string | null;
  date_available: string | null;
  deposit: number | null;
  letting_service: string | null;
  letting_fee: number | null;
  management_fee: number | null;
  landlord_payment_frequency: string | null;
  has_gas: boolean;
  gas_certificate_expiry: string | null;
  pat_test_expiry: string | null;
  electricity_certificate_expiry: string | null;
  epc_expiry: string | null;
  insurance_expiry: string | null;
  legionella_risk_assessment_date: string | null;
  smoke_co_alarm_expiry: string | null;
  property_licence_expiry: string | null;
  property_licence_type: string | null;
  property_licence_notes: string | null;
  deleted_at: string | null;
  deleted_by: string | null;
  created_at: string;
  updated_at: string;
  landlord?: {
    id: string;
    first_name: string;
    last_name: string;
    email: string;
    phone: string | null;
    company: string | null;
  } | null;
}

export type PropertyInsert = Omit<Property, 'id' | 'created_at' | 'updated_at' | 'landlord'>;

export function useProperties() {
  return useQuery({
    queryKey: ['properties'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('properties')
        .select(`
          *,
          landlord:contacts!landlord_id(id, first_name, last_name, email, phone, company)
        `)
        .is('deleted_at', null)
        .order('created_at', { ascending: false });

      if (error) throw error;
      return data as Property[];
    },
  });
}

export function useProperty(id: string | undefined) {
  return useQuery({
    queryKey: ['properties', id],
    queryFn: async () => {
      if (!id) return null;
      const { data, error } = await supabase
        .from('properties')
        .select(`
          *,
          landlord:contacts!landlord_id(id, first_name, last_name, email, phone, company)
        `)
        .eq('id', id)
        .single();

      if (error) throw error;
      return data as Property;
    },
    enabled: !!id,
  });
}

export function useLandlordContacts() {
  return useQuery({
    queryKey: ['landlord-contacts'],
    queryFn: async () => {
      // First find the Landlord tag
      const { data: tags, error: tagError } = await supabase
        .from('tags')
        .select('id')
        .ilike('name', 'landlord')
        .limit(1);

      if (tagError) throw tagError;
      
      if (!tags || tags.length === 0) {
        return { contacts: [], hasLandlordTag: false };
      }

      const landlordTagId = tags[0].id;

      // Get contacts with Landlord tag
      const { data: contactTags, error: ctError } = await supabase
        .from('contact_tags')
        .select('contact_id')
        .eq('tag_id', landlordTagId);

      if (ctError) throw ctError;

      if (!contactTags || contactTags.length === 0) {
        return { contacts: [], hasLandlordTag: true };
      }

      const contactIds = contactTags.map(ct => ct.contact_id);

      const { data: contacts, error: contactError } = await supabase
        .from('contacts')
        .select('id, first_name, last_name, email, phone, company')
        .in('id', contactIds)
        .is('deleted_at', null);

      if (contactError) throw contactError;

      return { contacts: contacts || [], hasLandlordTag: true };
    },
  });
}

export function useCreateProperty() {
  const queryClient = useQueryClient();
  const { user } = useAuth();

  return useMutation({
    mutationFn: async (property: Partial<PropertyInsert>) => {
      const { data, error } = await supabase
        .from('properties')
        .insert(property)
        .select()
        .single();

      if (error) throw error;
      return data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['properties'] });
      toast.success('Property created successfully');
      
      // Log activity
      if (user?.id && data?.id) {
        const address = data.display_address || data.address_line_1 || data.reference;
        logPropertyCreated(user.id, data.id, address || undefined);
      }
    },
    onError: (error) => {
      toast.error('Failed to create property: ' + error.message);
    },
  });
}

export function useUpdateProperty() {
  const queryClient = useQueryClient();
  const { user } = useAuth();

  return useMutation({
    mutationFn: async ({ id, _oldStatus, ...property }: Partial<Property> & { id: string; _oldStatus?: string | null }) => {
      const { data, error } = await supabase
        .from('properties')
        .update(property)
        .eq('id', id)
        .select()
        .single();

      if (error) throw error;
      return { data, oldStatus: _oldStatus };
    },
    onSuccess: (result, variables) => {
      queryClient.invalidateQueries({ queryKey: ['properties'] });
      queryClient.invalidateQueries({ queryKey: ['properties', variables.id] });
      queryClient.invalidateQueries({ queryKey: ['property-activities', variables.id] });
      toast.success('Property updated successfully');
      
      // Log activity
      if (user?.id && variables.id) {
        const { _oldStatus, id, ...changedProps } = variables;
        const changedFields = Object.keys(changedProps).filter(k => k !== 'updated_at');
        
        // Log status change if status was updated
        if (changedProps.status && _oldStatus !== changedProps.status) {
          logPropertyStatusChange(user.id, id, _oldStatus || null, changedProps.status);
        } else if (changedFields.length > 0) {
          logPropertyUpdated(user.id, id, changedFields);
        }
      }
    },
    onError: (error) => {
      toast.error('Failed to update property: ' + error.message);
    },
  });
}

export function useDeleteProperty() {
  const queryClient = useQueryClient();
  const { user } = useAuth();

  return useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase
        .from('properties')
        .update({
          deleted_at: new Date().toISOString(),
          deleted_by: user?.id,
        })
        .eq('id', id);

      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['properties'] });
      toast.success('Property deleted successfully');
    },
    onError: (error) => {
      toast.error('Failed to delete property: ' + error.message);
    },
  });
}

export function usePropertyAttachments(propertyId: string | undefined, category?: string) {
  return useQuery({
    queryKey: ['property-attachments', propertyId, category],
    queryFn: async () => {
      if (!propertyId) return [];
      
      let query = supabase
        .from('attachments')
        .select('*')
        .eq('entity_type', 'property')
        .eq('entity_id', propertyId)
        .order('created_at', { ascending: false });

      if (category) {
        query = query.eq('category', category);
      }

      const { data, error } = await query;
      if (error) throw error;
      return data;
    },
    enabled: !!propertyId,
  });
}
