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";
import { Trans } from "@lingui/react/macro";

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)}><Trans>Submit</Trans></Button>
      <Button variant="subtle" color="red" onClick={onClose}><Trans>Cancel</Trans></Button>
    </Stack>
  );
};

export default EditRules;
