// src/features/flyer/FlyerList.tsx
import React from 'react';
import toast from 'react-hot-toast';
import type { Flyer, UserProfile } from '../../types';
import { DocumentTextIcon } from '../../components/icons/DocumentTextIcon';
import { parseISO, format, isValid } from 'date-fns';
import { MapPinIcon, Trash2Icon } from 'lucide-react';
import { logger } from '../../services/logger.client';
import * as apiClient from '../../services/apiClient';

const formatShortDate = (dateString: string | null | undefined): string | null => {
    if (!dateString) return null;
    // Using `parseISO` from date-fns is more reliable than `new Date()` for YYYY-MM-DD strings.
    // It correctly interprets the string as a local date, avoiding timezone-related "off-by-one" errors.
    try {
        const date = parseISO(dateString);
        // Format the date to "MMM d" (e.g., "Oct 5")
        return format(date, 'MMM d');
    } catch {
        return null;
    }
}


interface FlyerListProps {
    flyers: Flyer[];
    onFlyerSelect: (flyer: Flyer) => void;
    selectedFlyerId: number | null;
    profile: UserProfile | null;
}

export const FlyerList: React.FC<FlyerListProps> = ({ flyers, onFlyerSelect, selectedFlyerId, profile }) => {
    const isAdmin = profile?.role === 'admin';

    const handleCleanupClick = async (e: React.MouseEvent, flyerId: number) => {
        e.stopPropagation(); // Prevent the row's onClick from firing
        if (!window.confirm(`Are you sure you want to clean up the files for flyer ID ${flyerId}? This action cannot be undone.`)) {
            return;
        }
        try {
            await apiClient.cleanupFlyerFiles(flyerId);
            toast.success(`Cleanup job for flyer ID ${flyerId} has been enqueued.`);
        } catch (error) {
            toast.error(error instanceof Error ? error.message : 'Failed to enqueue cleanup job.');
        }
    };

    return (
        <div className="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-700">
            <h3 className="text-lg font-bold text-gray-800 dark:text-white p-4 border-b border-gray-200 dark:border-gray-700">
                Processed Flyers
            </h3>
            {flyers.length > 0 ? (
                 <ul className="divide-y divide-gray-200 dark:divide-gray-700 max-h-96 overflow-y-auto">
                    {flyers.map(flyer => {
                        const from = formatShortDate(flyer.valid_from);
                        const to = formatShortDate(flyer.valid_to);
                        const dateRange = from && to ? (from === to ? from : `${from} - ${to}`) : from || to;

                        // Build a more detailed tooltip string
                        const processedDate = isValid(parseISO(flyer.created_at)) ? format(parseISO(flyer.created_at), 'PPPP p') : 'N/A';
                        const validFromFull = flyer.valid_from && isValid(parseISO(flyer.valid_from)) ? format(parseISO(flyer.valid_from), 'PPPP') : 'N/A';
                        const validToFull = flyer.valid_to && isValid(parseISO(flyer.valid_to)) ? format(parseISO(flyer.valid_to), 'PPPP') : 'N/A';
                        
                        const tooltipLines = [
                            `File: ${flyer.file_name}`,
                            `Store: ${flyer.store?.name || 'Unknown'}`,
                            `Address: ${flyer.store_address || 'N/A'}`,
                            `Items: ${flyer.item_count}`,
                            `Valid: ${validFromFull} to ${validToFull}`,
                            `Processed: ${processedDate}`
                        ];
                        const tooltipText = tooltipLines.join('\n');

                        // --- DEBUG LOGGING for icon display logic ---
                        // Log the flyer object and the specific icon_url value before the conditional check.
                        logger.debug(`[FlyerList] Checking icon for flyer ID ${flyer.flyer_id}.`, { flyer });
                        const hasIconUrl = !!flyer.icon_url;
                        logger.debug(`[FlyerList] Flyer ID ${flyer.flyer_id}: hasIconUrl is ${hasIconUrl}. Rendering ${hasIconUrl ? '<img>' : 'DocumentTextIcon'}.`);

                        return (
                            <li
                                data-testid={`flyer-list-item-${flyer.flyer_id}`}
                                key={flyer.flyer_id}
                                onClick={() => onFlyerSelect(flyer)}
                                className={`p-4 flex items-center space-x-3 cursor-pointer transition-colors duration-200 ${selectedFlyerId === flyer.flyer_id ? 'bg-brand-light dark:bg-brand-dark/30' : 'hover:bg-gray-50 dark:hover:bg-gray-800'}`}
                                title={tooltipText}
                            >
                                {flyer.icon_url ? (
                                    <img src={flyer.icon_url} alt="Flyer Icon" className="w-6 h-6 shrink-0 rounded-sm" />
                                ) : (
                                    <DocumentTextIcon className="w-6 h-6 text-brand-primary shrink-0" />
                                )}
                                <div className="grow min-w-0">
                                    <div className="flex items-center space-x-2">
                                        <p className="text-sm font-semibold text-gray-900 dark:text-white truncate">
                                            {flyer.store?.name || 'Unknown Store'}
                                        </p>
                                        {flyer.store_address && (
                                            <a href={`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(flyer.store_address)}`} target="_blank" rel="noopener noreferrer" onClick={(e) => e.stopPropagation()} title={`View address: ${flyer.store_address}`}>
                                                <MapPinIcon className="w-5 h-5 text-gray-400 hover:text-brand-primary transition-colors" />
                                            </a>
                                        )}
                                    </div>
                                    <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                        {`${flyer.item_count} items`}
                                        {dateRange && ` • Valid: ${dateRange}`}
                                    </p>
                                </div>
                                {isAdmin && (
                                    <button
                                        onClick={(e) => handleCleanupClick(e, flyer.flyer_id)}
                                        className="shrink-0 p-2 rounded-md hover:bg-red-100 dark:hover:bg-red-900/50 text-gray-400 hover:text-red-600 transition-colors"
                                        title={`Clean up files for flyer ID ${flyer.flyer_id}`}
                                    >
                                        <Trash2Icon className="w-4 h-4" />
                                    </button>
                                )}
                            </li>
                        );
                    })}
                 </ul>
            ) : (
                <p className="p-4 text-sm text-gray-500 dark:text-gray-400">
                    No flyers have been processed yet. Upload one to get started.
                </p>
            )}
        </div>
    );
};