import { Request, Response } from 'express';
import { supabase } from '../config/supabase.js';
import path from 'path';
import fs from 'fs';
import os from 'os';

const DEFAULT_SETTINGS = {
    settingsId: 'global',
    appName: 'GPI',
    appSubtitle: 'Gestão de Pintura Industrial'
};

export const getSettings = async (req: Request, res: Response) => {
    try {
        const { data: settings, error } = await supabase
            .from('system_settings')
            .select('*')
            .eq('key', 'global')
            .single();

        if (settings && settings.value) {
            const val = typeof settings.value === 'string' ? JSON.parse(settings.value) : settings.value;
            return res.json({
                settingsId: 'global',
                appName: val.appName || DEFAULT_SETTINGS.appName,
                appSubtitle: val.appSubtitle || DEFAULT_SETTINGS.appSubtitle,
                appLogoUrl: val.appLogoUrl || ''
            });
        }

        const { data: fallback } = await supabase
            .from('system_settings')
            .select('*')
            .limit(1)
            .single();

        if (fallback) {
            if (fallback.value) {
                const val = typeof fallback.value === 'string' ? JSON.parse(fallback.value) : fallback.value;
                return res.json({
                    settingsId: 'global',
                    appName: val.appName || DEFAULT_SETTINGS.appName,
                    appSubtitle: val.appSubtitle || DEFAULT_SETTINGS.appSubtitle,
                    appLogoUrl: val.appLogoUrl || ''
                });
            }
            return res.json({
                settingsId: 'global',
                appName: fallback.app_name || DEFAULT_SETTINGS.appName,
                appSubtitle: fallback.app_subtitle || DEFAULT_SETTINGS.appSubtitle,
                appLogoUrl: fallback.app_logo_url || ''
            });
        }

        res.json(DEFAULT_SETTINGS);
    } catch (error) {
        console.error('Error fetching system settings:', error);
        res.json(DEFAULT_SETTINGS);
    }
};

export const updateSettings = async (req: Request, res: Response) => {
    try {
        const { appName, appSubtitle, appLogoUrl } = req.body;
        const orgId = req.appUser?.organizationId || 'e47e6210-4879-4e5b-bf21-9285d2713123';

        const { data: existing } = await supabase
            .from('system_settings')
            .select('*')
            .eq('key', 'global')
            .single();

        const valPayload = {
            appName: appName || DEFAULT_SETTINGS.appName,
            appSubtitle: appSubtitle || DEFAULT_SETTINGS.appSubtitle,
            appLogoUrl: appLogoUrl || '',
            updatedBy: req.appUser?.email || 'admin',
            updatedAt: new Date().toISOString()
        };

        if (!existing) {
            const { error } = await supabase
                .from('system_settings')
                .insert({
                    organization_id: orgId,
                    key: 'global',
                    value: valPayload
                });

            if (error) throw error;
        } else {
            const { error } = await supabase
                .from('system_settings')
                .update({
                    value: valPayload,
                    updated_at: new Date().toISOString()
                })
                .eq('id', existing.id);

            if (error) throw error;
        }

        console.log(`⚙️ System Settings updated by ${req.appUser?.email}`);
        res.json({
            settingsId: 'global',
            appName,
            appSubtitle,
            appLogoUrl
        });
    } catch (error) {
        console.error('Error updating system settings:', error);
        res.status(500).json({ error: 'Erro ao atualizar configurações do sistema' });
    }
};

export const serveLogo = async (req: Request, res: Response) => {
    try {
        const { filename } = req.params as { filename: string };
        const tmpPath = path.join(os.tmpdir(), 'uploads', filename);
        const localPath = path.join(process.cwd(), 'uploads', filename);

        if (fs.existsSync(tmpPath)) {
            return res.sendFile(tmpPath);
        } else if (fs.existsSync(localPath)) {
            return res.sendFile(localPath);
        } else {
            res.setHeader('Content-Type', 'image/svg+xml');
            res.setHeader('Cache-Control', 'public, max-age=86400');
            return res.send(`
                <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
                    <rect width="100" height="100" rx="20" fill="#6366f1"/>
                    <text x="50%" y="55%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-size="48" font-weight="900" fill="#ffffff">G</text>
                </svg>
            `);
        }
    } catch (error) {
        console.error('Error serving logo:', error);
        res.status(500).json({ error: 'Erro ao processar imagem' });
    }
};

export const uploadLogo = async (req: Request, res: Response) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: 'Nenhum arquivo enviado.' });
        }

        const fileUrl = `/api/system-settings/logo-image/${req.file.filename}`;
        res.json({ url: fileUrl });
    } catch (error) {
        console.error('Error uploading logo:', error);
        res.status(500).json({ error: 'Erro ao fazer upload do logo.' });
    }
};

export const getGlobalUsers = async (req: Request, res: Response) => {
    try {
        const { data: users, error } = await supabase
            .from('users')
            .select('*')
            .order('created_at', { ascending: false });
        
        if (error && error.code !== '42P01') throw error;
        
        const mappedUsers = (users || []).map((u: any) => ({
            ...u,
            _id: u.id,
            id: u.id,
            name: u.name || u.email?.split('@')[0] || 'Usuário',
            email: u.email || '',
            role: u.role || 'user',
            isBanned: u.is_banned ?? false,
            createdAt: u.created_at
        }));

        res.json(mappedUsers);
    } catch (error) {
        console.error('Error getting global users:', error);
        res.status(500).json({ error: 'Erro ao buscar usuários globais.' });
    }
};

export const getGlobalOrganizations = async (req: Request, res: Response) => {
    try {
        const { data: organizations, error } = await supabase
            .from('organizations')
            .select('*');
        
        if (error && error.code !== '42P01') throw error;
        
        if (!organizations || organizations.length === 0) {
            return res.json([]);
        }
        
        const orgsWithMembers = await Promise.all(
            organizations.map(async (org) => {
                let members: any[] = [];
                try {
                    const { data: mems } = await supabase
                        .from('user_organizations')
                        .select('*')
                        .eq('organization_id', org.id);
                    members = mems || [];
                } catch {
                    members = [];
                }
                    
                return {
                    ...org,
                    _id: org.id,
                    id: org.id,
                    isBanned: org.is_banned ?? false,
                    members: members.map((m: any) => ({
                        userId: m.user_id || m.id,
                        name: m.name || m.user_name || 'Membro',
                        email: m.email || m.user_email || '',
                        role: m.role || 'user',
                        isBanned: m.is_banned ?? false
                    })),
                    memberCount: members?.length || 0
                };
            })
        );
        
        res.json(orgsWithMembers);
    } catch (error) {
        console.error('Error getting global organizations:', error);
        res.status(500).json({ error: 'Erro ao buscar organizações globais.' });
    }
};

export const toggleOrganizationBan = async (req: Request, res: Response) => {
    try {
        const { organizationId, isBanned } = req.body;

        if (!organizationId) {
            return res.status(400).json({ error: 'ID da organização é obrigatório.' });
        }

        const { data: org, error } = await supabase
            .from('organizations')
            .update({ is_banned: isBanned })
            .eq('id', organizationId)
            .select()
            .single();

        if (error) throw error;
        console.log(`Organization ${organizationId} ban status set to ${isBanned} by ${req.appUser?.email}`);
        res.json(org);
    } catch (error) {
        console.error('Error toggling organization ban:', error);
        res.status(500).json({ error: 'Erro ao atualizar status da organização.' });
    }
};