import { createClient } from '@supabase/supabase-js';
import type { Database } from './database.types';

const supabase = createClient<Database>(
  import.meta.env.PUBLIC_SUPABASE_URL,
  import.meta.env.PUBLIC_SUPABASE_ANON_KEY
);

export interface TicketType {
  id: string;
  name: string;
  description: string;
  price: number;
  quantity_available: number;
  quantity_sold: number;
  is_active: boolean;
  event_id: string;
  sort_order: number;
  created_at: string;
  updated_at?: string;
}

export interface TicketTypeFormData {
  name: string;
  description: string;
  price: number;
  quantity_available: number;
  is_active: boolean;
}

export interface TicketSale {
  id: string;
  event_id: string;
  ticket_type_id: string;
  price: number;
  checked_in: boolean;
  purchaser_email: string;
  purchaser_name: string;
  created_at: string;
  uuid: string;
  ticket_types: {
    name: string;
    price: number;
  };
}

export async function loadTicketTypes(eventId: string): Promise<TicketType[]> {
  try {
    const { data: ticketTypes, error } = await supabase
      .from('ticket_types')
      .select('*')
      .eq('event_id', eventId)
      .order('sort_order', { ascending: true });

    if (error) {

      return [];
    }

    return ticketTypes || [];
  } catch (error) {

    return [];
  }
}

export async function createTicketType(eventId: string, ticketTypeData: TicketTypeFormData): Promise<TicketType | null> {
  try {
    // Get the next sort order
    const { data: existingTypes } = await supabase
      .from('ticket_types')
      .select('sort_order')
      .eq('event_id', eventId)
      .order('sort_order', { ascending: false })
      .limit(1);

    const nextSortOrder = existingTypes?.[0]?.sort_order ? existingTypes[0].sort_order + 1 : 1;

    const { data: ticketType, error } = await supabase
      .from('ticket_types')
      .insert({
        ...ticketTypeData,
        event_id: eventId,
        sort_order: nextSortOrder
      })
      .select()
      .single();

    if (error) {

      return null;
    }

    return ticketType;
  } catch (error) {

    return null;
  }
}

export async function updateTicketType(ticketTypeId: string, updates: Partial<TicketTypeFormData>): Promise<boolean> {
  try {
    const { error } = await supabase
      .from('ticket_types')
      .update(updates)
      .eq('id', ticketTypeId);

    if (error) {

      return false;
    }

    return true;
  } catch (error) {

    return false;
  }
}

export async function deleteTicketType(ticketTypeId: string): Promise<boolean> {
  try {
    // Check if there are any tickets sold for this type
    const { data: tickets } = await supabase
      .from('tickets')
      .select('id')
      .eq('ticket_type_id', ticketTypeId)
      .limit(1);

    if (tickets && tickets.length > 0) {
      throw new Error('Cannot delete ticket type with existing sales');
    }

    const { error } = await supabase
      .from('ticket_types')
      .delete()
      .eq('id', ticketTypeId);

    if (error) {

      return false;
    }

    return true;
  } catch (error) {

    return false;
  }
}

export async function toggleTicketTypeStatus(ticketTypeId: string, isActive: boolean): Promise<boolean> {
  return updateTicketType(ticketTypeId, { is_active: isActive });
}

export async function loadTicketSales(eventId: string, filters?: {
  ticketTypeId?: string;
  searchTerm?: string;
  status?: string;
}): Promise<TicketSale[]> {
  try {
    let query = supabase
      .from('tickets')
      .select(`
        id,
        event_id,
        ticket_type_id,
        price,
        refund_status,
        checked_in,
        purchaser_email,
        purchaser_name,
        created_at,
        uuid,
        ticket_types (
          name,
          price
        )
      `)
      .eq('event_id', eventId)
      .order('created_at', { ascending: false });

    // Apply filters
    if (filters?.ticketTypeId) {
      query = query.eq('ticket_type_id', filters.ticketTypeId);
    }

    if (filters?.status) {
      if (filters.status === 'confirmed') {
        query = query.or('refund_status.is.null,refund_status.eq.null');
      } else if (filters.status === 'refunded') {
        query = query.eq('refund_status', 'completed');
      }
    }

    if (filters?.searchTerm) {
      query = query.or(`purchaser_email.ilike.%${filters.searchTerm}%,purchaser_name.ilike.%${filters.searchTerm}%`);
    }

    const { data: tickets, error } = await query;

    if (error) {

      return [];
    }

    return tickets || [];
  } catch (error) {

    return [];
  }
}

export async function checkInTicket(ticketId: string): Promise<boolean> {
  try {
    const { error } = await supabase
      .from('tickets')
      .update({ checked_in: true })
      .eq('id', ticketId);

    if (error) {

      return false;
    }

    return true;
  } catch (error) {

    return false;
  }
}

export async function refundTicket(ticketId: string): Promise<boolean> {
  try {
    const { error } = await supabase
      .from('tickets')
      .update({ refund_status: 'completed' })
      .eq('id', ticketId);

    if (error) {

      return false;
    }

    return true;
  } catch (error) {

    return false;
  }
}

export function formatTicketPrice(cents: number): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
  }).format(cents / 100);
}

export function calculateTicketTypeStats(ticketType: TicketType, sales: TicketSale[]): {
  sold: number;
  available: number;
  revenue: number;
} {
  const typeSales = sales.filter(sale => sale.ticket_type_id === ticketType.id && sale.status === 'confirmed');
  const sold = typeSales.length;
  const available = ticketType.quantity - sold;
  const revenue = typeSales.reduce((sum, sale) => sum + sale.price_paid, 0);

  return { sold, available, revenue };
}