import { useState } from "react";
import { Box, Text, useInput } from "ink";

export interface ConfirmDialogProps {
  title: string;
  message: string;
  items: string[];
  showVisibilityToggle?: boolean;
  defaultVisibility?: "private" | "public";
  onConfirm: (options: { visibility?: "private" | "public" }) => void;
  onCancel: () => void;
}

export function ConfirmDialog({
  title,
  message,
  items,
  showVisibilityToggle = false,
  defaultVisibility = "private",
  onConfirm,
  onCancel,
}: ConfirmDialogProps) {
  const [visibility, setVisibility] = useState<"private" | "public">(
    defaultVisibility
  );

  useInput((input, key) => {
    if (input === "y" || input === "Y") {
      onConfirm({ visibility: showVisibilityToggle ? visibility : undefined });
    } else if (input === "n" || input === "N" || key.escape) {
      onCancel();
    } else if (showVisibilityToggle && (input === "v" || input === "V")) {
      setVisibility((prev) => (prev === "private" ? "public" : "private"));
    }
  });

  const maxItems = 5;
  const displayItems = items.slice(0, maxItems);
  const remainingCount = items.length - maxItems;

  return (
    <Box
      flexDirection="column"
      borderStyle="round"
      borderColor="yellow"
      paddingX={2}
      paddingY={1}
      width={50}
    >
      <Box marginBottom={1}>
        <Text bold color="yellow">
          {title}
        </Text>
      </Box>

      <Box marginBottom={1}>
        <Text>{message}</Text>
      </Box>

      <Box flexDirection="column" marginBottom={1}>
        {displayItems.map((item) => (
          <Text key={item} color="cyan">
            {"  • "}
            {item}
          </Text>
        ))}
        {remainingCount > 0 && (
          <Text dimColor>{"  "}...and {remainingCount} more</Text>
        )}
      </Box>

      {showVisibilityToggle && (
        <Box marginBottom={1}>
          <Text>Visibility: </Text>
          <Text
            bold
            color={visibility === "private" ? "green" : "yellow"}
          >
            {visibility === "private" ? "[●] Private" : "[ ] Private"}
          </Text>
          <Text> </Text>
          <Text
            bold
            color={visibility === "public" ? "green" : "yellow"}
          >
            {visibility === "public" ? "[●] Public" : "[ ] Public"}
          </Text>
          <Text dimColor> (v to toggle)</Text>
        </Box>
      )}

      <Box>
        <Text dimColor>Press </Text>
        <Text color="green" bold>
          y
        </Text>
        <Text dimColor> to confirm, </Text>
        <Text color="red" bold>
          n
        </Text>
        <Text dimColor> to cancel</Text>
      </Box>
    </Box>
  );
}
