import { supabase } from '../config/supabase.js';

interface ProjectData {
    name: string;
    client?: string;
    clientName?: string;
    startDate?: string | Date;
    endDate?: string | Date;
    technician?: string;
    responsibleEngineer?: string;
    environment?: string;
    rigorLevel?: string;
    weightKg?: number;
    weightTons?: number;
    status?: string;
}

export const formatProjectResponse = (project: any): any => {
    if (!project) return project;
    if (Array.isArray(project)) {
        return project.map(p => formatProjectResponse(p));
    }
    const clientVal = project.client_name || project.clientName || project.client || '';
    const technicianVal = project.responsible_engineer || project.responsibleEngineer || project.technician || '';
    const environmentVal = project.rigor_level || project.rigorLevel || project.environment || '';

    let weightKgVal: number | null = null;
    if (project.weight_kg !== undefined && project.weight_kg !== null) {
        weightKgVal = Number(project.weight_kg);
    } else if (project.weightKg !== undefined && project.weightKg !== null) {
        weightKgVal = Number(project.weightKg);
    } else if (project.weight_tons !== undefined && project.weight_tons !== null) {
        weightKgVal = Number(project.weight_tons) * 1000;
    } else if (project.weightTons !== undefined && project.weightTons !== null) {
        weightKgVal = Number(project.weightTons) * 1000;
    }

    let weightTonsVal: number | null = null;
    if (weightKgVal !== null) {
        weightTonsVal = weightKgVal / 1000;
    }

    return {
        ...project,
        client: clientVal,
        client_name: clientVal,
        clientName: clientVal,
        technician: technicianVal,
        responsible_engineer: technicianVal,
        responsibleEngineer: technicianVal,
        environment: environmentVal,
        rigor_level: environmentVal,
        rigorLevel: environmentVal,
        weight_kg: weightKgVal,
        weightKg: weightKgVal,
        weight_tons: weightTonsVal,
        weightTons: weightTonsVal
    };
};

export const createProject = async (data: ProjectData & { organizationId?: string }) => {
    const clientVal = data.client || data.clientName || '';
    const technicianVal = data.technician || data.responsibleEngineer || '';
    const environmentVal = data.environment || data.rigorLevel || '';
    const weightKgVal = data.weightKg !== undefined && data.weightKg !== null
        ? Number(data.weightKg)
        : (data.weightTons !== undefined && data.weightTons !== null ? Number(data.weightTons) * 1000 : null);
    const orgId = data.organizationId || 'e47e6210-4879-4e5b-bf21-9285d2713123';

    const insertPayload: any = {
        name: data.name,
        client: clientVal,
        technician: technicianVal,
        environment: environmentVal,
        organization_id: orgId,
        weight_kg: weightKgVal,
        status: data.status || 'active',
        start_date: data.startDate ? new Date(data.startDate).toISOString().split('T')[0] : null,
        end_date: data.endDate ? new Date(data.endDate).toISOString().split('T')[0] : null
    };

    const { data: project, error } = await supabase
        .from('projects')
        .insert(insertPayload)
        .select()
        .single();

    if (error) {
        console.error('Supabase project insert error:', error);
        throw error;
    }
    return formatProjectResponse(project);
};

export const getAllProjects = async (organizationId?: string, isGlobalAdmin?: boolean, status?: string) => {
    try {
        let query = supabase
            .from('projects')
            .select('*, painting_schemes(*)');
        
        if (status) {
            query = query.eq('status', status);
        }

        const { data: projects, error } = await query;
        
        if (error) {
            console.error('Error fetching projects:', error);
            return [];
        }
        
        return formatProjectResponse(projects || []);
    } catch (error) {
        console.error('Error getting projects:', error);
        return [];
    }
};

export const getDashboardProjects = async (organizationId?: string) => {
    try {
        const { data: projects, error } = await supabase
            .from('projects')
            .select('*, painting_schemes(*)');
        
        if (error) return [];
        return formatProjectResponse(projects || []);
    } catch (error) {
        console.error('Error getting dashboard projects:', error);
        return [];
    }
};

export const archiveProject = async (id: string, organizationId?: string, isGlobalAdmin?: boolean) => {
    const { data: project, error: fetchError } = await supabase
        .from('projects')
        .select('*')
        .eq('id', id)
        .single();
        
    if (fetchError || !project) throw new Error('Projeto não encontrado');
    
    if (!isGlobalAdmin && project.organization_id && organizationId && project.organization_id !== organizationId) {
        throw new Error('Acesso negado');
    }
    
    const { data: updated, error } = await supabase
        .from('projects')
        .update({ status: 'archived' })
        .eq('id', id)
        .select()
        .single();
        
    if (error) throw error;
    return formatProjectResponse(updated);
};

export const getProjectById = async (id: string) => {
    const { data, error } = await supabase
        .from('projects')
        .select('*, painting_schemes(*)')
        .eq('id', id)
        .single();
        
    if (error) throw error;
    return formatProjectResponse(data);
};

export const updateProject = async (id: string, data: Partial<ProjectData> & { organizationId?: string }) => {
    const updateData: any = {};
    if (data.name !== undefined) updateData.name = data.name;
    if (data.client !== undefined || data.clientName !== undefined) {
        updateData.client = data.client || data.clientName;
    }
    if (data.technician !== undefined || data.responsibleEngineer !== undefined) {
        updateData.technician = data.technician || data.responsibleEngineer;
    }
    if (data.environment !== undefined || data.rigorLevel !== undefined) {
        updateData.environment = data.environment || data.rigorLevel;
    }
    if (data.startDate !== undefined) {
        updateData.start_date = data.startDate ? new Date(data.startDate).toISOString().split('T')[0] : null;
    }
    if (data.endDate !== undefined) {
        updateData.end_date = data.endDate ? new Date(data.endDate).toISOString().split('T')[0] : null;
    }
    if (data.weightKg !== undefined || data.weightTons !== undefined) {
        updateData.weight_kg = data.weightKg !== undefined && data.weightKg !== null
            ? Number(data.weightKg)
            : (data.weightTons !== undefined && data.weightTons !== null ? Number(data.weightTons) * 1000 : null);
    }
    if (data.status !== undefined) {
        updateData.status = data.status;
    }

    const { data: updated, error } = await supabase
        .from('projects')
        .update(updateData)
        .eq('id', id)
        .select()
        .single();
        
    if (error) throw error;
    return formatProjectResponse(updated);
};

export const deleteProject = async (id: string) => {
    const { error } = await supabase
        .from('projects')
        .delete()
        .eq('id', id);
        
    if (error) throw error;
};

export const getProjectStats = async (projectId: string) => {
    const { data: project, error: projectError } = await supabase
        .from('projects')
        .select('*')
        .eq('id', projectId)
        .single();
        
    if (projectError || !project) return null;
    
    const [schemesRes, inspectionsRes, partsRes] = await Promise.all([
        supabase.from('painting_schemes').select('*').eq('project_id', projectId),
        supabase.from('inspections').select('*').eq('project_id', projectId),
        supabase.from('parts').select('*').eq('project_id', projectId)
    ]);
    
    return {
        project: formatProjectResponse(project),
        schemes: schemesRes.data || [],
        inspections: inspectionsRes.data || [],
        parts: partsRes.data || []
    };
};