import React, { useState } from 'react';
import ForumImageUpload from './ForumImageUpload';
import { IMAGE_LIMITS } from '../config/imageLimits';

interface CommentFormProps {
  onSubmit: (content: string, images: File[]) => Promise<void>;
  onCancel?: () => void;
  placeholder?: string;
  buttonText?: string;
  isReply?: boolean;
}

const CommentForm: React.FC<CommentFormProps> = ({
  onSubmit,
  onCancel,
  placeholder = 'Write your comment...',
  buttonText = 'Post Comment',
  isReply = false,
}) => {
  const [content, setContent] = useState('');
  const [imageFiles, setImageFiles] = useState<File[]>([]);
  const [imagePreviews, setImagePreviews] = useState<string[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    const remainingSlots = IMAGE_LIMITS.forum - imageFiles.length;
    const filesToAdd = files.slice(0, remainingSlots);

    setImageFiles((prev) => [...prev, ...filesToAdd]);

    filesToAdd.forEach((file) => {
      const reader = new FileReader();
      reader.onloadend = () => {
        setImagePreviews((prev) => [...prev, reader.result as string]);
      };
      reader.readAsDataURL(file);
    });

    e.target.value = "";
  };

  const handleRemoveImage = (index: number) => {
    setImageFiles((prev) => prev.filter((_, i) => i !== index));
    setImagePreviews((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!content.trim()) {
      setError('Comment cannot be empty');
      return;
    }

    setIsSubmitting(true);
    setError('');

    try {
      await onSubmit(content, imageFiles);
      setContent('');
      setImageFiles([]);
      setImagePreviews([]);
    } catch (err: any) {
      setError(err.message || 'Failed to post comment');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className={isReply ? 'ms-4' : ''}>
      <div className="mb-2">
        <textarea
          className={`form-control ${error ? 'is-invalid' : ''}`}
          rows={isReply ? 2 : 3}
          value={content}
          onChange={(e) => setContent(e.target.value)}
          placeholder={placeholder}
          disabled={isSubmitting}
        />
        {error && <div className="invalid-feedback">{error}</div>}
      </div>
      <ForumImageUpload
        imageFiles={imageFiles}
        imagePreviews={imagePreviews}
        onImageChange={handleImageChange}
        onRemoveImage={handleRemoveImage}
        compact={true}
      />
      <div className="d-flex gap-2">
        <button
          type="submit"
          className={`btn btn-${isReply ? 'sm btn-outline-' : ''}primary`}
          disabled={isSubmitting || !content.trim()}
        >
          {isSubmitting ? (
            <>
              <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
              Posting...
            </>
          ) : (
            buttonText
          )}
        </button>
        {onCancel && (
          <button
            type="button"
            className={`btn btn-${isReply ? 'sm btn-outline-' : ''}secondary`}
            onClick={onCancel}
            disabled={isSubmitting}
          >
            Cancel
          </button>
        )}
      </div>
    </form>
  );
};

export default CommentForm;
