// src/components/MyDealsPage.tsx
import React, { useState, useEffect } from 'react';
import { WatchedItemDeal } from '../types';
import { fetchBestSalePrices } from '../services/apiClient';
import { logger } from '../services/logger.client';
import { AlertCircle, Tag, Store, Calendar } from 'lucide-react';

const MyDealsPage: React.FC = () => {
  const [deals, setDeals] = useState<WatchedItemDeal[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadDeals = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const response = await fetchBestSalePrices();
        if (!response.ok) {
          throw new Error('Failed to fetch deals. Please try again later.');
        }
        const data: WatchedItemDeal[] = await response.json();
        setDeals(data);
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred.';
        logger.error('Error fetching watched item deals:', errorMessage);
        setError(errorMessage);
      } finally {
        setIsLoading(false);
      }
    };

    loadDeals();
  }, []);

  if (isLoading) {
    return <div className="text-center p-8">Loading your deals...</div>;
  }

  if (error) {
    return (
      <div className="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-md shadow-md max-w-2xl mx-auto" role="alert">
        <div className="flex items-center">
          <AlertCircle className="h-6 w-6 mr-3" />
          <div>
            <p className="font-bold">Error</p>
            <p>{error}</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto p-4 sm:p-6 lg:p-8">
      <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-6">My Watched Item Deals</h1>
      {deals.length === 0 ? (
        <div className="text-center bg-gray-100 dark:bg-gray-800 p-8 rounded-lg shadow-sm">
          <p className="text-lg text-gray-600 dark:text-gray-400">No deals found for your watched items right now.</p>
          <p className="text-sm text-gray-500 mt-2">Try adding more items to your watchlist or check back after new flyers are uploaded!</p>
        </div>
      ) : (
        <ul className="space-y-4">
          {deals.map((deal) => (
            <li key={`${deal.master_item_id}-${deal.flyer_id}`} className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4 transition hover:shadow-lg">
              <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center">
                <h2 className="text-xl font-semibold text-gray-800 dark:text-gray-100 mb-2 sm:mb-0">{deal.item_name}</h2>
                <div className="flex items-center bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 text-lg font-bold px-3 py-1 rounded-full">
                  <Tag className="h-5 w-5 mr-2" />
                  <span>${(deal.best_price_in_cents / 100).toFixed(2)}</span>
                </div>
              </div>
              <div className="mt-3 text-sm text-gray-600 dark:text-gray-400 flex flex-col sm:flex-row sm:items-center sm:space-x-6 space-y-2 sm:space-y-0">
                <div className="flex items-center">
                  <Store className="h-4 w-4 mr-2 text-gray-500" />
                  <span>{deal.store_name}</span>
                </div>
                <div className="flex items-center">
                  <Calendar className="h-4 w-4 mr-2 text-gray-500" />
                  <span>Valid until: {new Date(deal.valid_to).toLocaleDateString()}</span>
                </div>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default MyDealsPage;