import React, { useState, useEffect, useMemo } from 'react'; // Import useMemo
import { createMedia, updateMedia, validateMediaData, formatMediaData, getFileUrl, mediaTypes } from '../../services/pocketbaseService';
import { useAuth } from '../../contexts/AuthContext';
import { FaUpload, FaTimesCircle, FaTrash, FaCrop } from 'react-icons/fa'; // Import icons
import { v4 as uuidv4 } from 'uuid'; // Import uuid for unique IDs
import ImageCropper from '../common/ImageCropper';

// Define characteristic presets
const characteristicPresets = {
    movie: [
        { key: 'story', label: 'Сюжет' },
        { key: 'acting', label: 'Актерская игра' },
        { key: 'visuals', label: 'Визуал' },
        { key: 'sound', label: 'Звук' },
        { key: 'atmosphere', label: 'Атмосфера' },
        { key: 'pacing', label: 'Темп' },
    ],
    tv: [
        { key: 'story', label: 'Сюжет' },
        { key: 'acting', label: 'Актерская игра' },
        { key: 'visuals', label: 'Визуал' },
        { key: 'sound', label: 'Звук' },
        { key: 'characters', label: 'Персонажи' },
        { key: 'pacing', label: 'Темп' },
    ],
    game: [
        { key: 'updates', label: 'Сопровождение' },
        { key: 'story', label: 'Сюжет' },
        { key: 'gameplay', label: 'Геймплей' },
        { key: 'visual', label: 'Визуал' },
        { key: 'community', label: 'Сообщество' },
        { key: 'atmosphere', label: 'Атмосфера' },
        { key: 'soundtrack', label: 'Саундтрек' },
        { key: 'openworld', label: 'Открытый мир' },
    ],
     anime: [
        { key: 'story', label: 'Сюжет' },
        { key: 'characters', label: 'Персонажи' },
        { key: 'visuals', label: 'Визуал' },
        { key: 'sound', label: 'Звук' },
        { key: 'atmosphere', label: 'Атмосфера' },
        { key: 'pacing', label: 'Темп' },
    ],
    // Add more types as needed
};

// Define progress type options
const progressTypeOptions = [
    { value: 'hours', label: 'Часы (для игр)' },
    { value: 'watched', label: 'Просмотрено (для фильмов/сериалов)' },
    { value: 'completed', label: 'Пройдено (для сюжетных игр)' },
];


