'use client';

import * as React from 'react';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { EmptyState } from '@/components/ui/EmptyState';
import { History, X, Trash2, ChevronDown, ChevronUp, Clock } from 'lucide-react';
import { cn } from '@/lib/utils/cn';
import { getHistory, clearHistory, removeHistoryItem, type HistoryItem } from '@/lib/storage/history';

export interface HistoryPanelProps {
  onSelectHistory: (item: HistoryItem) => void;
  className?: string;
}

export function HistoryPanel({ onSelectHistory, className }: HistoryPanelProps) {
  const [isExpanded, setIsExpanded] = React.useState(false);
  const [history, setHistory] = React.useState<HistoryItem[]>([]);

  const loadHistory = React.useCallback(() => {
    setHistory(getHistory());
  }, []);

  React.useEffect(() => {
    loadHistory();
    // Refresh history every 2 seconds when expanded
    if (isExpanded) {
      const interval = setInterval(loadHistory, 2000);
      return () => clearInterval(interval);
    }
  }, [isExpanded, loadHistory]);

  const handleClearAll = () => {
    clearHistory();
    loadHistory();
  };

  const handleRemove = (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    removeHistoryItem(id);
    loadHistory();
  };

  const formatTime = (timestamp: number) => {
    const now = Date.now();
    const diff = now - timestamp;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);

    if (minutes < 1) return 'Just now';
    if (minutes < 60) return `${minutes}m ago`;
    if (hours < 24) return `${hours}h ago`;
    return new Date(timestamp).toLocaleDateString();
  };

  return (
    <Card className={className}>
      <div className="p-4">
        <button
          onClick={() => setIsExpanded(!isExpanded)}
          className="w-full flex items-center justify-between text-sm font-medium hover:text-primary transition-colors"
        >
          <div className="flex items-center gap-2">
            <History className="h-4 w-4" />
            <span>Copy History</span>
            <span className="text-xs text-muted-foreground">({history.length})</span>
          </div>
          {isExpanded ? (
            <ChevronUp className="h-4 w-4" />
          ) : (
            <ChevronDown className="h-4 w-4" />
          )}
        </button>

        {isExpanded && (
          <div className="mt-4 space-y-2 slide-down">
            {history.length === 0 ? (
              <EmptyState
                icon={Clock}
                title="No copy history yet"
                description="Your recently copied ASCII art will appear here"
              />
            ) : (
              <>
                <div className="flex justify-end">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleClearAll}
                    className="text-destructive hover:text-destructive"
                  >
                    <Trash2 className="h-3 w-3 mr-1" />
                    Clear All
                  </Button>
                </div>

                <div className="space-y-2 max-h-[300px] overflow-y-auto">
                  {history.map((item) => (
                    <div
                      key={item.id}
                      onClick={() => onSelectHistory(item)}
                      className="group relative p-3 bg-muted/50 hover:bg-accent hover:scale-[1.02] rounded-md cursor-pointer transition-all"
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="text-xs font-mono px-1.5 py-0.5 bg-primary/10 text-primary rounded">
                              {item.font}
                            </span>
                            <span className="text-xs text-muted-foreground">
                              {formatTime(item.timestamp)}
                            </span>
                          </div>
                          <p className="text-xs truncate">{item.text}</p>
                        </div>
                        <button
                          onClick={(e) => handleRemove(item.id, e)}
                          className="opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-destructive/10 rounded"
                        >
                          <X className="h-3 w-3 text-destructive" />
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        )}
      </div>
    </Card>
  );
}
