//@ts-ignore: Cannot find module '@wordpress/components' or its corresponding type declarations.
import { Notice, Spinner } from '@wordpress/components';
import { useState, useEffect } from 'react';
import NoticeCredits from '../shared/NoticeCredits';
import fsPublicDataManager from '../shared/fsPublicDataManager';
declare const scroll_sequence_editor_data :any


// COPIED FROM API - START
// when changing this, also change the type in the API
type UsageDataSuccessResponse = {
  success: true,
  fsPublicData: {
    isMatchingSiteId : boolean
    isMatchinUrl : boolean
    isMatchingSk : boolean 
    isMatchingAll? : boolean

    planLimit: PlanLimit 
    usage30d: LicenseUsageSummary 
    hasCredits: boolean // true if the user has credits, false if not
  },
}
export type PlanLimit = {
    plan_id: number; // This is the plan_id from Freemius 
    name: string; // Human readable name of the plan 'Pro', 'Business', etc.
    usage30dLimit: number; // This is the 30 day limit for the free plan example: 1000 (cents) = 10$
};
export type LicenseUsageSummary = {
    usage_total: number;
    usage_remaining: number;
    details: LicenseUsageDetails
};
export type LicenseUsageDetails = {
    media_tools_usage: number;
    blocks_usage: number;
    contanim_usage: number;
    // img2img_usage: number;
    // img2imgvision_usage: number;
    // img2vid_usage: number;
}
// COPIED FROM API - END 


type UsageDataErrorResponse = {
    success: false,
    error: any, // This can be a string or an object with error details, we can just stringify it 
}

type UsageDataResponse = UsageDataSuccessResponse | UsageDataErrorResponse;

// Stacked progress bar component
type StackedProgressBarProps = {
    details: {
        media_tools_usage: number,
        blocks_usage: number,
        contanim_usage: number,
        // img2img_usage: number,
        // img2imgvision_usage: number,
        // img2vid_usage: number
    },
    total: number,
    limit: number
};

function StackedProgressBar({ details, total, limit }: StackedProgressBarProps) {
    const colors = [
        //"#add8e6", // Light Blue
        "#6495ed", // Cornflower Blue
        "#1e90ff", // Dodger Blue
        //"#0074d9", // Strong Medium Blue
        "#003a6dff", // Strong Medium Blue
        //"#001f3f"  // Navy Blue
    ];
    const keys = [
        'media_tools_usage',
        'blocks_usage',
        'contanim_usage',
        // 'img2img_usage',
        // 'img2imgvision_usage',
        // 'img2vid_usage',
        // 'img2vid002_usage'
    ];

    // Calculate each segment as a percentage of the total limit
    const segments = keys.map((key, i) => ({
        width: (details[key as keyof typeof details] / limit) * 100,
        color: colors[i],
        value: details[key as keyof typeof details],
        label: key.replace('_usage', '')
    }));

    // Calculate remaining
    const used = keys.reduce((sum, key) => sum + details[key as keyof typeof details], 0);
    const remaining = Math.max(limit - used, 0);
    const remainingWidth = (remaining / limit) * 100;

    // Add remaining segment
    if (remainingWidth > 0) {
        segments.push({
            width: remainingWidth,
            color: '#rgb(243, 243, 243)',
            value: remaining,
            label: 'remaining'
        });
    }

    return (
        <div style={{margin: '18px 0 8px 0'}}>
            <div style={{
                display: 'flex',
                height: 20,
                borderRadius: 8,
                overflow: 'hidden',
                background: 'rgb(243, 243, 243)'
            }}>
                {segments.map(seg => (
                    <div
                        key={seg.label}
                        style={{
                            width: `${seg.width}%`,
                            background: seg.color,
                            transition: 'width 0.5s',
                            height: '100%'
                        }}
                        title={`${seg.label}: ${seg.value} / ${limit}`}
                    />
                ))}
            </div>
            <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                fontSize: 12,
                marginTop: 6,
                color: '#666'
            }}>
                <div>
                    {segments.filter(seg => seg.label !== 'remaining').map(seg => (
                        <span key={seg.label} style={{marginRight: 16, display: 'block'}}>
                            <span style={{
                                display: 'inline-block',
                                width: 10,
                                height: 10,
                                background: seg.color,
                                borderRadius: 2,
                                marginRight: 4,
                                verticalAlign: 'middle'
                            }} />
                            {seg.label}: {Number(seg.value).toLocaleString(undefined, { maximumFractionDigits: 2 })}
                        </span>
                    ))}
                    {/* {segments.find(seg => seg.label === 'remaining') && (
                        <span key="remaining" style={{marginRight: 16, display: 'inline-block'}}>
                            <span style={{
                                display: 'inline-block',
                                width: 10,
                                height: 10,
                                background: '#bdbdbd',
                                borderRadius: 2,
                                marginRight: 4,
                                verticalAlign: 'middle'
                            }} />
                            remaining: {Number(remaining).toLocaleString(undefined, { maximumFractionDigits: 2 })}
                        </span>
                    )} */}
                </div>
                <div>
                    {used.toLocaleString(undefined, { maximumFractionDigits: 2 })} / {limit.toLocaleString(undefined, { maximumFractionDigits: 2 })} ({limit > 0 ? Math.round((used/limit)*100) : 0}%)
                </div>
            </div>
        </div>
    );
}

