import AutoExpandingTextArea from "@/components/Low/AutoExpandingTextarea";
import { Card, CardContent } from "@/components/ui/card";
import { useState } from "react";
import { MdEdit, MdEditOff } from "react-icons/md";

interface Props {
    value: string;
    onChange: (text: string) => void;
    wrapperCard?: boolean;
}

const PromptEdit: React.FC<Props> = ({ value, onChange, wrapperCard = true }) => {
    const [editing, setEditing] = useState(false);

    const renderTextWithLineBreaks = (text: string) => {
        const unescapedText = text.replace(/\\n/g, '\n');
        return unescapedText.split('\n').map((line, index, array) => (
            <span key={index}>
                {line}
                {index < array.length - 1 && <br />}
            </span>
        ));
    };

    const promptEditTsx = (
        <div className="flex justify-between items-start gap-4">
            {editing ? (
                <AutoExpandingTextArea
                    className="flex-1 p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:outline-none min-h-[100px]"
                    value={value}
                    onChange={onChange}
                    onBlur={() => setEditing(false)}
                />
            ) : (
                <div className="flex-1">
                    <h3 className="font-medium text-gray-800 mb-2">
                        Question/Instructions displayed to the student:
                    </h3>
                    <p className="text-gray-600">
                        {renderTextWithLineBreaks(value)}
                    </p>
                </div>
            )}
            <button
                onClick={() => setEditing(!editing)}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
            >
                {editing ? (
                    <MdEditOff size={20} className="text-gray-500" />
                ) : (
                    <MdEdit size={20} className="text-gray-500" />
                )}
            </button>
        </div>
    );

    if (!wrapperCard) {
        return promptEditTsx;
    }

    return (
        <Card className="mb-6">
            <CardContent className="p-4">
                {promptEditTsx}
            </CardContent>
        </Card>
    );
};

export default PromptEdit;
