import { useAppStore } from "@/stores/app-store";
import { useToggleReadOnly } from "@/hooks/use-read-only";
import { Button } from "@/components/ui/button";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { Lock, LockOpen } from "lucide-react";

export function ReadOnlyToggle() {
  const { activeConnectionId, readOnlyMap, connectedIds } = useAppStore();
  const toggleMutation = useToggleReadOnly();

  if (!activeConnectionId || !connectedIds.has(activeConnectionId)) {
    return null;
  }

  const isReadOnly = readOnlyMap[activeConnectionId] ?? true;

  const handleToggle = () => {
    if (isReadOnly) {
      const confirmed = window.confirm(
        "Switch to Read-Write mode?\n\nThis will allow executing INSERT, UPDATE, DELETE, DROP, and other mutating queries."
      );
      if (!confirmed) return;
    }
    toggleMutation.mutate({
      connectionId: activeConnectionId,
      readOnly: !isReadOnly,
    });
  };

  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          variant="ghost"
          size="xs"
          className={`gap-1.5 font-medium ${
            isReadOnly
              ? "text-warning hover:bg-warning/10 hover:text-warning"
              : "text-success hover:bg-success/10 hover:text-success"
          }`}
          onClick={handleToggle}
          disabled={toggleMutation.isPending}
        >
          {isReadOnly ? (
            <>
              <Lock className="h-3 w-3" />
              <span className="text-[11px] tracking-wide">Read-Only</span>
            </>
          ) : (
            <>
              <LockOpen className="h-3 w-3" />
              <span className="text-[11px] tracking-wide">Read-Write</span>
            </>
          )}
        </Button>
      </TooltipTrigger>
      <TooltipContent side="bottom">
        {isReadOnly
          ? "Read-Only mode: mutations are blocked. Click to enable writes."
          : "Read-Write mode: all queries are allowed. Click to restrict to read-only."}
      </TooltipContent>
    </Tooltip>
  );
}
