import React, { useState } from "react";
import { marked } from "marked";
import type { CommentData } from "../../types/comments";

interface CommentFormProps {
  onAdd: (comment: CommentData) => void;
}

const CommentForm: React.FC<CommentFormProps> = ({ onAdd }) => {
  const [text, setText] = useState<string>("");
  const [markdownEnabled, setMarkdownEnabled] = useState<boolean>(false);
  const [preview, setPreview] = useState<boolean>(false);

  function handleSubmit() {
    if (!text.trim()) return;

    const newComment: CommentData = {
      user_name: "User",
      comment_text: text,
      created_at: new Date().toISOString(),
      markdown_enabled: markdownEnabled,
    };

    onAdd(newComment);
    setText("");
    setPreview(false);
  }

  return (
    <div className="comment-form">
      <textarea
        placeholder="Add a comment..."
        value={text}
        onChange={(e) => setText(e.target.value)}
      />

      <div className="comment-controls">
        <label className="toggle-label">
          <input
            type="checkbox"
            checked={markdownEnabled}
            onChange={() => setMarkdownEnabled((prev) => !prev)}
          />
          Enable Markdown
        </label>

        <label className="toggle-label">
          <input
            type="checkbox"
            disabled={!markdownEnabled}
            checked={preview}
            onChange={() => setPreview((prev) => !prev)}
          />
          Preview Markdown
        </label>

        <button className="btn" onClick={handleSubmit}>
          Add Comment
        </button>
      </div>

      {markdownEnabled && preview && (
        <div
          className="markdown-preview"
          dangerouslySetInnerHTML={{ __html: marked(text) }}
        />
      )}
    </div>
  );
};

export default CommentForm;
