import { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { AlertTriangle } from 'lucide-react';
import { Alert, AlertDescription } from '@/components/ui/alert';

interface RollbackDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  versionId: string;
  entityType: string;
  entityId: string;
  entityName: string;
  onRollback: (reason: string) => Promise<void>;
}

export function RollbackDialog({
  open,
  onOpenChange,
  versionId,
  entityName,
  onRollback,
}: RollbackDialogProps) {
  const [reason, setReason] = useState('');
  const [loading, setLoading] = useState(false);

  const handleRollback = async () => {
    if (!reason.trim()) return;

    setLoading(true);
    try {
      await onRollback(reason);
      setReason('');
      onOpenChange(false);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Restore Previous Version (Moderator Action)</DialogTitle>
          <DialogDescription>
            You are about to restore "{entityName}" to a previous version. This will create a new version with the restored data. This action will be logged in the audit trail.
          </DialogDescription>
        </DialogHeader>

        <Alert variant="default" className="border-yellow-500/50 bg-yellow-500/10">
          <AlertTriangle className="h-4 w-4 text-yellow-600 dark:text-yellow-500" />
          <AlertDescription className="text-yellow-900 dark:text-yellow-200">
            This action will restore the entity to its previous state. The current version will be preserved in history.
          </AlertDescription>
        </Alert>

        <div className="space-y-2">
          <Label htmlFor="rollback-reason">Reason for rollback *</Label>
          <Textarea
            id="rollback-reason"
            placeholder="Explain why you're rolling back to this version..."
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            rows={4}
            required
          />
          <p className="text-xs text-muted-foreground">
            This reason will be logged in the version history for audit purposes.
          </p>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={loading}
          >
            Cancel
          </Button>
          <Button
            onClick={handleRollback}
            disabled={!reason.trim() || loading}
          >
            {loading ? 'Restoring...' : 'Restore Version'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
