
import React from 'react';
import type { Store } from '../types';

const formatDateRange = (from: string | null | undefined, to: string | null | undefined): string | null => {
  if (!from && !to) return null;
  const options: Intl.DateTimeFormatOptions = { month: 'long', day: 'numeric', year: 'numeric' };
  
  const fromDate = from ? new Date(`${from}T00:00:00`).toLocaleDateString('en-US', options) : null;
  const toDate = to ? new Date(`${to}T00:00:00`).toLocaleDateString('en-US', options) : null;

  if (fromDate && toDate) {
    return fromDate === toDate ? `Valid on ${fromDate}` : `Deals valid from ${fromDate} to ${toDate}`;
  }
  return fromDate ? `Deals start ${fromDate}` : (toDate ? `Deals end ${toDate}` : null);
};

interface FlyerDisplayProps {
  imageUrl: string | null;
  store?: Store;
  validFrom?: string | null;
  validTo?: string | null;
  storeAddress?: string | null;
}

export const FlyerDisplay: React.FC<FlyerDisplayProps> = ({ imageUrl, store, validFrom, validTo, storeAddress }) => {
  const dateRange = formatDateRange(validFrom, validTo);
  
  return (
    <div className="w-full rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700 shadow-sm bg-white dark:bg-gray-900 flex flex-col">
      {(store || dateRange) && (
        <div className="p-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 flex items-center space-x-4">
          {store?.logo_url && (
            <img 
              src={store.logo_url}
              alt={`${store.name || 'Store'} Logo`}
              className="h-12 w-12 object-contain rounded-md"
            />
          )}
          <div className="flex-grow text-center sm:text-left">
            {store?.name && <h3 className="text-gray-900 dark:text-white text-lg font-bold tracking-wide">{store.name}</h3>}
            {dateRange && <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">{dateRange}</p>}
            {storeAddress && <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">{storeAddress}</p>}
          </div>
        </div>
      )}
      <div className="bg-gray-100 dark:bg-gray-800">
        {imageUrl ? (
          <img src={imageUrl} alt="Grocery Flyer" className="w-full h-auto object-contain max-h-[60vh] dark:invert dark:hue-rotate-180" />
        ) : (
          <div className="w-full h-64 bg-gray-200 dark:bg-gray-700 rounded-lg flex items-center justify-center">
             <p className="text-gray-500">Flyer image will be displayed here</p>
          </div>
        )}
      </div>
    </div>
  );
};
