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

export interface Business {
  id: string;
  name: string;
  location?: string | null;
  address?: string | null;
  city?: string | null;
  state?: string | null;
  postal_code?: string | null;
  country?: string | null;
  industries?: string[] | null;
  phone?: string | null;
  email?: string | null;
  website?: string | null;
  owner_name?: string | null;
  owner_email?: string | null;
  owner_phone?: string | null;
  logo_url?: string | null;
  preferred_theme?: string | null;
  preferred_accent_color?: string | null;
  preferred_layout?: string | null;
  created_at: string;
  updated_at: string;
}

export interface BusinessEmailConfig {
  id: string;
  business_id?: string | null;
  provider: string;
  smtp_host?: string | null;
  smtp_port?: number | null;
  smtp_username?: string | null;
  smtp_password?: string | null;
  smtp_encryption?: string | null;
  from_email?: string | null;
  from_name?: string | null;
  reply_to_email?: string | null;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

export function useBusiness() {
  const queryClient = useQueryClient();

  const businessQuery = useQuery({
    queryKey: ['business'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('business')
        .select('*')
        .limit(1)
        .maybeSingle();

      if (error) throw error;
      return data as Business | null;
    },
  });

  const createMutation = useMutation({
    mutationFn: async (business: Partial<Business>) => {
      const { data, error } = await supabase
        .from('business')
        .insert(business as any)
        .select()
        .single();

      if (error) throw error;
      return data as Business;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['business'] });
      toast.success('Business created successfully');
    },
    onError: (error) => {
      toast.error('Failed to create business: ' + error.message);
    },
  });

  const updateMutation = useMutation({
    mutationFn: async ({ id, ...updates }: Partial<Business> & { id: string }) => {
      const { data, error } = await supabase
        .from('business')
        .update(updates as any)
        .eq('id', id)
        .select()
        .single();

      if (error) throw error;
      return data as Business;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['business'] });
      toast.success('Business updated successfully');
    },
    onError: (error) => {
      toast.error('Failed to update business: ' + error.message);
    },
  });

  return {
    business: businessQuery.data,
    isLoading: businessQuery.isLoading,
    createBusiness: createMutation.mutateAsync,
    updateBusiness: updateMutation.mutateAsync,
    isCreating: createMutation.isPending,
    isUpdating: updateMutation.isPending,
  };
}

export function useBusinessEmailConfig(businessId?: string) {
  const queryClient = useQueryClient();

  const configQuery = useQuery({
    queryKey: ['business-email-config', businessId],
    queryFn: async () => {
      if (!businessId) return null;
      
      const { data, error } = await supabase
        .from('business_email_config')
        .select('*')
        .eq('business_id', businessId)
        .maybeSingle();

      if (error) throw error;
      return data as BusinessEmailConfig | null;
    },
    enabled: !!businessId,
  });

  const upsertMutation = useMutation({
    mutationFn: async (config: Partial<BusinessEmailConfig> & { business_id: string }) => {
      // Check if config exists
      const { data: existing } = await supabase
        .from('business_email_config')
        .select('id')
        .eq('business_id', config.business_id)
        .maybeSingle();

      if (existing) {
        const { data, error } = await supabase
          .from('business_email_config')
          .update(config as any)
          .eq('id', existing.id)
          .select()
          .single();
        if (error) throw error;
        return data as BusinessEmailConfig;
      } else {
        const { data, error } = await supabase
          .from('business_email_config')
          .insert(config as any)
          .select()
          .single();
        if (error) throw error;
        return data as BusinessEmailConfig;
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['business-email-config'] });
      toast.success('Email configuration saved successfully');
    },
    onError: (error) => {
      toast.error('Failed to save email configuration: ' + error.message);
    },
  });

  return {
    emailConfig: configQuery.data,
    isLoading: configQuery.isLoading,
    saveEmailConfig: upsertMutation.mutateAsync,
    isSaving: upsertMutation.isPending,
  };
}
