import { useState, useCallback, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Loader2, History } from 'lucide-react';
import { client } from '@/client/client.gen';
import { formatDistanceToNow } from 'date-fns';

interface EditHistoryEntry {
  old_content: string;
  new_content: string;
  edited_at: string;
}

interface EditHistoryResponse {
  message_id: string;
  history: EditHistoryEntry[];
  total_edits: number;
}

interface RoomMessageEditHistoryDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  messageId: string;
  roomId: string;
}

export function RoomMessageEditHistoryDialog({
  open,
  onOpenChange,
  messageId,
  roomId,
}: RoomMessageEditHistoryDialogProps) {
  const [history, setHistory] = useState<EditHistoryResponse | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (open && messageId) {
      loadHistory();
    }
  }, [open, messageId]);

  const loadHistory = useCallback(async () => {
    if (!messageId) return;
    
    setIsLoading(true);
    try {
      const resp = await client.get({
        url: `/api/rooms/${roomId}/messages/${messageId}/edit-history`,
      });
      const data = (resp.data as any)?.data as EditHistoryResponse | undefined;
      if (data) {
        setHistory(data);
      }
    } catch (err) {
      console.error('Failed to load edit history:', err);
    } finally {
      setIsLoading(false);
    }
  }, [messageId, roomId]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <History className="h-5 w-5" />
            Edit History ({history?.total_edits ?? 0} edits)
          </DialogTitle>
        </DialogHeader>

        <ScrollArea className="max-h-[60vh]">
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : !history || history.history.length === 0 ? (
            <div className="py-8 text-center text-sm text-muted-foreground">
              No edit history available
            </div>
          ) : (
            <div className="space-y-4 p-2">
              {history.history.map((entry, index) => (
                <div key={index} className="rounded-lg border border-border/50 p-4">
                  <div className="mb-2 flex items-center justify-between">
                    <span className="text-xs font-medium text-muted-foreground">
                      Edit #{index + 1}
                    </span>
                    <span className="text-xs text-muted-foreground">
                      {formatDistanceToNow(new Date(entry.edited_at), { addSuffix: true })}
                    </span>
                  </div>

                  <div className="space-y-2">
                    <div>
                      <div className="mb-1 text-xs font-semibold text-destructive">Before:</div>
                      <div className="whitespace-pre-wrap break-words rounded bg-destructive/5 p-2 text-sm text-foreground">
                        {entry.old_content}
                      </div>
                    </div>

                    <div>
                      <div className="mb-1 text-xs font-semibold text-green-600">After:</div>
                      <div className="whitespace-pre-wrap break-words rounded bg-green-500/5 p-2 text-sm text-foreground">
                        {entry.new_content}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </ScrollArea>
      </DialogContent>
    </Dialog>
  );
}
