'use server';

import { createClient } from '@/lib/supabase/server';
import { customAlphabet } from 'nanoid';
import { revalidatePath } from 'next/cache';

const generateSlug = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 8);

export interface ShippingOption {
    name: string;
    price: number;
}

export interface SampleSize {
    cl: number;
    glassCost: number;
}

export interface CreateSplitData {
    bottleId: string;
    totalVolume?: number;
    hostShare?: number;
    priceBottle: number;
    sampleSizes: SampleSize[];
    shippingOptions: ShippingOption[];
}

export interface SplitDetails {
    id: string;
    publicSlug: string;
    bottleId: string;
    hostId: string;
    totalVolume: number;
    hostShare: number;
    priceBottle: number;
    sampleSizes: SampleSize[];
    shippingOptions: ShippingOption[];
    isActive: boolean;
    createdAt: string;
    bottle: {
        id: string;
        name: string;
        distillery?: string;
        imageUrl?: string;
        abv?: number;
        age?: number;
    };
    available: number;
    taken: number;
    reserved: number;
    remaining: number;
    participants: Array<{
        id: string;
        userId: string;
        username?: string;
        amountCl: number;
        shippingMethod: string;
        totalCost: number;
        status: string;
        createdAt: string;
    }>;
}

/**
 * Create a new bottle split
 */
export async function createSplit(data: CreateSplitData): Promise<{
    success: boolean;
    splitId?: string;
    slug?: string;
    error?: string;
}> {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        // Verify bottle belongs to user
        const { data: bottle, error: bottleError } = await supabase
            .from('bottles')
            .select('id, user_id')
            .eq('id', data.bottleId)
            .eq('user_id', user.id)
            .single();

        if (bottleError || !bottle) {
            return { success: false, error: 'Flasche nicht gefunden' };
        }

        // Check if split already exists for this bottle
        const { data: existingSplit } = await supabase
            .from('bottle_splits')
            .select('id')
            .eq('bottle_id', data.bottleId)
            .single();

        if (existingSplit) {
            return { success: false, error: 'Diese Flasche hat bereits einen aktiven Split' };
        }

        const slug = generateSlug();

        // Convert sample sizes to DB format
        const sampleSizesDb = data.sampleSizes.map(s => ({
            cl: s.cl,
            glass_cost: s.glassCost,
        }));

        const { data: split, error } = await supabase
            .from('bottle_splits')
            .insert({
                bottle_id: data.bottleId,
                host_id: user.id,
                total_volume: data.totalVolume || 70,
                host_share: data.hostShare || 10,
                price_bottle: data.priceBottle,
                sample_sizes: sampleSizesDb,
                shipping_options: data.shippingOptions,
                public_slug: slug,
            })
            .select('id')
            .single();

        if (error) {
            console.error('Create split error:', error);
            return { success: false, error: 'Split konnte nicht erstellt werden' };
        }

        revalidatePath(`/bottles/${data.bottleId}`);
        revalidatePath('/splits/manage');

        return { success: true, splitId: split.id, slug };
    } catch (error) {
        console.error('createSplit error:', error);
        return { success: false, error: 'Unerwarteter Fehler' };
    }
}

/**
 * Get split details by public slug
 */
