// src/features/flyer/AnalysisPanel.tsx
import React, { useState } from 'react';
import { AnalysisType, Flyer } from '../../types';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { LightbulbIcon } from '../../components/icons/LightbulbIcon';
import { BrainIcon } from '../../components/icons/BrainIcon';
import { SearchIcon } from '../../components/icons/SearchIcon';
import { MapPinIcon } from '../../components/icons/MapPinIcon';
import { PhotoIcon as ImageIcon } from '../../components/icons/PhotoIcon';
import { ScaleIcon } from '../../components/icons/ScaleIcon';
import { useFlyerItems } from '../../hooks/useFlyerItems';
import { useUserData } from '../../hooks/useUserData';
import { useAiAnalysis } from '../../hooks/useAiAnalysis';

interface AnalysisPanelProps {
  selectedFlyer: Flyer | null;
}

/**
 * Defines the types of analysis that correspond to a visible tab in the panel.
 * This is a subset of the main `AnalysisType` enum and is used to ensure
 * that the `activeTab` state can only be one of these values, preventing
 * type errors when indexing into results or loading state objects.
 */
type AnalysisTabType = Exclude<AnalysisType, AnalysisType.GENERATE_IMAGE>;

interface TabButtonProps {
    label: string;
    icon: React.ReactNode;
    isActive: boolean;
    onClick: () => void;
}

const TabButton: React.FC<TabButtonProps> = ({ label, icon, isActive, onClick }) => {
    const activeClasses = 'bg-brand-primary text-white';
    const inactiveClasses = 'bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600';
    return (
        <button
            // Add role="tab" for accessibility, which fixes the test query.
            role="tab"
            onClick={onClick}
            className={`flex-1 flex items-center justify-center space-x-2 px-4 py-2.5 text-sm font-medium rounded-md transition-colors duration-200 ${isActive ? activeClasses : inactiveClasses}`}
        >
            {icon}
            <span>{label}</span>
        </button>
    );
};

export const AnalysisPanel: React.FC<AnalysisPanelProps> = ({ selectedFlyer }) => {
  const { flyerItems, isLoading: isLoadingItems, error: itemsError } = useFlyerItems(selectedFlyer);
  const { watchedItems, isLoading: isLoadingWatchedItems } = useUserData();
  const [activeTab, setActiveTab] = useState<AnalysisTabType>(AnalysisType.QUICK_INSIGHTS);
  
  const {
    results,
    sources,
    loadingStates,
    error,
    runAnalysis,
    generatedImageUrl,
    isGeneratingImage,
    generateImage,
  } = useAiAnalysis({ flyerItems, selectedFlyer, watchedItems });

  const renderContent = () => {
    // Show loading state from item or watched items fetching first
    if (isLoadingItems || isLoadingWatchedItems) {
      return (
        <div role="status" className="flex justify-center items-center h-48">
          <LoadingSpinner /> <span className="ml-2">Loading data...</span>
        </div>
      );
    }
    if (loadingStates[activeTab]) { // Then show loading state from analysis
      // Add role="status" for accessibility, which fixes the test query.
      return (
        <div role="status" className="flex justify-center items-center h-48">
          <LoadingSpinner />
        </div>
      );
    }

    // Show item fetching error
    if (itemsError) {
      return <p className="text-red-500 text-center">Could not load flyer items: {itemsError.message}</p>;
    }
    
    const resultText = results[activeTab];
    const sourceList = sources[activeTab] || [];
    if (resultText) {
        const isSearchType = activeTab === AnalysisType.WEB_SEARCH || activeTab === AnalysisType.PLAN_TRIP || activeTab === AnalysisType.COMPARE_PRICES;
        return (
            <div className="prose prose-sm dark:prose-invert max-w-none whitespace-pre-wrap">
                {resultText}
                {isSearchType && sourceList.length > 0 && (
                    <div className="mt-4">
                        <h4 className="font-semibold">Sources:</h4>
                        <ul className="list-disc pl-5">
                            {sourceList.map((source) => {
                                if (!source.uri) return null;
                                return (
                                    <li key={source.uri}>
                                        <a href={source.uri} target="_blank" rel="noopener noreferrer" className="text-brand-primary hover:underline">
                                            {source.title}
                                        </a>
                                    </li>
                                )
                            })}
                        </ul>
                    </div>
                )}
                {activeTab === AnalysisType.DEEP_DIVE && (
                    <div className="mt-6 text-center">
                        {generatedImageUrl ? (
                            <img src={generatedImageUrl} alt="AI generated meal plan" className="rounded-lg shadow-md mx-auto" />
                        ) : (
                            <button
                                onClick={generateImage}
                                disabled={isGeneratingImage}
                                className="inline-flex items-center justify-center bg-indigo-500 hover:bg-indigo-600 disabled:bg-indigo-300 text-white font-bold py-2 px-4 rounded-lg"
                            >
                                {isGeneratingImage ? <><LoadingSpinner /> <span className="ml-2">Generating...</span></> : <><ImageIcon className="w-4 h-4 mr-2"/> Generate an image for this meal plan</>}
                            </button>
                        )}
                    </div>
                )}
            </div>
        );
    }
    
    return (
        <div className="text-center py-10">
            <p className="text-gray-500 mb-4">Click below to generate AI-powered insights.</p>
            <button
              onClick={() => runAnalysis(activeTab)}
              className="bg-brand-secondary hover:bg-brand-dark text-white font-bold py-2 px-4 rounded-lg transition-colors duration-300"
            >
              Generate {activeTab.replace('_', ' ')}
            </button>
        </div>
    );
  };

  return (
    <div className="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
      <div className="flex space-x-2 mb-4">
        <TabButton label="Quick Insights" icon={<LightbulbIcon className="w-4 h-4" />} isActive={activeTab === AnalysisType.QUICK_INSIGHTS} onClick={() => setActiveTab(AnalysisType.QUICK_INSIGHTS)} />
        <TabButton label="Deep Dive" icon={<BrainIcon className="w-4 h-4" />} isActive={activeTab === AnalysisType.DEEP_DIVE} onClick={() => setActiveTab(AnalysisType.DEEP_DIVE)} />
        <TabButton label="Web Search" icon={<SearchIcon className="w-4 h-4" />} isActive={activeTab === AnalysisType.WEB_SEARCH} onClick={() => setActiveTab(AnalysisType.WEB_SEARCH)} />
        <TabButton label="Plan Trip" icon={<MapPinIcon className="w-4 h-4" />} isActive={activeTab === AnalysisType.PLAN_TRIP} onClick={() => setActiveTab(AnalysisType.PLAN_TRIP)} />
        <TabButton label="Compare Prices" icon={<ScaleIcon className="w-4 h-4" />} isActive={activeTab === AnalysisType.COMPARE_PRICES} onClick={() => setActiveTab(AnalysisType.COMPARE_PRICES)} />
      </div>
      <div className="bg-gray-50 dark:bg-gray-800 rounded-md p-4 min-h-[200px] overflow-y-auto">
        {/* Conditionally render error OR content, not both. */}
        {error ? 
          <p className="text-red-500 text-center">{error}</p> : 
          renderContent()}
      </div>
    </div>
  );
};