import { useState, useCallback } from 'react';
import { Undo2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { trpc } from '@/lib/trpc';

interface ChangeSetInlineProps {
  changeSetId: string;
}

export function ChangeSetInline({ changeSetId }: ChangeSetInlineProps) {
  const [conflicts, setConflicts] = useState<string[] | null>(null);

  const detailQuery = trpc.getChangeSet.useQuery({ id: changeSetId });
  const entries = detailQuery.data?.entries ?? [];
  const status = detailQuery.data?.status ?? 'applied';
  const isReverted = status === 'reverted';

  const revertMutation = trpc.revertChangeSet.useMutation({
    onSuccess: (result) => {
      if (!result.success && 'conflicts' in result) {
        setConflicts(result.conflicts);
      } else {
        setConflicts(null);
      }
    },
  });

  const handleRevert = useCallback(
    (force?: boolean) => {
      revertMutation.mutate({ id: changeSetId, force });
    },
    [changeSetId, revertMutation],
  );

  if (detailQuery.isLoading) {
    return (
      <div className="mt-1.5 rounded border border-border bg-accent/30 px-2.5 py-1.5 text-xs text-muted-foreground">
        Loading changes...
      </div>
    );
  }

  if (entries.length === 0) return null;

  return (
    <div className="mt-1.5 rounded border border-border bg-accent/30 px-2.5 py-1.5 space-y-1.5">
      <div className="space-y-0.5">
        {entries.map((entry) => (
          <div
            key={entry.id}
            className={`flex items-center gap-1.5 text-xs ${isReverted ? 'line-through text-muted-foreground/60' : 'text-muted-foreground'}`}
          >
            <span className="font-mono">
              {entry.action === 'create' ? '+' : entry.action === 'delete' ? '-' : '~'}
            </span>
            <span>
              {entry.action === 'create' ? 'Created' : entry.action === 'delete' ? 'Deleted' : 'Updated'}{' '}
              {entry.entityType}
              {entry.newState &&
                (() => {
                  try {
                    const parsed = JSON.parse(entry.newState);
                    return parsed.name || parsed.title ? `: ${parsed.name || parsed.title}` : '';
                  } catch {
                    return '';
                  }
                })()}
            </span>
          </div>
        ))}
      </div>

      {isReverted ? (
        <span className="text-[10px] font-medium text-muted-foreground italic">Reverted</span>
      ) : (
        <Button
          variant="ghost"
          size="sm"
          onClick={() => handleRevert()}
          disabled={revertMutation.isPending}
          className="h-6 gap-1 px-1.5 text-[10px]"
        >
          <Undo2 className="h-3 w-3" />
          {revertMutation.isPending ? 'Reverting...' : 'Revert'}
        </Button>
      )}

      {conflicts && (
        <div className="rounded border border-status-warning-border bg-status-warning-bg p-1.5">
          <p className="text-[10px] font-medium text-status-warning-fg">Conflicts:</p>
          <ul className="text-[10px] text-status-warning-fg list-disc pl-3">
            {conflicts.map((c, i) => (
              <li key={i}>{c}</li>
            ))}
          </ul>
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              setConflicts(null);
              handleRevert(true);
            }}
            disabled={revertMutation.isPending}
            className="mt-1 h-5 text-[10px]"
          >
            Force Revert
          </Button>
        </div>
      )}
    </div>
  );
}
