import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api } from '../../api';
import './CreatePost.css';

const CreatePost = ({ currentUser, onClose = null }) => {
  const [imageUrl, setImageUrl] = useState('');
  const [description, setDescription] = useState('');
  const [title, setTitle] = useState('');
  const [location, setLocation] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

  const navigate = useNavigate();

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

    if (!imageUrl) {
      setError('Bitte gib eine Bild-URL ein.');
      return;
    }

    setLoading(true);
    setError('');

    try {
      await api('/api/posts', {
        method: 'POST',
        body: JSON.stringify({
          bild: imageUrl,
          title: title.trim(),
          description: description.trim(),
          ort: location.trim(),
        }),
      });

      setSuccess(true);
      setImageUrl('');
      setDescription('');
      setTitle('');
      setLocation('');

      if (typeof onClose === 'function') {
        setTimeout(() => onClose(), 1000);
      } else {
        setTimeout(() => navigate('/'), 1000);
      }
    } catch (err) {
      setError(`Fehler beim Erstellen des Posts: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    if (typeof onClose === 'function') {
      onClose();
    } else {
      navigate('/');
    }
  };

  return (
    <div className="create-post-container">
      <div className="create-post-form">
        <h2>Create new post</h2>

        {success ? (
          <div className="success-message">
            <p>Your post is created!</p>
          </div>
        ) : (
          <form onSubmit={handleSubmit}>
            <div className="create-post-input-group">
              <input
                type="url"
                placeholder="Bild-URL eingeben (http://example.com/image.jpg)"
                value={imageUrl}
                onChange={(e) => setImageUrl(e.target.value)}
                className="create-post-input"
              />
            </div>

            {imageUrl && (
              <div className="image-preview-container">
                <img
                  src={imageUrl}
                  alt="Preview"
                  className="image-preview"
                  onError={() => setError('Ungültige Bild-URL oder Bild kann nicht geladen werden')}
                  onLoad={() => setError('')}
                />
              </div>
            )}

            <input
              type="text"
              placeholder="Titel"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="create-post-input"
            />

            <textarea
              placeholder="Beschreibung"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="create-post-textarea"
            />

            <input
              type="text"
              placeholder="Ort"
              value={location}
              onChange={(e) => setLocation(e.target.value)}
              className="create-post-input"
            />

            {error && <p className="create-post-error">{error}</p>}

            <div className="create-post-actions">
              <button
                type="button"
                onClick={handleClose}
                className="cancel-button"
                disabled={loading}
              >
                Abbrechen
              </button>
              <button
                type="submit"
                className="submit-button"
                disabled={loading || !imageUrl}
              >
                {loading ? 'Wird erstellt...' : 'Posten'}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
};

export default CreatePost;
