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 EventData {
  id: string;
  title: string;
  description: string;
  start_time: string;
  venue: string;
  slug: string;
  organization_id: string;
  seating_map_id?: string | null;
  seating_type?: string;
  created_by?: string;
  created_at?: string;
  end_time?: string;
  is_published?: boolean;
  is_public?: boolean;
  seating_map?: any;
}

export interface EventStats {
  totalRevenue: number;
  netRevenue: number;
  ticketsSold: number;
  ticketsAvailable: number;
  checkedIn: number;
}

export async function loadEventData(eventId: string, organizationId: string): Promise<EventData | null> {
  try {

    // First try to load the event by ID only
    const { data: event, error } = await supabase
      .from('events')
      .select(`
        *,
        seating_maps (
          id,
          name,
          layout_data
        )
      `)
      .eq('id', eventId)
      .single();

    if (error) {

      return null;
    }

    if (!event) {

      return null;
    }

    // Check if user has access to this event
    const { data: { user } } = await supabase.auth.getUser();
    const { data: userProfile } = await supabase
      .from('users')
      .select('role, organization_id')
      .eq('id', user?.id || '')
      .single();
    
    const isAdmin = userProfile?.role === 'admin';
    
    // If not admin and event doesn't belong to user's organization, deny access
    if (!isAdmin && event.organization_id !== userProfile?.organization_id) {

      return null;
    }

    if (error) {

      return null;
    }

    return {
      ...event,
      seating_map: event.seating_maps
    };
  } catch (error) {

    return null;
  }
}

export async function loadEventStats(eventId: string): Promise<EventStats> {
  try {
    // Get ticket sales data
    const { data: tickets, error: ticketsError } = await supabase
      .from('tickets')
      .select(`
        id,
        price,
        checked_in,
        ticket_types (
          id,
          name,
          price,
          quantity_available
        )
      `)
      .eq('event_id', eventId);

    if (ticketsError) {

      return getDefaultStats();
    }

    // Get ticket types for availability calculation
    const { data: ticketTypes, error: typesError } = await supabase
      .from('ticket_types')
      .select('id, quantity_available')
      .eq('event_id', eventId)
      .eq('is_active', true);

    if (typesError) {

      return getDefaultStats();
    }

    // Calculate stats
    const ticketsSold = tickets?.length || 0;
    const totalRevenue = tickets?.reduce((sum, ticket) => sum + (ticket.price || 0), 0) || 0;
    const netRevenue = totalRevenue * 0.97; // Assuming 3% platform fee
    const checkedIn = tickets?.filter(ticket => ticket.checked_in).length || 0;
    const totalCapacity = ticketTypes?.reduce((sum, type) => sum + (type.quantity_available || 0), 0) || 0;
    const ticketsAvailable = totalCapacity - ticketsSold;

    return {
      totalRevenue,
      netRevenue,
      ticketsSold,
      ticketsAvailable,
      checkedIn
    };
  } catch (error) {

    return getDefaultStats();
  }
}

export async function updateEventData(eventId: string, updates: Partial<EventData>): Promise<boolean> {
  try {
    const { error } = await supabase
      .from('events')
      .update(updates)
      .eq('id', eventId);

    if (error) {

      return false;
    }

    return true;
  } catch (error) {

    return false;
  }
}

export function formatEventDate(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit'
  });
}

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

function getDefaultStats(): EventStats {
  return {
    totalRevenue: 0,
    netRevenue: 0,
    ticketsSold: 0,
    ticketsAvailable: 0,
    checkedIn: 0
  };
}