import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext'; // Adjusted path
import { createMedia } from '../../services/pocketbaseService'; // Adjusted path
import MediaForm from '../../components/admin/MediaForm'; // Adjusted path

const AdminMediaCreatePage = () => {
  const navigate = useNavigate();
  const { user, userProfile, loading: authLoading } = useAuth();
  const [error, setError] = useState(null);

  useEffect(() => {
    console.log('AdminMediaCreatePage mounted, user:', user);

    if (authLoading) {
      console.log('AdminMediaCreatePage: Auth loading...');
      return;
    }

    if (!user) {
      console.log('AdminMediaCreatePage: No user, redirecting to login');
      navigate('/login');
      return;
    }

    if (userProfile?.role !== 'admin') {
      console.log('AdminMediaCreatePage: Access denied');
      navigate('/');
      return;
    }

    console.log('AdminMediaCreatePage: User is admin, ready to create media...');

  }, [user, userProfile, authLoading, navigate]); // Depend on user, userProfile, authLoading


  const handleCreate = async (formData) => {
    try {
      // Use the imported createMedia function from pocketbaseService
      const { data, error: createError } = await createMedia(formData);

      if (createError) throw createError;

      console.log('Media created successfully!', data);
      navigate('/admin/media'); // Redirect back to the media list
    } catch (err) {
      console.error('Error creating media:', err);
      setError(err.message);
    }
  };

  if (authLoading) {
    return <div className="flex justify-center items-center h-screen text-campfire-light">Загрузка аутентификации...</div>;
  }

  if (!user || userProfile?.role !== 'admin') {
     return null; // Redirect handled by useEffect
  }


  return (
    <div className="container-custom pt-20">
      <h1 className="text-3xl font-bold text-campfire-amber mb-8">Добавить медиа</h1>
      {error && (
        <div className="bg-red-500/10 border border-red-500/20 text-red-500 p-4 rounded-lg mb-6">
          Ошибка: {error}
        </div>
      )}
      <MediaForm
        onSuccess={() => navigate('/admin/media')} // Redirect on success
        onCancel={() => navigate('/admin/media')} // Redirect on cancel
      />
    </div>
  );
};

export default AdminMediaCreatePage;
