"use client";

import { useCallback } from "react";
import { Panel } from "@xyflow/react";
import { AnimatePresence, motion } from "motion/react";

import { Button } from "@turbostarter/ui-web/button";
import { Icons } from "@turbostarter/ui-web/icons";

import { useGraphStore } from "../../stores/useGraphStore";
import { useProposalDiff } from "~/modules/copilot/hooks/useProposalDiff";
import { acceptCurrentProposal, rejectCurrentProposal } from "~/modules/copilot/components/CopilotPanel";

interface ProposalBarProps {
  diagramId: string;
}

export function ProposalBar({ diagramId }: ProposalBarProps) {
  const proposalStatus = useGraphStore((s) => s.proposalStatus);
  const { changeSummary } = useProposalDiff();

  const handleAccept = useCallback(() => {
    acceptCurrentProposal(diagramId);
  }, [diagramId]);

  const handleReject = useCallback(() => {
    rejectCurrentProposal();
  }, []);

  return (
    <Panel position="bottom-center">
      <AnimatePresence>
        {proposalStatus === "pending" && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 20 }}
            role="alert"
            aria-label={`AI proposes: ${changeSummary}. Press Enter to accept, Escape to reject.`}
            className="flex items-center gap-3 rounded-lg border border-border bg-background/95 px-4 py-2.5 shadow-lg backdrop-blur-sm"
          >
            <span className="text-sm text-muted-foreground">{changeSummary}</span>
            <Button size="sm" onClick={handleAccept}>
              <Icons.Check className="mr-1 size-3" /> Accept
              <kbd className="ml-1.5 rounded bg-primary-foreground/20 px-1 text-[10px]">Enter</kbd>
            </Button>
            <Button size="sm" variant="ghost" onClick={handleReject}>
              <Icons.X className="mr-1 size-3" /> Reject
              <kbd className="ml-1.5 rounded bg-muted px-1 text-[10px]">Esc</kbd>
            </Button>
          </motion.div>
        )}
      </AnimatePresence>
    </Panel>
  );
}