export async function getSplitBySlug(slug: string): Promise<{
    success: boolean;
    data?: SplitDetails;
    error?: string;
}> {
    const supabase = await createClient();

    try {
        const { data: split, error } = await supabase
            .from('bottle_splits')
            .select(`
                id,
                public_slug,
                bottle_id,
                host_id,
                total_volume,
                host_share,
                price_bottle,
                sample_sizes,
                shipping_options,
                is_active,
                created_at,
                bottles (id, name, distillery, image_url, abv, age)
            `)
            .eq('public_slug', slug)
            .eq('is_active', true)
            .single();

        if (error || !split) {
            return { success: false, error: 'Split nicht gefunden' };
        }

        // Get participants
        const { data: participants } = await supabase
            .from('split_participants')
            .select(`
                id,
                user_id,
                amount_cl,
                shipping_method,
                total_cost,
                status,
                created_at,
                profiles:user_id (username)
            `)
            .eq('split_id', split.id)
            .order('created_at', { ascending: true });

        // Calculate availability
        const available = split.total_volume - split.host_share;
        let taken = 0;
        let reserved = 0;

        (participants || []).forEach(p => {
            if (['APPROVED', 'PAID', 'SHIPPED'].includes(p.status)) {
                taken += p.amount_cl;
            } else if (p.status === 'PENDING') {
                reserved += p.amount_cl;
            }
        });

        const remaining = available - taken - reserved;
        const bottle = split.bottles as any;

        if (!bottle) {
            console.error(`Split ${slug} has no associated bottle data.`);
            return { success: false, error: 'Flaschendaten für diesen Split fehlen.' };
        }

        // Convert sample sizes from DB format
        const sampleSizes = ((split.sample_sizes as any[]) || []).map(s => ({
            cl: s.cl,
            glassCost: s.glass_cost,
        }));

        return {
            success: true,
            data: {
                id: split.id,
                publicSlug: split.public_slug,
                bottleId: split.bottle_id,
                hostId: split.host_id,
                totalVolume: split.total_volume,
                hostShare: split.host_share,
                priceBottle: split.price_bottle,
                sampleSizes,
                shippingOptions: split.shipping_options as ShippingOption[],
                isActive: split.is_active,
                createdAt: split.created_at,
                bottle: {
                    id: bottle.id,
                    name: bottle.name || 'Unbekannte Flasche',
                    distillery: bottle.distillery || 'Unbekannte Destillerie',
                    imageUrl: bottle.image_url,
                    abv: bottle.abv,
                    age: bottle.age,
                },
                available,
                taken,
                reserved,
                remaining,
                participants: (participants || []).map(p => ({
                    id: p.id,
                    userId: p.user_id,
                    username: (p.profiles as any)?.username,
                    amountCl: p.amount_cl,
                    shippingMethod: p.shipping_method,
                    totalCost: p.total_cost,
                    status: p.status,
                    createdAt: p.created_at,
                })),
            },
        };
    } catch (error) {
        console.error('getSplitBySlug error:', error);
        return { success: false, error: 'Unerwarteter Fehler' };
    }
}

/**
 * Request a slot in a split
 */
export async function requestSlot(
    splitId: string,
    amountCl: number,
    shippingMethod: string
): Promise<{ success: boolean; error?: string }> {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        // Get split details
        const { data: split, error: splitError } = await supabase
            .from('bottle_splits')
            .select('*')
            .eq('id', splitId)
            .eq('is_active', true)
            .single();

        if (splitError || !split) {
            return { success: false, error: 'Split nicht gefunden' };
        }

        if (split.host_id === user.id) {
            return { success: false, error: 'Du kannst nicht an deinem eigenen Split teilnehmen' };
        }

        // Check if already participating
        const { data: existing } = await supabase
            .from('split_participants')
            .select('id, status')
            .eq('split_id', splitId)
            .eq('user_id', user.id)
            .single();

        if (existing && !['REJECTED'].includes(existing.status)) {
            return { success: false, error: 'Du nimmst bereits an diesem Split teil' };
        }

        // Find the glass cost for this size
        const sampleSizes = (split.sample_sizes as any[]) || [];
        const sizeOption = sampleSizes.find(s => s.cl === amountCl);
        if (!sizeOption) {
            return { success: false, error: 'Ungültige Größe' };
        }

        // Calculate availability
        const { data: participants } = await supabase
            .from('split_participants')
            .select('amount_cl, status')
            .eq('split_id', splitId);

        const available = split.total_volume - split.host_share;
        let takenAndReserved = 0;

        (participants || []).forEach(p => {
            if (['APPROVED', 'PAID', 'SHIPPED', 'PENDING'].includes(p.status)) {
                takenAndReserved += p.amount_cl;
            }
        });

        const remaining = available - takenAndReserved;

        // Calculate total cost
        const pricePerCl = split.price_bottle / split.total_volume;
        const glassCost = sizeOption.glass_cost;
        const shippingOption = (split.shipping_options as ShippingOption[])
            .find(s => s.name === shippingMethod);
        const shippingCost = shippingOption?.price || 0;
        const totalCost = (pricePerCl * amountCl) + glassCost + shippingCost;

        const status = remaining >= amountCl ? 'PENDING' : 'WAITLIST';

        if (existing) {
            const { error } = await supabase
                .from('split_participants')
                .update({
                    amount_cl: amountCl,
                    shipping_method: shippingMethod,
                    total_cost: totalCost,
                    status,
                    created_at: new Date().toISOString(),
                })
                .eq('id', existing.id);

            if (error) {
                return { success: false, error: 'Anfrage fehlgeschlagen' };
            }
        } else {
            const { error } = await supabase
                .from('split_participants')
                .insert({
                    split_id: splitId,
                    user_id: user.id,
                    amount_cl: amountCl,
                    shipping_method: shippingMethod,
                    total_cost: totalCost,
                    status,
                });

            if (error) {
                console.error('Insert participant error:', error);
                return { success: false, error: 'Anfrage fehlgeschlagen' };
            }
        }

        revalidatePath(`/splits/${split.public_slug}`);

        return { success: true };
    } catch (error) {
        console.error('requestSlot error:', error);
        return { success: false, error: 'Unerwarteter Fehler' };
    }
}