export default function TabApi(){
    const [ usageData, setUsageData ] = useState< null | UsageDataResponse>(null);
    const [ loading, setLoading ] = useState<boolean>(true);
    const [ usageError, setUsageError ] = useState<any>(null);

    useEffect(() => {
        const fetchUsageData = async () => {
            setLoading(true);
            try {
                const response = await fetch(`${scroll_sequence_editor_data.scrollSequenceApiUrl}/v2/usage`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `${scroll_sequence_editor_data.fs_auth_hash}`,
                        'Content-Type': 'application/json',
                    },
                });

                const data = await response.json();

                console.log('Usage data response:ZXXXXXXXXXXXXXXXXXX', data);

                if (!response.ok || data.success === false) {
                    const errorDetails = data?.error ||  'Unknown error occurred.' ;
                    setUsageError({
                        status: response.status,
                        message: errorDetails || response.statusText,
                        details: errorDetails || null,
                    });
                    setUsageData(null);
                } else {
                    setUsageData(data);
                    setUsageError(null);
                }
                // pass data to the notice
                fsPublicDataManager.update(data.fsPublicData);
            } catch (error: any) {
                setUsageError({
                    message: error.message || 'An unexpected error occurred.',
                    stack: error.stack || null,
                });
                setUsageData(null);
            }
            setLoading(false);
        };

        fetchUsageData();
    }, []);

    // Helper for progress value
    const getProgress = (used: number, limit: number) =>
        Math.min((used / limit) * 100, 100);

    return (
        <>
            <div style={{
                maxWidth: 700,
                minHeight: 480,
                position: 'relative'
            }}>
                <h2 >Usage & Limits</h2>
                {/* <div style={{color: "#b00", fontSize: 13, marginBottom: 16}}>
                    <span>Scope: license_id</span>
                </div> */}
                <div style={{fontSize: 13, color: "#666", marginBottom: 24}}>
                    This shows license-based usage/total summaries for the last 30 days.
                </div>
                {loading && (
                    <div style={{textAlign: 'center', margin: '2em 0'}}>
                        <Spinner />
                        <p>Loading usage data...</p>
                    </div>
                )}
                {!loading && usageError && (
                    <Notice status="error" isDismissible={false}>
                        <strong>Error loading usage data:</strong>
                        <br />
                        {usageError.message ? usageError.message : JSON.stringify(usageError)}
                    </Notice>
                )}
                {!loading && usageData && usageData.success && (
                    <>
                        <div style={{
                            marginBottom: 24,
                            display: 'flex',
                            alignItems: 'center',
                            gap: 16
                        }}>
                            <div style={{fontWeight: 600, fontSize: 16}}>
                                Plan: <span style={{fontWeight: 400}}>{usageData.fsPublicData.planLimit.name}</span>
                            </div>
                            <div style={{
                                background: '#f3f3f3',
                                borderRadius: 8,
                                padding: '2px 10px',
                                fontSize: 13,
                                color: '#444'
                            }}>
                                Limit: {usageData.fsPublicData.planLimit.usage30dLimit}
                            </div>
                        </div>
                        <StackedProgressBar
                            details={usageData.fsPublicData.usage30d.details}
                            total={usageData.fsPublicData.usage30d.usage_total}
                            limit={usageData.fsPublicData.planLimit.usage30dLimit}
                        />
                        <div style={{display: "flex", justifyContent: "center", fontSize: 16, fontWeight: 600, marginTop: 12, marginBottom: 18}}>
                            {usageData.fsPublicData.usage30d.usage_remaining} remaining
                        </div>
                        <br/><br/>
                        <NoticeCredits />
                    </>
                )}
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <span
                    style={{
                        fontSize: '10px',
                        color: '#bbb',
                        opacity: 0.7,
                        pointerEvents: 'none',
                        userSelect: 'none',
                    }}
                >
                   API:{scroll_sequence_editor_data.scrollSequenceApiUrl}
                </span>
            </div>                    
        </>
    );
}