import { useFormContext, Controller } from "react-hook-form";
import FormError from "./FormError";
import { useState } from "react";
import QuillEditor from "../editor/quill/QuillEditor";

export interface FormQuillInputProps {
	name: string;
	label?: string;
	placeholder?: string;
	maxLength?: number;
	minLength?: number;
	className?: string;
	readOnly?: boolean;
	maxRows?: number;
	minRows?: number;
}

export function FormQuillInput({
	name,
	label,
	placeholder,
	maxLength,
	minLength,
	className,
	readOnly = false,
	maxRows = 10,
	minRows = 4,
}: FormQuillInputProps) {
	const [isFocused, setIsFocused] = useState(false);
	const {
		control,
		formState: { errors },
		trigger,
	} = useFormContext();

	const error = errors[name]?.message as string;

	const handleBlur = async () => {
		setIsFocused(false);
		await trigger(name);
	};
	console.log(isFocused);
	const containerClasses = `
    w-full rounded-md border bg-white shadow-sm
    transition-all duration-300 ease-out
    ${
		isFocused
			? `ring-2 ring-opacity-50 ${error ? "ring-red-200 border-red-500" : "ring-blue-200 border-blue-500"}`
			: "border-gray-300"
	}
    ${className}
  `.trim();
	return (
		<div className="space-y-2">
			{label && (
				<label className="block text-sm font-medium text-gray-700">
					{label}
				</label>
			)}
			<div className={containerClasses}>
				<Controller
					name={name}
					control={control}
					render={({ field: { value, onChange } }) => (
						<QuillEditor
							minRows={minRows}
							maxRows={maxRows}
							value={value}
							onChange={onChange}
							placeholder={placeholder}
							maxLength={maxLength}
							minLength={minLength}
							readOnly={readOnly}
							onFocus={() => setIsFocused(true)}
							onBlur={handleBlur}
						/>
					)}
				/>
			</div>
			<FormError error={error} />
		</div>
	);
}