function MediaForm({ media, onSuccess }) {
  const [title, setTitle] = useState('');
  const [path, setPath] = useState('');
  const [type, setType] = useState('');
  const [overview, setOverview] = useState('');
  const [poster, setPoster] = useState(null);
  const [backdrop, setBackdrop] = useState(null);
  // Change characteristics state to an array of objects { id, key, label }
  const [characteristics, setCharacteristics] = useState([]);
  const [isPublished, setIsPublished] = useState(false);
  const [isPopular, setIsPopular] = useState(false); // State for is_popular
  const [progressType, setProgressType] = useState('completed'); // State for progress_type
  const [releaseDate, setReleaseDate] = useState(''); // State for release_date
  const [tmdbId, setTmdbId] = useState(null);
  const [tmdbType, setTmdbType] = useState(null);

  const [posterPreview, setPosterPreview] = useState(null);
  const [backdropPreview, setBackdropPreview] = useState(null);
  const [posterPosition, setPosterPosition] = useState({ x: 50, y: 50 }); // Добавляем состояние для позиции постера
  const [backdropPosition, setBackdropPosition] = useState({ x: 50, y: 50 }); // Добавляем состояние для позиции баннера
  const [posterScale, setPosterScale] = useState(1); // Добавляем состояние для масштаба постера
  const [backdropScale, setBackdropScale] = useState(1); // Добавляем состояние для масштаба баннера

  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState([]);

  const { user } = useAuth(); // Get current user

  const isEditing = !!media; // Determine if we are editing or creating

  const [showPosterCropper, setShowPosterCropper] = useState(false);
  const [showBackdropCropper, setShowBackdropCropper] = useState(false);
  const [tempPosterFile, setTempPosterFile] = useState(null);
  const [tempBackdropFile, setTempBackdropFile] = useState(null);

  useEffect(() => {
    if (media) {
      // Populate form for editing
      setTitle(media.title || '');
      setPath(media.path || '');
      setType(media.type || '');
      setOverview(media.overview || media.description || '');
      setTmdbId(media.tmdb_id || null);
      setTmdbType(media.tmdb_type || null);

      // Convert characteristics object from PocketBase to array of { id, key, label }
      let initialCharacteristicsArray = [];
      try {
         // Check if characteristics is already an object or needs parsing
         const rawCharacteristics = typeof media.characteristics === 'object' && media.characteristics !== null
             ? media.characteristics // It's already an object
             : (typeof media.characteristics === 'string' && media.characteristics ? JSON.parse(media.characteristics) : {}); // Parse if it's a string

         // Convert the object { key: label } to an array of { id, key, label }
         initialCharacteristicsArray = Object.entries(rawCharacteristics).map(([key, label]) => ({
             id: uuidv4(), // Generate a unique ID for React key
             key: key,
             label: label
         }));

      } catch (e) {
         console.error("Failed to parse characteristics JSON:", e);
         initialCharacteristicsArray = []; // Default to empty array on error
      }
      setCharacteristics(initialCharacteristicsArray);

      setIsPublished(media.is_published ?? false); // Use ?? for null/undefined check
      setIsPopular(media.is_popular ?? false); // Populate is_popular
      setProgressType(media.progress_type || 'completed'); // Populate progress_type, default to 'completed' if null/empty
      // Populate release_date, format to YYYY-MM-DD for input type="date"
      setReleaseDate(media.release_date ? new Date(media.release_date).toISOString().split('T')[0] : '');


      // Set initial previews for existing files
      setPosterPreview(getFileUrl(media, 'poster'));
      setBackdropPreview(getFileUrl(media, 'backdrop'));

    } else {
      // Reset form for creation
      setTitle('');
      setPath('');
      setType('');
      setOverview('');
      setPoster(null);
      setBackdrop(null);
      setCharacteristics([]); // Reset to empty array
      setIsPublished(false);
      setIsPopular(false); // Reset is_popular
      setProgressType('completed'); // Default progressType to 'completed' for new media
      setReleaseDate(''); // Reset release_date
      setTmdbId(null);
      setTmdbType(null);
      setPosterPreview(null);
      setBackdropPreview(null);
    }
     setErrors([]); // Clear errors on media change
  }, [media]);

  // Update path automatically when title changes, if creating
  useEffect(() => {
    if (!isEditing && title) {
      // Simple slugification: lowercase, replace spaces with hyphens, remove non-alphanumeric
      const slug = title
        .toLowerCase()
        .replace(/\s+/g, '-') // Replace spaces with hyphens
        .replace(/[^a-z0-9-]/g, '') // Remove non-alphanumeric except hyphens
        .replace(/--+/g, '-') // Replace multiple hyphens with single
        .replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
      setPath(slug);
    } else if (!isEditing && !title) {
        setPath(''); // Clear path if title is empty when creating
    }
  }, [title, isEditing]);


  // Handle change for characteristic label (now takes item id and new label)
  const handleCharacteristicLabelChange = (id, newLabel) => {
    setCharacteristics(prev =>
        prev.map(char =>
            char.id === id ? { ...char, label: newLabel } : char
        )
    );
  };

  // Handle change for characteristic key (now takes item id and new key)
  const handleCharacteristicKeyChange = (id, newKey) => {
      // Basic validation: key cannot be empty
      if (!newKey.trim()) {
          setErrors(prev => [...prev, 'Ключ характеристики не может быть пустым.']);
          return;
      }

      // Check for duplicate keys (excluding the item being edited)
      const isDuplicate = characteristics.some(char =>
          char.id !== id && char.key === newKey.trim()
      );

      if (isDuplicate) {
          setErrors(prev => [...prev, `Ключ характеристики "${newKey.trim()}" уже существует.`]);
          return;
      }

      setCharacteristics(prev =>
          prev.map(char =>
              char.id === id ? { ...char, key: newKey.trim() } : char
          )
      );
      setErrors(prev => prev.filter(err => !err.startsWith('Ключ характеристики'))); // Clear key-related errors on successful change
  };


  const handleAddCharacteristic = () => {
     // Check if max characteristics reached (8)
     if (characteristics.length >= 8) {
         setErrors(prev => [...prev, 'Максимальное количество характеристик - 8.']);
         return;
     }
     // Add a new characteristic object with a unique ID and default values
     const newChar = {
         id: uuidv4(),
         key: `new_char_${characteristics.length + 1}`, // Default key
         label: '' // Empty label
     };
     setCharacteristics(prev => [...prev, newChar]);
     setErrors(prev => prev.filter(err => !err.startsWith('Максимальное количество характеристик'))); // Clear max count error
  };

  const handleRemoveCharacteristic = (idToRemove) => {
     // Check if minimum characteristics reached (6)
     if (characteristics.length <= 6) {
         setErrors(prev => [...prev, 'Минимальное количество характеристик - 6.']);
         return;
     }
     setCharacteristics(prev => prev.filter(char => char.id !== idToRemove));
     setErrors(prev => prev.filter(err => !err.startsWith('Минимальное количество характеристик'))); // Clear min count error
  };


  // Determine if the current type has a preset
  const hasPreset = type && characteristicPresets[type];

  // Get the preset characteristics for the current type (memoized)
  const presetChars = useMemo(() => {
      if (hasPreset) {
          // Convert preset array to array of { id, key, label }
          return characteristicPresets[type].map(char => ({
              id: uuidv4(), // Generate new IDs for preset application
              key: char.key,
              label: char.label
          }));
      }
      return [];
  }, [type, hasPreset]); // Recompute if type or hasPreset changes


  // Function to apply a preset
  const applyPreset = () => {
      if (hasPreset) {
          setCharacteristics(presetChars); // Set the state with the memoized preset array
          setErrors(prev => prev.filter(err => !err.includes('характеристик'))); // Clear characteristic count errors
      }
  };


  const handleFileChange = (e, field) => {
    const file = e.target.files[0];
    if (file) {
      if (field === 'poster') {
        setTempPosterFile(file);
        setShowPosterCropper(true);
      } else if (field === 'backdrop') {
        setTempBackdropFile(file);
        setShowBackdropCropper(true);
      }
    }
  };

  const handleRemoveFile = (field) => {
      if (field === 'poster') {
          setPoster(null);
          setPosterPreview(null);
      } else if (field === 'backdrop') {
          setBackdrop(null);
          setBackdropPreview(null);
      }
  };

  // Добавляем функцию для обработки изменения позиции
  const handlePositionChange = (field, x, y) => {
    if (field === 'poster') {
      setPosterPosition({ x, y });
    } else if (field === 'backdrop') {
      setBackdropPosition({ x, y });
    }
  };

  // Добавляем функцию для обработки изменения масштаба
  const handleScaleChange = (field, scale) => {
    if (field === 'poster') {
      setPosterScale(scale);
    } else if (field === 'backdrop') {
      setBackdropScale(scale);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setErrors([]);

    const formData = new FormData();
    formData.append('title', title);
    formData.append('path', path);
    formData.append('type', type);
    formData.append('overview', overview);
    formData.append('is_published', isPublished);
    formData.append('is_popular', isPopular);
    formData.append('progress_type', progressType);
    
    if (releaseDate) {
        formData.append('release_date', releaseDate);
    }

    if (tmdbId) {
        formData.append('tmdb_id', tmdbId);
    }
    if (tmdbType) {
        formData.append('tmdb_type', tmdbType);
    }

    // Обработка файлов
    if (isEditing) {
      // При редактировании
      if (poster instanceof File) {
        // Если есть новый файл
        formData.append('poster', poster);
        // Если poster_src не существует или равен N/A, сохраняем оригинальный файл
        if (!media.poster_src || media.poster_src === 'N/A') {
          formData.append('poster_src', poster);
        }
      } else if (!posterPreview && media.poster) {
        // Если файл удален
        formData.append('poster', '');
        formData.append('poster_src', '');
      }

      if (backdrop instanceof File) {
        // Если есть новый файл
        formData.append('backdrop', backdrop);
        // Если backdrop_src не существует или равен N/A, сохраняем оригинальный файл
        if (!media.backdrop_src || media.backdrop_src === 'N/A') {
          formData.append('backdrop_src', backdrop);
        }
      } else if (!backdropPreview && media.backdrop) {
        // Если файл удален
        formData.append('backdrop', '');
        formData.append('backdrop_src', '');
      }
    } else {
      // При создании
      if (poster instanceof File) {
        formData.append('poster_src', poster);
        formData.append('poster', poster);
      }
      if (backdrop instanceof File) {
        formData.append('backdrop_src', backdrop);
        formData.append('backdrop', backdrop);
        }
    }

    // Convert characteristics array to object
    const characteristicsObject = characteristics.reduce((acc, char) => {
        if (char.key.trim()) {
            acc[char.key.trim()] = char.label;
        }
        return acc;
    }, {});

    // Append characteristics as a JSON string
    formData.append('characteristics', JSON.stringify(characteristicsObject));

    // Add created_by user ID if creating
    if (!isEditing && user) {
        formData.append('created_by', user.id);
    }

    try {
      if (isEditing) {
        await updateMedia(media.id, formData);
        console.log('Media updated successfully');
      } else {
        await createMedia(formData);
        console.log('Media created successfully');
      }
      onSuccess(); // Close modal and refresh list
    } catch (err) {
      console.error('Error submitting media form:', err);
       if (err.response && err.response.data) {
           console.error('PocketBase Response Data:', err.response.data);
           const apiErrors = [];
           for (const field in err.response.data) {
               if (err.response.data[field].message) {
                   apiErrors.push(`${field}: ${err.response.data[field].message}`);
               }
           }
           if (apiErrors.length > 0) {
               setErrors(apiErrors);
           } else {
               setErrors(['Произошла ошибка при сохранении контента.']);
           }
       } else {
           setErrors(['Произошла ошибка при сохранении контента.']);
       }
    } finally {
      setLoading(false);
    }
  };

  const handleCrop = (blob, type) => {
    const file = new File([blob], type === 'poster' ? 'poster.jpg' : 'backdrop.jpg', {
      type: 'image/jpeg'
    });

    if (type === 'poster') {
      setPoster(file);
      setPosterPreview(URL.createObjectURL(blob));
      setShowPosterCropper(false);
      setTempPosterFile(null);
    } else {
      setBackdrop(file);
      setBackdropPreview(URL.createObjectURL(blob));
      setShowBackdropCropper(false);
      setTempBackdropFile(null);
    }
  };

  const handleRecrop = async (type) => {
    try {
      let file;
      if (type === 'poster') {
        if (media?.poster_src) {
          // Используем оригинальный файл из poster_src
          const response = await fetch(getFileUrl(media, 'poster_src'));
          const blob = await response.blob();
          file = new File([blob], 'poster.jpg', { type: 'image/jpeg' });
        } else if (poster instanceof File) {
          file = poster;
        } else if (media?.poster) {
          const response = await fetch(getFileUrl(media, 'poster'));
          const blob = await response.blob();
          file = new File([blob], 'poster.jpg', { type: 'image/jpeg' });
        }
        if (file) {
          setTempPosterFile(file);
          setShowPosterCropper(true);
        }
      } else if (type === 'backdrop') {
        if (media?.backdrop_src) {
          // Используем оригинальный файл из backdrop_src
          const response = await fetch(getFileUrl(media, 'backdrop_src'));
          const blob = await response.blob();
          file = new File([blob], 'backdrop.jpg', { type: 'image/jpeg' });
        } else if (backdrop instanceof File) {
          file = backdrop;
        } else if (media?.backdrop) {
          const response = await fetch(getFileUrl(media, 'backdrop'));
          const blob = await response.blob();
          file = new File([blob], 'backdrop.jpg', { type: 'image/jpeg' });
        }
        if (file) {
          setTempBackdropFile(file);
          setShowBackdropCropper(true);
        }
      }
    } catch (error) {
      console.error('Error preparing image for recrop:', error);
    }
  };

  return (
    <div className="p-6 bg-campfire-charcoal rounded-lg shadow-md text-campfire-light max-h-[80vh] overflow-y-auto custom-scrollbar">
      <h2 className="text-2xl font-bold text-campfire-light mb-6 border-b border-campfire-ash/20 pb-4">
        {isEditing ? 'Редактировать контент' : 'Добавить новый контент'}
      </h2>

      {errors.length > 0 && (
        <div className="bg-status-error/20 text-status-error p-4 rounded-md mb-6 border border-status-error/30">
          <ul className="list-disc list-inside">
            {errors.map((err, index) => (
              <li key={index}>{err}</li>
            ))}
          </ul>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Basic Info */}
        <div>
          <label htmlFor="title" className="block text-sm font-medium text-campfire-light mb-1">
            Название <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            id="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="input w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
            required
          />
        </div>

        <div>
          <label htmlFor="path" className="block text-sm font-medium text-campfire-light mb-1">
            Путь (URL Slug) <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            id="path"
            value={path}
            onChange={(e) => setPath(e.target.value)}
            className="input w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
            required
          />
           <p className="mt-1 text-sm text-campfire-ash">
             Используется в URL (например, `/media/ваш-путь`). Только латинские буквы, цифры и дефисы.
           </p>
        </div>

        <div>
          <label htmlFor="type" className="block text-sm font-medium text-campfire-light mb-1">
            Тип <span className="text-red-500">*</span>
          </label>
          <select
            id="type"
            value={type}
            onChange={(e) => setType(e.target.value)}
            className="input w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
            required
          >
            <option value="">Выберите тип</option>
            {Object.entries(mediaTypes).map(([key, value]) => (
                <option key={key} value={key}>{value.label}</option>
            ))}
          </select>
        </div>

         {/* Progress Type Selection */}
        <div>
            <label htmlFor="progress_type" className="block text-sm font-medium text-campfire-light mb-1">
                Тип отслеживания прогресса <span className="text-red-500">*</span>
            </label>
            <select
                id="progress_type"
                value={progressType}
                onChange={(e) => setProgressType(e.target.value)}
                className="input w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
                required
            >
                {/* Removed default empty option, 'completed' is now the default state */}
                {progressTypeOptions.map(option => (
                    <option key={option.value} value={option.value}>{option.label}</option>
                ))}
            </select>
             <p className="mt-1 text-sm text-campfire-ash">
                Определяет, как пользователи будут отмечать прогресс (часы, просмотрено/нет, пройдено/нет).
             </p>
        </div>

        {/* Release Date */}
        <div>
            <label htmlFor="release_date" className="block text-sm font-medium text-campfire-light mb-1">
                Дата выхода
            </label>
            <input
                type="date"
                id="release_date"
                value={releaseDate}
                onChange={(e) => setReleaseDate(e.target.value)}
                className="input w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
            />
        </div>


        <div>
          <label htmlFor="overview" className="block text-sm font-medium text-campfire-light mb-1">
            Описание / Обзор
          </label>
          <textarea
            id="overview"
            rows="4"
            value={overview}
            onChange={(e) => setOverview(e.target.value)}
            className="input w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
          ></textarea>
        </div>

        {/* File Uploads */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Poster Upload with Controls */}
            <div>
                <label className="block text-sm font-medium text-campfire-light mb-1">
                    Постер
                </label>
                <div className="relative">
                    {posterPreview ? (
                        <div className="relative">
                            <img
                                src={posterPreview}
                                alt="Poster preview"
                                className="w-full h-64 object-contain rounded-lg"
                            />
                            <div className="absolute top-2 right-2 flex gap-2">
                                <button
                                    type="button"
                                    onClick={() => handleRecrop('poster')}
                                    className="p-2 bg-campfire-amber text-campfire-dark rounded-full hover:bg-campfire-amber/80"
                                >
                                    <FaCrop />
                                </button>
                            <button
                                type="button"
                                onClick={() => handleRemoveFile('poster')}
                                    className="p-2 bg-red-500 text-white rounded-full hover:bg-red-600"
                            >
                                    <FaTrash />
                            </button>
                            </div>
                        </div>
                    ) : (
                        <div className="border-2 border-dashed border-campfire-ash rounded-lg p-6 text-center">
                            <input
                                type="file"
                                accept="image/*"
                                onChange={(e) => handleFileChange(e, 'poster')}
                                className="hidden"
                                id="poster-upload"
                            />
                                <label
                                    htmlFor="poster-upload"
                                className="cursor-pointer flex flex-col items-center"
                            >
                                <FaUpload className="text-3xl text-campfire-ash mb-2" />
                                <span className="text-campfire-ash">
                                    Нажмите для загрузки постера
                                </span>
                                </label>
                        </div>
                    )}
                </div>
            </div>

            {/* Backdrop Upload with Controls */}
             <div>
                <label className="block text-sm font-medium text-campfire-light mb-1">
                    Фон (Backdrop)
                </label>
                <div className="relative">
                     {backdropPreview ? (
                        <div className="relative">
                            <img
                                src={backdropPreview}
                                alt="Backdrop preview"
                                className="w-full h-64 object-cover rounded-lg"
                            />
                            <div className="absolute top-2 right-2 flex gap-2">
                                <button
                                    type="button"
                                    onClick={() => handleRecrop('backdrop')}
                                    className="p-2 bg-campfire-amber text-campfire-dark rounded-full hover:bg-campfire-amber/80"
                                >
                                    <FaCrop />
                                </button>
                             <button
                                type="button"
                                onClick={() => handleRemoveFile('backdrop')}
                                    className="p-2 bg-red-500 text-white rounded-full hover:bg-red-600"
                            >
                                    <FaTrash />
                            </button>
                            </div>
                        </div>
                    ) : (
                        <div className="border-2 border-dashed border-campfire-ash rounded-lg p-6 text-center">
                            <input
                                type="file"
                                accept="image/*"
                                onChange={(e) => handleFileChange(e, 'backdrop')}
                                className="hidden"
                                id="backdrop-upload"
                            />
                                <label
                                    htmlFor="backdrop-upload"
                                className="cursor-pointer flex flex-col items-center"
                            >
                                <FaUpload className="text-3xl text-campfire-ash mb-2" />
                                <span className="text-campfire-ash">
                                    Нажмите для загрузки баннера
                                </span>
                                </label>
                        </div>
                    )}
                </div>
            </div>
        </div>


        {/* Characteristics */}
        <div className="border-t border-campfire-ash/20 pt-6 mt-6">
          <div className="flex justify-between items-center mb-4">
             <h3 className="text-xl font-bold text-campfire-light">
                Характеристики <span className="text-red-500">*</span>
             </h3>
             {hasPreset && (
                 <button
                     type="button"
                     onClick={applyPreset}
                     className="btn-secondary text-sm"
                 >
                     Применить пресет "{mediaTypes[type]?.label || type}"
                 </button>
             )}
          </div>

          <p className="mb-4 text-sm text-campfire-ash">
             Определите характеристики, по которым пользователи будут оценивать контент (минимум 6, максимум 8).
          </p>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> {/* Use grid for better layout */}
            {/* Map over the characteristics array */}
            {characteristics.map((char) => (
              <div key={char.id} className="flex items-center space-x-2 bg-campfire-dark rounded-md p-3 border border-campfire-ash/30"> {/* Styled container */}
                <div className="flex-1 grid grid-cols-2 gap-3"> {/* Inner grid for key/label */}
                    {/* Key Input */}
                    <div>
                        <label htmlFor={`char-key-${char.id}`} className="block text-xs font-medium text-campfire-ash mb-1">
                            Ключ (для системы)
                        </label>
                        <input
                            type="text"
                            id={`char-key-${char.id}`}
                            value={char.key}
                            onChange={(e) => handleCharacteristicKeyChange(char.id, e.target.value)}
                            className="input w-full px-2 py-1 bg-campfire-charcoal text-campfire-light border border-campfire-ash/20 rounded-md text-sm focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
                            placeholder="e.g., story"
                            required
                        />
                    </div>
                    {/* Label Input */}
                     <div>
                        <label htmlFor={`char-label-${char.id}`} className="block text-xs font-medium text-campfire-ash mb-1">
                            Название (для пользователей)
                        </label>
                        <input
                            type="text"
                            id={`char-label-${char.id}`}
                            value={char.label}
                            onChange={(e) => handleCharacteristicLabelChange(char.id, e.target.value)}
                            className="input w-full px-2 py-1 bg-campfire-charcoal text-campfire-light border border-campfire-ash/20 rounded-md text-sm focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
                            placeholder="e.g., Сюжет"
                            required
                        />
                    </div>
                </div>
                {characteristics.length > 6 && ( // Only show remove if more than 6
                    <button
                      type="button"
                      onClick={() => handleRemoveCharacteristic(char.id)}
                      className="text-status-error hover:text-red-700 transition-colors p-1"
                      aria-label={`Remove characteristic ${char.label}`}
                    >
                      <FaTimesCircle size={18} /> {/* Slightly smaller icon */}
                    </button>
                )}
              </div>
            ))}
          </div>

           {characteristics.length < 8 && ( // Only show add if less than 8
               <button
                 type="button"
                 onClick={handleAddCharacteristic}
                 className="btn-secondary mt-4 text-sm"
               >
                 Добавить характеристику
               </button>
           )}
        </div>


        {/* Status Toggles */}
        <div className="border-t border-campfire-ash/20 pt-6 mt-6">
            <h3 className="text-xl font-bold text-campfire-light mb-4">Статус</h3>
            <div className="flex items-center space-x-6">
                {/* Is Published */}
                <div className="flex items-center">
                    <input
                        type="checkbox"
                        id="is_published"
                        checked={isPublished}
                        onChange={(e) => setIsPublished(e.target.checked)}
                        className="w-4 h-4 text-campfire-amber bg-campfire-dark border-campfire-ash rounded focus:ring-campfire-amber focus:ring-2 cursor-pointer"
                    />
                    <label htmlFor="is_published" className="ml-2 text-campfire-light text-sm font-medium cursor-pointer">
                        Опубликовано
                    </label>
                </div>
                 {/* Is Popular */}
                 <div className="flex items-center">
                    <input
                        type="checkbox"
                        id="is_popular"
                        checked={isPopular}
                        onChange={(e) => setIsPopular(e.target.checked)}
                        className="w-4 h-4 text-campfire-amber bg-campfire-dark border-campfire-ash rounded focus:ring-campfire-amber focus:ring-2 cursor-pointer"
                    />
                    <label htmlFor="is_popular" className="ml-2 text-campfire-light text-sm font-medium cursor-pointer">
                        Популярное
                    </label>
                </div>
            </div>
        </div>


        {/* Submit Button */}
        <div className="flex justify-end mt-6">
          <button
            type="submit"
            disabled={loading}
            className={`btn-primary ${loading ? 'opacity-50 cursor-not-allowed' : ''} transition-colors duration-200`}
          >
            {loading ? (isEditing ? 'Сохранение...' : 'Создание...') : (isEditing ? 'Сохранить изменения' : 'Создать контент')}
          </button>
        </div>
      </form>

      {showPosterCropper && tempPosterFile && (
        <ImageCropper
          imageUrl={URL.createObjectURL(tempPosterFile)}
          onCrop={(blob) => handleCrop(blob, 'poster')}
          onCancel={() => {
            setShowPosterCropper(false);
            setTempPosterFile(null);
          }}
          aspectRatio={2/3}
          maxWidth={500}
          maxHeight={750}
        />
      )}

      {showBackdropCropper && tempBackdropFile && (
        <ImageCropper
          imageUrl={URL.createObjectURL(tempBackdropFile)}
          onCrop={(blob) => handleCrop(blob, 'backdrop')}
          onCancel={() => {
            setShowBackdropCropper(false);
            setTempBackdropFile(null);
          }}
          aspectRatio={16/9}
          maxWidth={1920}
          maxHeight={1080}
        />
      )}
    </div>
  );
}

export default MediaForm;
