import React, { useEffect, useState } from 'react';
import { Link, useLocation } from '@tanstack/react-router';

type ViewedItem = {
  type: 'customer' | 'project';
  id: string;
  name: string;
  viewedAt: number;
};

export default function RecentlyViewed() {
  const location = useLocation();
  const [items, setItems] = useState<ViewedItem[]>([]);

  useEffect(() => {
    // 1. Track current route
    const path = location.pathname;
    const customerMatch = path.match(/\/customers\/([^/]+)/);
    const projectMatch = path.match(/\/projects\/([^/]+)/);

    if (customerMatch || projectMatch) {
      const type = customerMatch ? 'customer' : 'project';
      const id = customerMatch ? customerMatch[1] : projectMatch![1];
      
      // In a real app, we'd fetch the name from a store/cache. 
      // For the widget, we'll use a placeholder or try to extract from state if available.
      // Here we use a generic label since we don't have the full entity object in the URL.
      const name = `View ${id}`; 

      const stored = localStorage.getItem('recently_viewed');
      const parsed: ViewedItem[] = stored ? JSON.parse(stored) : [];
      
      // Remove existing entry of same item to move it to top
      const filtered = parsed.filter(i => !(i.type === type && i.id === id));
      const updated = [{ type, id, name, viewedAt: Date.now() }, ...filtered].slice(0, 5);
      
      localStorage.setItem('recently_viewed', JSON.stringify(updated));
      setItems(updated);
    }
  }, [location.pathname]);

  // Initial load
  useEffect(() => {
    const stored = localStorage.getItem('recently_viewed');
    if (stored) setItems(JSON.parse(stored));
  }, []);

  if (items.length === 0) return null;

  return (
    <div className="p-4 bg-white border border-slate-200 rounded-lg shadow-sm">
      <h3 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-3">
        Recently Viewed
      </h3>
      <ul className="space-y-2">
        {items.map((item) => (
          <li key={`${item.type}-${item.id}`}>
            <Link
              to={`/${item.type}s/${item.id}`}
              className="flex items-center justify-between p-2 text-sm text-slate-700 hover:bg-slate-50 rounded-md transition-colors group"
            >
              <div className="flex items-center gap-2">
                <span className={`w-2 h-2 rounded-full ${item.type === 'customer' ? 'bg-blue-400' : 'bg-emerald-400'}`} />
                <span className="truncate max-w-[150px]">{item.name}</span>
              </div>
              <span className="text-xs text-slate-400 opacity-0 group-hover:opacity-100 transition-opacity">
                →
              </span>
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}