import { useState } from "react";

import { Button, FloatingPanel } from "@ax/components";
import type { IDomainRobot } from "@ax/types";

import * as S from "./style";

const RobotsPanel = (props: IProps): JSX.Element => {
	const { isOpen, toggleModal, item, setItemContent } = props;

	const [value, setValue] = useState(item.content);

	const editItemAction = () => {
		setItemContent(value);
		toggleModal();
	};

	const resetItem = () => setValue("");

	const title = item.content ? "Update Robots.txt" : "Add Robots.txt";

	const editButton = {
		label: title,
		action: editItemAction,
	};

	const placeholder = "User-agent: * \nAllow: *";

	const noteTitle = "From site settings · read-only";

	const noteText = (
		<>
			Each site under this domain can define its own sitemap and visibility rules for search engines and LLMs from its
			{` `}
			<strong>site settings</strong>. Rules from all sites are listed below and will be combined with your custom rules
			above to generate the final robots.txt.
			<br />
			<br />
			{item.computedContent}
		</>
	);

	return (
		<FloatingPanel title={title} toggleModal={toggleModal} isOpen={isOpen}>
			<S.Wrapper>
				<S.Content>
					<S.Item>
						<S.ItemHeader>You are editing</S.ItemHeader>
						<S.ItemContent>{item.fullUrl}</S.ItemContent>
					</S.Item>
					<S.StyledFieldsBehavior
						fieldType="TextArea"
						onChange={setValue}
						value={value}
						title="Robots.txt"
						placeholder={placeholder}
					/>
					<Button buttonStyle="text" type="button" icon="refresh" disabled={!value} onClick={resetItem}>
						Reset to default
					</Button>
					{item.computedContent?.length > 0 && <S.StyledFNoteField value={{ title: noteTitle, text: noteText }} />}
				</S.Content>
				<S.Footer>
					<Button className="button" type="button" onClick={editButton.action}>
						{editButton.label}
					</Button>
				</S.Footer>
			</S.Wrapper>
		</FloatingPanel>
	);
};

interface IProps {
	item: IDomainRobot;
	isOpen: boolean;
	toggleModal(): any;
	setItemContent(content: string): void;
}

export default RobotsPanel;
