import React, { useState, useEffect } from 'react';
import { ReportWidgetProps } from '../platform/types/index';
import { ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { Eye, EyeOff } from 'lucide-react';
import { formatMetricValue } from '../platform/core/utils/formatting';

// Standard colors for Gauge (Red/Yellow/Green)
const COLORS = ['#ef4444', '#eab308', '#22c55e'];

/**
 * GaugeWidget - Report-First Dashboard Component
 * 
 * Displays a semi-circle gauge visualization. Data sources:
 * 1. initialData from Dashboard refresh (pre-computed report data)
 * 2. Empty state if no data available
 * 
 * This widget does NOT support direct analytics queries - all dashboard
 * components are powered by Salesforce Reports per native architecture.
 */
export const GaugeWidget: React.FC<ReportWidgetProps> = ({
    title,
    config,
    data: initialData,
    loading: initialLoading,
    isEditing,
    isVisible,
    onToggle,
}) => {
    const [value, setValue] = useState(0);
    const [loading, setLoading] = useState(initialLoading);

    // Config extraction
    const min = Number(config.config?.min) || 0;
    const max = Number(config.config?.max) || 100;
    const thresholds = (config.config?.thresholds as number[]) || [33, 66];

    useEffect(() => {
        // Use initialData from Dashboard refresh
        if (initialData !== undefined && initialData !== null) {
            setValue(Number(initialData) || 0);
            setLoading(false);
            return;
        }

        // No data source - show default
        setValue(0);
        setLoading(false);
    }, [initialData]);

    // Data for Pie Chart (Gauge emulation)
    const range = max - min;
    const normalized = Math.max(0, Math.min(range, value - min));
    const remainder = range - normalized;

    const data = [
        { name: 'Value', value: normalized },
        { name: 'Remaining', value: remainder }
    ];

    // Determine color based on value
    let color = COLORS[2]; // Green
    const pct = (normalized / range) * 100;
    if (pct < thresholds[0]) color = COLORS[0];
    else if (pct < thresholds[1]) color = COLORS[1];

    return (
        <div
            className={`bg-white rounded-lg border shadow-sm flex flex-col relative h-full min-h-[200px] overflow-hidden ${isEditing ? 'border-dashed border-2 border-slate-300' : 'border-slate-200'} ${!isVisible ? 'opacity-50' : ''}`}
        >
            <div className="p-4 flex justify-between items-start">
                <h3 className="font-bold text-slate-700">{title}</h3>
                {isEditing && (
                    <button onClick={onToggle} className={`p-1 rounded-full ${isVisible ? 'bg-blue-100 text-blue-600' : 'bg-slate-200 text-slate-500'}`}>
                        {isVisible ? <Eye size={16} /> : <EyeOff size={16} />}
                    </button>
                )}
            </div>

            <div className="flex-1 flex flex-col items-center justify-center relative">
                {loading ? (
                    <div className="text-slate-400">Loading...</div>
                ) : (
                    <>
                        <ResponsiveContainer width="100%" height={160}>
                            <PieChart>
                                <Pie
                                    data={data}
                                    cx="50%"
                                    cy="70%"
                                    startAngle={180}
                                    endAngle={0}
                                    innerRadius={50}
                                    outerRadius={80}
                                    paddingAngle={2}
                                    dataKey="value"
                                >
                                    <Cell key="cell-val" fill={color} />
                                    <Cell key="cell-rem" fill="#f1f5f9" />
                                </Pie>
                            </PieChart>
                        </ResponsiveContainer>
                        <div className="absolute bottom-6 flex flex-col items-center">
                            <span className="text-3xl font-bold text-slate-800">
                                {formatMetricValue(value)}
                            </span>
                            <span className="text-xs text-slate-500">
                                Min: {min} / Max: {max}
                            </span>
                        </div>
                    </>
                )}
            </div>
        </div>
    );
};
