'use client';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { HistoryPopoverProps } from '@/src/types/builder';
import { formatDistanceToNow } from 'date-fns';
import { Clock, History } from 'lucide-react';

export function HistoryPopover({
  items,
  onRestore,
  isLoading,
  title,
  description,
  icon = 'history',
  buttonText,
}: HistoryPopoverProps) {
  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant='ghost' size='sm' className='flex items-center gap-2'>
          {icon === 'history' ? <History className='h-4 w-4' /> : <Clock className='h-4 w-4' />}
          {buttonText}
        </Button>
      </PopoverTrigger>
      <PopoverContent
        className='w-80 p-0 bg-neutral-800 border-neutral-400 max-h-[400px] overflow-y-auto z-[401] pt-2'
        align='end'
      >
        <div className='flex flex-col'>
          <div className='px-4 py-3 border-b border-neutral-700'>
            <h3 className='text-sm font-medium text-neutral-200'>{title}</h3>
            <p className='text-xs text-neutral-400'>{description}</p>
          </div>
          <div className='py-2'>
            {(() => {
              if (isLoading) {
                return <div className='px-4 py-2 text-sm text-neutral-400'>Loading...</div>;
              }

              if (items.length === 0) {
                return <div className='px-4 py-2 text-sm text-neutral-400'>No history items available</div>;
              }

              return items.map((item) => (
                <div key={item.id} className='flex items-center justify-between px-4 py-2 hover:bg-neutral-800 group'>
                  <div className='flex flex-col'>
                    <span className='text-sm text-neutral-300'>{item.title}</span>
                    <span className='text-xs text-neutral-500'>
                      {item.subtitle || formatDistanceToNow(item.timestamp, { addSuffix: true })}
                    </span>
                  </div>
                  <Button
                    variant='ghost'
                    size='sm'
                    className='text-neutral-300 hover:text-white hover:bg-neutral-600'
                    onClick={() => onRestore(item.id)}
                  >
                    Restore
                  </Button>
                </div>
              ));
            })()}
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
}
