import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Loader2 } from 'lucide-react';
import { useEffect, useState } from 'react';

interface RoomMessageEditDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  originalContent: string;
  onConfirm: (newContent: string) => void;
  isPending?: boolean;
}

export function RoomMessageEditDialog({
  open,
  onOpenChange,
  originalContent,
  onConfirm,
  isPending = false,
}: RoomMessageEditDialogProps) {
  const [content, setContent] = useState(originalContent);

  useEffect(() => {
    if (open) setContent(originalContent);
  }, [open, originalContent]);

  const handleConfirm = () => {
    const trimmed = content.trim();
    if (trimmed && trimmed !== originalContent) {
      onConfirm(trimmed);
    }
  };

  const isChanged = content.trim() !== originalContent;
  const isValid = content.trim().length > 0;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Edit Message</DialogTitle>
          <DialogDescription>After editing, others will see an &quot;edited&quot; tag.</DialogDescription>
        </DialogHeader>
        <div className="py-4">
          <Textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            placeholder="Enter message..."
            className="min-h-[100px]"
            autoFocus
            onKeyDown={(e) => {
              if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
                e.preventDefault();
                if (isValid && isChanged) handleConfirm();
              }
            }}
          />
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isPending}>
            Cancel
          </Button>
          <Button onClick={handleConfirm} disabled={!isValid || !isChanged || isPending}>
            {isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
            Save
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