/**
 * Update participant status (host only)
 */
export async function updateParticipantStatus(
    participantId: string,
    newStatus: 'APPROVED' | 'REJECTED' | 'PAID' | 'SHIPPED'
): Promise<{ success: boolean; error?: string }> {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        const { data: participant, error: findError } = await supabase
            .from('split_participants')
            .select(`
                id,
                split_id,
                bottle_splits!inner (host_id, public_slug)
            `)
            .eq('id', participantId)
            .single();

        if (findError || !participant) {
            return { success: false, error: 'Teilnehmer nicht gefunden' };
        }

        const split = participant.bottle_splits as any;
        if (split.host_id !== user.id) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        const { error } = await supabase
            .from('split_participants')
            .update({ status: newStatus })
            .eq('id', participantId);

        if (error) {
            return { success: false, error: 'Status konnte nicht aktualisiert werden' };
        }

        revalidatePath(`/splits/${split.public_slug}`);
        revalidatePath('/splits/manage');

        return { success: true };
    } catch (error) {
        console.error('updateParticipantStatus error:', error);
        return { success: false, error: 'Unerwarteter Fehler' };
    }
}

/**
 * Get all splits hosted by current user
 */
export async function getHostSplits(): Promise<{
    success: boolean;
    splits?: Array<{
        id: string;
        slug: string;
        bottleName: string;
        bottleImage?: string;
        totalVolume: number;
        hostShare: number;
        participantCount: number;
        pendingCount: number;
        isActive: boolean;
    }>;
    error?: string;
}> {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        const { data: splits, error } = await supabase
            .from('bottle_splits')
            .select(`
                id,
                public_slug,
                total_volume,
                host_share,
                is_active,
                bottles (name, image_url),
                split_participants (status)
            `)
            .eq('host_id', user.id)
            .order('created_at', { ascending: false });

        if (error) {
            return { success: false, error: 'Fehler beim Laden' };
        }

        return {
            success: true,
            splits: (splits || []).map(s => {
                const participants = (s.split_participants as any[]) || [];
                const bottle = s.bottles as any;
                return {
                    id: s.id,
                    slug: s.public_slug,
                    bottleName: bottle?.name || 'Unbekannt',
                    bottleImage: bottle?.image_url,
                    totalVolume: s.total_volume,
                    hostShare: s.host_share,
                    participantCount: participants.filter(p =>
                        ['APPROVED', 'PAID', 'SHIPPED'].includes(p.status)
                    ).length,
                    pendingCount: participants.filter(p => p.status === 'PENDING').length,
                    isActive: s.is_active,
                };
            }),
        };
    } catch (error) {
        console.error('getHostSplits error:', error);
        return { success: false, error: 'Unerwarteter Fehler' };
    }
}

/**
 * Get all splits the current user is participating in
 */
