import { Link } from 'react-router';
import { MessageSquare, Trash2 } from 'lucide-react';
import { Widget } from 'widgets/Widget';
import { useChatSessions } from 'state/useChatSessions';

export const ChatHistory = () => {
  const { sessions, deleteSession } = useChatSessions();

  return (
    <Widget title="Chat History">
      <div className="px-4 pb-3 max-h-72 overflow-y-auto">
        {sessions.length === 0 ? (
          <p className="text-xs text-duck-dark/40 py-4 text-center">No sessions yet</p>
        ) : (
          <ul className="space-y-0.5">
            {sessions.map((session) => (
              <li
                key={session.id}
                className="flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-duck-dark/5 group"
              >
                <Link
                  to={`/chat/${session.id}`}
                  className="flex items-center gap-2 flex-1 min-w-0"
                >
                  <MessageSquare className="h-4 w-4 shrink-0 text-duck-teal/60" />
                  <div className="min-w-0 flex-1">
                    <span className="text-sm text-duck-dark dark:text-foreground truncate block">
                      {session.title}
                      <span className="ml-1.5 font-mono text-xs text-duck-dark/25 dark:text-foreground/25">
                        ({session.id.slice(0, 8)})
                      </span>
                    </span>
                    <span className="text-xs text-duck-dark/40 dark:text-foreground/40 truncate block">
                      {new Date(session.createdAt).toLocaleDateString(undefined, {
                        month: 'short',
                        day: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                      })}
                    </span>
                    {session.model && (
                      <span className="text-xs text-duck-teal/70 dark:text-duck-teal/60 truncate block">
                        {session.model.includes('/') ? session.model.replace('/', ' - ') : session.model}
                      </span>
                    )}
                  </div>
                </Link>
                <button
                  onClick={() => deleteSession(session.id)}
                  className="shrink-0 p-1 rounded text-duck-dark/20 md:opacity-0 md:group-hover:opacity-100 hover:text-red-500 transition-opacity cursor-pointer"
                >
                  <Trash2 className="h-3.5 w-3.5" />
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>
    </Widget>
  );
};
