import {
  Stack,
  Button
} from "@mantine/core";
import { useState, useCallback } from "react";
import { useTournament } from "../queries";
import useUpdateTournament from "../hooks/use-update-tournament";
import { RichTextEditor } from "@/components/rich-text-editor";

interface EditRulesProps {
  tournamentId: string;
  onClose?: () => void
}

const EditRules = ({ tournamentId, onClose }: EditRulesProps) => {
  const [search, setSearch] = useState("");

  const { data: tournament, isLoading: tournamentLoading } =
    useTournament(tournamentId);

  const { mutate: updateTournament, isPending: updatePending } = useUpdateTournament(tournamentId);
  const [value, setValue] = useState(tournament.rules);

  const handleSubmit = useCallback(
    (rules?: string) => {
      updateTournament({ rules }, {
        onSuccess: () => {
          onClose?.();
        }
      });
    },
    [updateTournament, tournamentId]
  );

  return (
    <Stack gap="xs" w="100%">
      <RichTextEditor value={value || ""} onChange={setValue} />
      <Button onClick={() => handleSubmit(value)}>Submit</Button>
      <Button variant="subtle" color="red" onClick={onClose}>Cancel</Button>
    </Stack>
  );
};

export default EditRules;
