/**
 * Widget Template
 * 
 * Copy this file to create a new dashboard widget:
 * 1. cp src/templates/WidgetTemplate.tsx src/components/widgets/MyWidget.tsx
 * 2. Rename the widget and update data fetching
 */

import { useState, useEffect } from 'react';
import { TrendingUp, TrendingDown, Minus, RefreshCw } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';

interface WidgetTemplateProps {
    title: string;
    icon: LucideIcon;
    iconColor?: string;
    refreshInterval?: number; // ms, 0 = no auto-refresh
}

interface WidgetData {
    value: number | string;
    label: string;
    trend?: 'up' | 'down' | 'neutral';
    trendValue?: string;
}

export function WidgetTemplate({
    title,
    icon: Icon,
    iconColor = 'text-[var(--color-primary)]',
    refreshInterval = 0,
}: WidgetTemplateProps) {
    const [data, setData] = useState<WidgetData | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [lastUpdated, setLastUpdated] = useState<Date>(new Date());

    const fetchData = async () => {
        setIsLoading(true);
        try {
            // Replace with actual API call
            // const response = await api.get('/widget-data');
            // setData(response.data);

            // Demo data
            await new Promise(resolve => setTimeout(resolve, 500));
            setData({
                value: Math.floor(Math.random() * 100),
                label: 'Items',
                trend: Math.random() > 0.5 ? 'up' : 'down',
                trendValue: `${Math.floor(Math.random() * 20)}%`,
            });
            setLastUpdated(new Date());
        } catch (error) {
            console.error('Widget fetch failed:', error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        fetchData();

        if (refreshInterval > 0) {
            const interval = setInterval(fetchData, refreshInterval);
            return () => clearInterval(interval);
        }
    }, [refreshInterval]);

    const TrendIcon = data?.trend === 'up' ? TrendingUp : data?.trend === 'down' ? TrendingDown : Minus;
    const trendColor = data?.trend === 'up' ? 'text-[var(--color-primary)]' : data?.trend === 'down' ? 'text-red-500' : 'text-[var(--color-text-tertiary)]';

    return (
        <div className="bg-[var(--color-bg-elevated)] rounded-xl border border-[var(--color-border-default)] p-4 shadow-sm">
            {/* Header */}
            <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2">
                    <div className={`p-2 rounded-lg bg-[var(--color-bg-tertiary)] ${iconColor}`}>
                        <Icon size={18} />
                    </div>
                    <h3 className="text-sm font-medium text-[var(--color-text-primary)]">{title}</h3>
                </div>
                <button
                    onClick={fetchData}
                    disabled={isLoading}
                    className="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 text-[var(--color-text-tertiary)]"
                    title="Refresh"
                >
                    <RefreshCw size={14} className={isLoading ? 'animate-spin' : ''} />
                </button>
            </div>

            {/* Content */}
            {isLoading && !data ? (
                <div className="h-16 flex items-center justify-center">
                    <div className="animate-spin w-5 h-5 border-2 border-emerald-500 border-t-transparent rounded-full" />
                </div>
            ) : data ? (
                <div className="space-y-2">
                    <div className="flex items-end gap-2">
                        <span className="text-3xl font-bold text-[var(--color-text-primary)]">
                            {data.value}
                        </span>
                        <span className="text-sm text-[var(--color-text-tertiary)] mb-1">{data.label}</span>
                    </div>
                    {data.trend && (
                        <div className={`flex items-center gap-1 text-sm ${trendColor}`}>
                            <TrendIcon size={14} />
                            <span>{data.trendValue} from last week</span>
                        </div>
                    )}
                </div>
            ) : (
                <p className="text-sm text-[var(--color-text-tertiary)]">No data available</p>
            )}

            {/* Footer */}
            <div className="mt-3 pt-3 border-t border-slate-100 dark:border-slate-700">
                <p className="text-[10px] text-[var(--color-text-tertiary)]">
                    Updated {lastUpdated.toLocaleTimeString()}
                </p>
            </div>
        </div>
    );
}
