import DOMPurify from 'dompurify';
import { Clock } from 'lucide-react';

import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { EmptyState } from '@/Components/ui/empty-state';
import { formatDateTime } from '@/lib/format';

const ALLOWED_TAGS = [
  'p',
  'br',
  'h1',
  'h2',
  'h3',
  'h4',
  'h5',
  'h6',
  'ul',
  'ol',
  'li',
  'a',
  'strong',
  'em',
  'blockquote',
  'code',
  'pre',
];
const ALLOWED_ATTR = ['href', 'title'];

interface ContentSnapshot {
  id: number;
  title: string;
  content: string;
  meta_description: string | null;
  wp_modified_at: string;
  created_at: string;
}

interface SnapshotListProps {
  snapshots: ContentSnapshot[];
  currentSnapshotId?: number;
  onRollback: (snapshot: ContentSnapshot) => void;
}

export default function SnapshotList({
  snapshots,
  currentSnapshotId,
  onRollback,
}: SnapshotListProps) {
  const truncateText = (text: string, maxLength: number): string => {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  };

  const extractTextFromHtml = (html: string): string => {
    const sanitized = DOMPurify.sanitize(html, { ALLOWED_TAGS, ALLOWED_ATTR });
    const temp = document.createElement('div');
    temp.innerHTML = sanitized;
    return temp.textContent || temp.innerText || '';
  };

  if (snapshots.length === 0) {
    return (
      <div className="rounded-lg border bg-card">
        <EmptyState
          icon={Clock}
          title="No content history"
          description="Content snapshots are captured when you publish an AI draft to WordPress. Publish a draft to start tracking version history for this article."
          size="sm"
        />
      </div>
    );
  }

  return (
    <div className="rounded-lg border bg-card">
      <div className="p-4 border-b bg-muted/50">
        <h3 className="text-sm font-medium">Content History</h3>
        <p className="text-xs text-muted-foreground mt-1">
          {snapshots.length} snapshot{snapshots.length !== 1 ? 's' : ''} available
        </p>
      </div>

      <div className="divide-y">
        {snapshots.map((snapshot, index) => {
          const isCurrent = currentSnapshotId ? snapshot.id === currentSnapshotId : index === 0;
          const contentPreview = extractTextFromHtml(snapshot.content);

          return (
            <div key={snapshot.id} className="p-4 hover:bg-muted/30 transition-colors">
              <div className="flex items-start justify-between gap-4">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-2">
                    <h4 className="text-sm font-medium truncate">{snapshot.title}</h4>
                    {isCurrent && (
                      <Badge variant="success" className="text-xs shrink-0">
                        Current
                      </Badge>
                    )}
                  </div>

                  {snapshot.meta_description && (
                    <p className="text-xs text-muted-foreground mb-2 line-clamp-2">
                      {snapshot.meta_description}
                    </p>
                  )}

                  <p className="text-xs text-muted-foreground mb-2 line-clamp-3">
                    {truncateText(contentPreview, 200)}
                  </p>

                  <div className="flex items-center gap-3 text-xs text-muted-foreground">
                    <span>Snapshot: {formatDateTime(snapshot.created_at)}</span>
                    {snapshot.wp_modified_at && (
                      <>
                        <span>&bull;</span>
                        <span>WP Modified: {formatDateTime(snapshot.wp_modified_at)}</span>
                      </>
                    )}
                  </div>
                </div>

                <div className="shrink-0">
                  {!isCurrent && (
                    <Button size="sm" variant="outline" onClick={() => onRollback(snapshot)}>
                      Rollback
                    </Button>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
