import { faker } from "@faker-js/faker"
import { type ColorOption, getRandomColor } from "./utils"
import { useAuthStore } from '@/stores/auth';
import axios from 'axios';


type PercentageDirection = "up" | "down"

interface Item {
	id: string
	code: string
	fgcolor: string
	bgcolor: string
	image?: string
	name: string
	adjective?: string
	amount: string
	percentage: number
	direction: PercentageDirection
}

export async function getCompany(count: number, colorOption: ColorOption): Promise<Item[]> {
    try {
        // Fetch data from the API
        const response = await axios.get('/api/state/agreements', {
            headers: {
                'Content-Type': 'multipart/form-data',
                Authorization: `Bearer ${useAuthStore().user.token}`,
            },
        });

        console.log(response.data)

        // Initialize an array to hold the result
        let result: Item[] = [];

        // Check if response.data is an array
        if (Array.isArray(response.data)) {
            // Iterate over each item in the response data and push mapped objects to the result array
            response.data.forEach(item => {
                // Get random colors based on the specified color options
                let { fgcolor, bgcolor } = getRandomColor(colorOption);

                // Map each item in the API response to the Item interface
                result.push({
                    id: item.id,
                    code: item.customer_name.substring(0, 2).toUpperCase(), // Adjust if item.code is undefined
                    fgcolor: item.fgcolor || fgcolor, // Use API data if available, otherwise use random color
                    bgcolor: item.bgcolor || bgcolor, // Same as above
                    image: null , // Adjust as per your requirements
                    name: item.customer_name, // Adjust as per your requirements
                    adjective: item.customer_phone, // Adjust as per your requirements
                    amount: `$${item.amount}`, // Handle null values or use faker as fallback
                    percentage: 100, // Adjust as per your requirements
                    created_at: item.created_at, // Adjust as per your requirements
                    direction: (item.paid) ? 'up' : 'down' // Adjust as per your requirements
                });
            });
        } else {
            console.error('API response data is not an array:', response.data);
        }

        // Return the array of mapped objects
        return result;

    } catch (error) {
        console.error('Error fetching data from API:', error);
        throw error; // Optionally rethrow the error if you want to handle it elsewhere
    }
}

export function getColors(count: number): Item[] {
	const colors = [
		{
			name: "Pink",
			value: "#FF61C9"
		},
		{
			name: "Blue",
			value: "#6267FF"
		},
		{
			name: "Yellow",
			value: "#FFB600"
		},
		{
			name: "Red",
			value: "#FF0156"
		},
		{
			name: "Black",
			value: "#000"
		},
		{
			name: "Latte",
			value: "#f5f5f5"
		}
	]
	return new Array(count || 6).fill(undefined).map((_: any, i: number) => {
		const color = colors[i % colors.length]

		return {
			id: faker.string.nanoid(),
			code: "",
			fgcolor: color.value,
			bgcolor: color.value,
			name: color.name,
			amount:
				i === 0 ? "4.303" : faker.finance.amount({ min: 200, max: 3000, dec: 0, symbol: "", autoFormat: true }),
			percentage: faker.number.int({ min: 5, max: 100 }),
			direction: faker.datatype.boolean() ? "up" : "down"
		}
	})
}
