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

export interface EmailTemplate {
  id: string;
  name: string;
  subject: string;
  body: string;
  description?: string | null;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

export interface Business {
  name: string;
  location?: string | null;
  address?: string | null;
  city?: string | null;
  state?: string | null;
  postal_code?: string | null;
  country?: string | null;
  phone?: string | null;
  email?: string | null;
  website?: string | null;
  owner_name?: string | null;
  owner_email?: string | null;
  owner_phone?: string | null;
}

export type CustomField = Tables<'custom_fields'>;
export type ContactCustomValue = Tables<'contact_custom_values'>;

// Base template variables
export const BASE_TEMPLATE_VARIABLES = [
  { key: '{{business.name}}', label: 'Business Name', category: 'Business' },
  { key: '{{business.phone}}', label: 'Business Phone', category: 'Business' },
  { key: '{{business.email}}', label: 'Business Email', category: 'Business' },
  { key: '{{business.website}}', label: 'Business Website', category: 'Business' },
  { key: '{{business.address}}', label: 'Business Address', category: 'Business' },
  { key: '{{business.city}}', label: 'Business City', category: 'Business' },
  { key: '{{business.state}}', label: 'Business State', category: 'Business' },
  { key: '{{business.postal_code}}', label: 'Postal Code', category: 'Business' },
  { key: '{{business.country}}', label: 'Country', category: 'Business' },
  { key: '{{business.owner_name}}', label: 'Owner Name', category: 'Owner' },
  { key: '{{business.owner_email}}', label: 'Owner Email', category: 'Owner' },
  { key: '{{business.owner_phone}}', label: 'Owner Phone', category: 'Owner' },
  { key: '{{contact.first_name}}', label: 'Contact First Name', category: 'Contact' },
  { key: '{{contact.last_name}}', label: 'Contact Last Name', category: 'Contact' },
  { key: '{{contact.email}}', label: 'Contact Email', category: 'Contact' },
  { key: '{{contact.phone}}', label: 'Contact Phone', category: 'Contact' },
  { key: '{{contact.company}}', label: 'Contact Company', category: 'Contact' },
];

// Build template variables including custom fields
export function buildTemplateVariables(customFields: CustomField[] = []) {
  const customFieldVars = customFields.map(field => ({
    key: `{{custom.${field.name}}}`,
    label: field.label,
    category: 'Custom Fields'
  }));
  
  return [...BASE_TEMPLATE_VARIABLES, ...customFieldVars];
}

// Legacy export for backwards compatibility
export const TEMPLATE_VARIABLES = BASE_TEMPLATE_VARIABLES;

// Replace template variables with actual values
export function replaceTemplateVariables(
  template: string,
  business?: Business | null,
  contact?: { first_name?: string; last_name?: string; email?: string; phone?: string; company?: string } | null,
  customValues?: { field_name: string; value: string | null }[]
): string {
  let result = template;
  
  if (business) {
    result = result
      .replace(/\{\{business\.name\}\}/g, business.name || '')
      .replace(/\{\{business\.phone\}\}/g, business.phone || '')
      .replace(/\{\{business\.email\}\}/g, business.email || '')
      .replace(/\{\{business\.website\}\}/g, business.website || '')
      .replace(/\{\{business\.address\}\}/g, business.address || '')
      .replace(/\{\{business\.city\}\}/g, business.city || '')
      .replace(/\{\{business\.state\}\}/g, business.state || '')
      .replace(/\{\{business\.postal_code\}\}/g, business.postal_code || '')
      .replace(/\{\{business\.country\}\}/g, business.country || '')
      .replace(/\{\{business\.owner_name\}\}/g, business.owner_name || '')
      .replace(/\{\{business\.owner_email\}\}/g, business.owner_email || '')
      .replace(/\{\{business\.owner_phone\}\}/g, business.owner_phone || '');
  }

  if (contact) {
    result = result
      .replace(/\{\{contact\.first_name\}\}/g, contact.first_name || '')
      .replace(/\{\{contact\.last_name\}\}/g, contact.last_name || '')
      .replace(/\{\{contact\.email\}\}/g, contact.email || '')
      .replace(/\{\{contact\.phone\}\}/g, contact.phone || '')
      .replace(/\{\{contact\.company\}\}/g, contact.company || '');
  }

  // Replace custom field variables
  if (customValues) {
    for (const cv of customValues) {
      const regex = new RegExp(`\\{\\{custom\\.${cv.field_name}\\}\\}`, 'g');
      result = result.replace(regex, cv.value || '');
    }
  }

  // Clean up any remaining custom field placeholders
  result = result.replace(/\{\{custom\.[^}]+\}\}/g, '');

  return result;
}

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

  const templatesQuery = useQuery({
    queryKey: ['email-templates'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('email_templates')
        .select('*')
        .order('created_at', { ascending: false });

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

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

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

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

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

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase
        .from('email_templates')
        .delete()
        .eq('id', id);

      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['email-templates'] });
      toast.success('Template deleted successfully');
    },
    onError: (error) => {
      toast.error('Failed to delete template: ' + error.message);
    },
  });

  return {
    templates: templatesQuery.data ?? [],
    isLoading: templatesQuery.isLoading,
    createTemplate: createMutation.mutateAsync,
    updateTemplate: updateMutation.mutateAsync,
    deleteTemplate: deleteMutation.mutateAsync,
    isCreating: createMutation.isPending,
    isUpdating: updateMutation.isPending,
    isDeleting: deleteMutation.isPending,
  };
}
