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

const AdminMediaEditPage = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user, userProfile, loading: authLoading } = useAuth();
  const [media, setMedia] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

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

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

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

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

    console.log('AdminMediaEditPage: User is admin, loading media for edit...');
    const loadMedia = async () => {
      try {
        setLoading(true);
        const { data, error: fetchError } = await getMediaById(id);

        if (fetchError) throw fetchError;

        setMedia(data);
      } catch (err) {
        console.error('Error loading media for edit:', err);
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      loadMedia();
    } else {
      setError('Media ID is missing.');
      setLoading(false);
    }

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

  const handleUpdate = async (formData) => {
    try {
      // Use the imported updateMedia function from pocketbaseService
      const success = await updateMedia(id, formData);

      if (success) {
        console.log('Media updated successfully!');
        navigate('/admin/media'); // Redirect back to the media list
      } else {
        throw new Error('Failed to update media'); // Handle potential non-success from service
      }

    } catch (err) {
      console.error('Error updating 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
  }


  if (loading) {
    return <div className="text-center py-8 text-campfire-light">Загрузка медиа для редактирования...</div>;
  }

  if (error) {
    return (
      <div className="bg-red-500/10 border border-red-500/20 text-red-500 p-4 rounded-lg mb-6">
        Ошибка: {error}
      </div>
    );
  }

  if (!media) {
    return <div className="text-center py-8 text-campfire-light">Медиа-контент не найден.</div>;
  }

  return (
    <div className="container-custom pt-20">
      <h1 className="text-3xl font-bold text-campfire-amber mb-8">Редактировать медиа</h1>
      <MediaForm
        mediaToEdit={media}
        onSuccess={() => navigate('/admin/media')} // Redirect on success
        onCancel={() => navigate('/admin/media')} // Redirect on cancel
      />
    </div>
  );
};

export default AdminMediaEditPage;