export async function getParticipatingSplits(): Promise<{
    success: boolean;
    splits?: Array<{
        id: string;
        slug: string;
        bottleName: string;
        bottleImage?: string;
        totalVolume: number;
        hostShare: number;
        participantCount: number;
        amountCl: number;
        status: string;
        isActive: boolean;
        hostName?: string;
    }>;
    error?: string;
}> {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        const { data: participations, error } = await supabase
            .from('split_participants')
            .select(`
                amount_cl,
                status,
                bottle_splits!inner (
                    id,
                    public_slug,
                    total_volume,
                    host_share,
                    is_active,
                    host_id,
                    bottles (name, image_url),
                    profiles:host_id (username)
                )
            `)
            .eq('user_id', user.id)
            .order('created_at', { ascending: false });

        if (error) {
            console.error('getParticipatingSplits error:', error);
            return { success: false, error: 'Fehler beim Laden' };
        }

        return {
            success: true,
            splits: (participations || []).map(p => {
                const split = p.bottle_splits as any;
                const bottle = split.bottles as any;
                const hostProfile = split.profiles as any;

                return {
                    id: split.id,
                    slug: split.public_slug,
                    bottleName: bottle?.name || 'Unbekannt',
                    bottleImage: bottle?.image_url,
                    totalVolume: split.total_volume,
                    hostShare: split.host_share,
                    participantCount: 0, // We could count this but might be overkill for list view
                    amountCl: p.amount_cl,
                    status: p.status,
                    isActive: split.is_active,
                    hostName: hostProfile?.username || 'Host',
                };
            }),
        };
    } catch (error) {
        console.error('getParticipatingSplits unexpected error:', error);
        return { success: false, error: 'Unerwarteter Fehler' };
    }
}
export async function generateForumExport(splitId: string): Promise<{
    success: boolean;
    text?: string;
    error?: string;
}> {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        const { data: split, error } = await supabase
            .from('bottle_splits')
            .select(`
                *,
                bottles (name, distillery),
                split_participants (
                    amount_cl,
                    status,
                    profiles:user_id (username)
                )
            `)
            .eq('id', splitId)
            .eq('host_id', user.id)
            .single();

        if (error || !split) {
            return { success: false, error: 'Split nicht gefunden' };
        }

        const bottle = split.bottles as any;
        const participants = split.split_participants as any[] || [];
        const shippingOptions = split.shipping_options as ShippingOption[];
        const sampleSizes = (split.sample_sizes as any[]) || [];

        const pricePerCl = split.price_bottle / split.total_volume;

        // Build price list for all sizes
        const priceList = sampleSizes.map(s => {
            const price = (pricePerCl * s.cl + s.glass_cost).toFixed(2);
            return `${s.cl}cl: ${price}€`;
        }).join(' | ');

        let text = `[b]${bottle.name}${bottle.distillery ? ` (${bottle.distillery})` : ''} Split[/b]\n\n`;
        text += `Flaschenpreis: ${split.price_bottle.toFixed(2)}€\n`;
        text += `${priceList}\n`;
        text += `Versand: ${shippingOptions.map(s => `${s.name} (${s.price.toFixed(2)}€)`).join(', ')}\n\n`;
        text += `[b]Teilnehmer:[/b]\n`;
        text += `1. Host (${split.host_share}cl)\n`;

        participants.forEach((p, i) => {
            const profile = p.profiles as any;
            const statusLabel = p.status === 'PENDING' ? ' - Ausstehend' :
                p.status === 'APPROVED' ? ' - Bestätigt' :
                    p.status === 'PAID' ? ' - Bezahlt' :
                        p.status === 'SHIPPED' ? ' - Versendet' : '';
            text += `${i + 2}. ${profile?.username || 'Anonym'} (${p.amount_cl}cl)${statusLabel}\n`;
        });

        return { success: true, text };
    } catch (error) {
        console.error('generateForumExport error:', error);
        return { success: false, error: 'Unerwarteter Fehler' };
    }
}

/**
 * Close/deactivate a split
 */
export async function closeSplit(splitId: string): Promise<{
    success: boolean;
    error?: string;
}> {
    const supabase = await createClient();

    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
            return { success: false, error: 'Nicht autorisiert' };
        }

        const { error } = await supabase
            .from('bottle_splits')
            .update({ is_active: false })
            .eq('id', splitId)
            .eq('host_id', user.id);

        if (error) {
            return { success: false, error: 'Split konnte nicht geschlossen werden' };
        }

        revalidatePath('/splits/manage');

        return { success: true };
    } catch (error) {
        console.error('closeSplit error:', error);
        return { success: false, error: 'Unerwarteter Fehler' };
    }
}
/**
 * Get all active splits for public discovery
 */
export async function getActiveSplits() {
    const supabase = await createClient();

    try {
        const { data: splits, error } = await supabase
            .from('bottle_splits')
            .select(`
                id,
                public_slug,
                total_volume,
                host_share,
                is_active,
                bottles (name, image_url, distillery),
                profiles:host_id (username)
            `)
            .eq('is_active', true)
            .order('created_at', { ascending: false });

        if (error) {
            console.error('getActiveSplits error:', error);
            return { success: false, error: 'Fehler beim Laden' };
        }

        return {
            success: true,
            splits: (splits || []).map(s => {
                const bottle = s.bottles as any;
                const hostProfile = s.profiles as any;
                return {
                    id: s.id,
                    slug: s.public_slug,
                    bottleName: bottle?.name || 'Unbekannt',
                    bottleImage: bottle?.image_url,
                    distillery: bottle?.distillery,
                    totalVolume: s.total_volume,
                    hostShare: s.host_share,
                    hostName: hostProfile?.username || 'Host',
                };
            }),
        };
    } catch (error) {
        console.error('getActiveSplits unexpected error:', error);
        return { success: false, error: 'Unerwarteter Fehler' };
    }
}
