import React, { useState, useEffect } from 'react';
import { Eye, EyeOff, Loader2, Maximize2 } from 'lucide-react';
import { ReportWidgetProps, ChartDataEntry } from '../platform/types/index';
import { ReportChart } from '../platform/features/analytics/components/ReportChart';
import { analyticsAPI } from '../platform/infrastructure/api/analytics';
import { processReportData, ReportResult } from '../platform/features/analytics/utils/reportUtils';
import { formatTooltipValue } from '../platform/core/utils/formatting';
import { DraggableResizableModal } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { Logger } from '../platform/core/services/Logger';
import { useApp } from '@nexuscrm/host-sdk';

/**
 * ChartWidget - Report-First Dashboard Component
 * 
 * Data sourcing hierarchy (Salesforce-aligned):
 * 1. initialData from Dashboard refresh (pre-computed report data)
 * 2. reportId fallback (fetch report directly if no initialData)
 * 
 * This widget does NOT support direct analytics queries - all dashboard
 * components are powered by Salesforce Reports per native architecture.
 */
export const ChartWidget: React.FC<ReportWidgetProps> = ({
    title,
    config,
    data: initialData,
    loading: initialLoading,
    isEditing,
    isVisible,
    onToggle,
}) => {
    const { currentFrontendAppId } = useApp();
    const [data, setData] = useState<ChartDataEntry[]>(
        Array.isArray(initialData) ? initialData as ChartDataEntry[] : []
    );
    const [loading, setLoading] = useState(initialLoading);
    const [isExpanded, setIsExpanded] = useState(false);

    useEffect(() => {
        // Clean, sort, and set data helper
        const processAndSetData = (rawData: unknown) => {
            const cleanedAndSorted = Array.isArray(rawData)
                ? [...(rawData as ChartDataEntry[])]
                    .filter(entry => entry.name != null && String(entry.name).trim() !== '')
                    .sort((a, b) => String(a.name).localeCompare(String(b.name)))
                : [];
            setData(cleanedAndSorted);
            setLoading(false);
        };

        // Path 1: Use initialData from Dashboard refresh (preferred)
        if (initialData && Array.isArray(initialData) && initialData.length > 0) {
            processAndSetData(initialData);
            return;
        }

        // Path 2: Fallback to fetching report directly via reportId
        const reportId = config.reportId;
        if (reportId) {
            setLoading(true);
            analyticsAPI.executeReport(reportId)
                .then(reportData => {
                    const { chartData } = processReportData(reportData as ReportResult, { fieldSurfacePolicyScope: currentFrontendAppId ?? undefined });
                    processAndSetData(chartData);
                })
                .catch(err => {
                    Logger.error('[ChartWidget] Failed to fetch report', { reportId }, err);
                    setLoading(false);
                });
            return;
        }

        // Path 3: No data source available - show empty state
        processAndSetData([]);
    }, [config.reportId, currentFrontendAppId, initialData]);

    // Format options for axis and tooltip
    const formatOptions = {
        format: config.config?.format as string,
        hintFromTitle: title
    };
    const visualizationType = typeof config.config?.visualizationType === 'string'
        ? config.config.visualizationType.toLowerCase()
        : '';
    const chartType = visualizationType === 'pie' ? 'pie' : 'bar';

    // Reusable chart renderer component (Delegated to ReportChart)
    const renderChart = (height: number = 300) => (
        <ReportChart
            data={Array.isArray(data) ? data : []}
            type={chartType}
            height={height}
            formatOptions={formatOptions}
        />
    );


    return (
        <>
            <div className={`bg-white p-6 rounded-lg border shadow-sm min-h-[350px] flex flex-col relative ${isEditing ? 'border-dashed border-2 border-slate-300' : 'border-slate-200'} h-full`}>
                {/* Header with controls */}
                <div className="flex justify-between items-center mb-6">
                    <h3 className="text-lg font-bold text-slate-800">{title}</h3>
                    <div className="flex items-center gap-2">
                        {/* Expand button - always visible when not editing */}
                        {!isEditing && (
                            <button
                                onClick={() => setIsExpanded(true)}
                                className="p-1.5 rounded-full hover:bg-slate-100 text-slate-400 hover:text-slate-600 transition-colors"
                                title="Expand to Full View"
                            >
                                <Maximize2 size={16} />
                            </button>
                        )}
                        {/* Visibility toggle - only in edit mode */}
                        {isEditing && (
                            <button onClick={onToggle} className={`p-1.5 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>

                {/* Chart content */}
                <div className="w-full relative h-[300px]">
                    {loading ? (
                        <div className="w-full h-full flex items-center justify-center text-slate-400"><Loader2 className="animate-spin mr-2" /> Loading...</div>
                    ) : (!data || (Array.isArray(data) && data.length === 0)) ? (
                        <div className="w-full h-full flex flex-col items-center justify-center text-slate-300">
                            <Loader2 size={32} className="mb-2 opacity-20" />
                            <span className="text-sm font-medium">No Data Available</span>
                        </div>
                    ) : (
                        renderChart(300)
                    )}
                </div>
            </div>

            {/* Expanded Modal View */}
            <DraggableResizableModal
                isOpen={isExpanded}
                onClose={() => setIsExpanded(false)}
                title={title || 'Chart'}
                initialWidth={900}
                initialHeight={600}
            >
                <div className="p-6 h-full overflow-hidden flex flex-col">
                    {/* Summary stats in expanded view */}
                    {data.length > 0 && (
                        <div className="mb-4 flex gap-4 text-sm">
                            <div className="bg-slate-50 px-3 py-2 rounded-lg">
                                <span className="text-slate-500">Items:</span>
                                <span className="ml-2 font-semibold text-slate-700">{data.length}</span>
                            </div>
                            <div className="bg-slate-50 px-3 py-2 rounded-lg">
                                <span className="text-slate-500">Total:</span>
                                <span className="ml-2 font-semibold text-slate-700">
                                    {formatTooltipValue(data.reduce((sum, d) => sum + (Number(d.value) || 0), 0), formatOptions)[0]}
                                </span>
                            </div>
                        </div>
                    )}
                    {/* Larger chart in modal */}
                    <div className="flex-1 min-h-0">
                        {loading ? (
                            <div className="w-full h-full flex items-center justify-center text-slate-400">
                                <Loader2 className="animate-spin mr-2" /> Loading...
                            </div>
                        ) : (!data || data.length === 0) ? (
                            <div className="w-full h-full flex flex-col items-center justify-center text-slate-300">
                                <span className="text-sm font-medium">No Data Available</span>
                            </div>
                        ) : (
                            renderChart(450)
                        )}
                    </div>
                </div>
            </DraggableResizableModal>
        </>
    );
};
