'use client';

import * as React from 'react';
import dynamic from 'next/dynamic';
import {
  Box,
  Button,
  FormControl,
  Grid,
  IconButton,
  InputLabel,
  MenuItem,
  Modal,
  Select,
  Stack,
  TextField,
  Typography,
  useTheme,
  TablePagination,
  Chip,
} from '@mui/material';
import { Plus as PlusIcon } from '@phosphor-icons/react/dist/ssr/Plus';
import { Upload as UploadIcon } from '@phosphor-icons/react/dist/ssr/Upload';
import { X as CloseIcon } from '@phosphor-icons/react/dist/ssr/X';
import { VideoCamera as VideoCameraIcon } from '@phosphor-icons/react/dist/ssr/VideoCamera';
import { FileText as FileTextIcon } from '@phosphor-icons/react/dist/ssr/FileText';
import { Article as ArticleIcon } from '@phosphor-icons/react/dist/ssr/Article';
import { toast, Toaster } from 'react-hot-toast';

import { TrainingFilters } from '@/components/dashboard/training/training-filters';
import { AppLoader } from '@/components/core/app-loader';
import { TrainingContentCard } from '@/components/dashboard/training/training-content-card';
// import { TrainingCategoryCard } from '@/components/dashboard/training/training-category-card';
import trainingService, {
  type TrainingContent,
  // type TrainingCategory,
  type UploadTrainingData,
  // type CreateCategoryData,
} from '@/services/training.service';

import 'react-quill/dist/quill.snow.css';

const ReactQuill = dynamic(() => import('react-quill'), { ssr: false });

// Content types
type ContentType = 'video' | 'document' | 'blog';

export default function TrainingPage(): React.JSX.Element {
  const theme = useTheme();
  
  // Tab state - only content tab now
  const [selectedTab, setSelectedTab] = React.useState(0);
  
  // Modal states
  const [contentModalOpen, setContentModalOpen] = React.useState(false);
  const [detailModalOpen, setDetailModalOpen] = React.useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = React.useState(false);
  const [selectedContent, setSelectedContent] = React.useState<TrainingContent | null>(null);
  const [contentToDelete, setContentToDelete] = React.useState<TrainingContent | null>(null);
  
  // Data states
  const [trainingContent, setTrainingContent] = React.useState<TrainingContent[]>([]);
  // const [trainingCategories, setTrainingCategories] = React.useState<TrainingCategory[]>([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [modalLoading, setModalLoading] = React.useState(false);
  
  // Pagination states
  const [contentPage, setContentPage] = React.useState(0);
  const [contentRowsPerPage, setContentRowsPerPage] = React.useState(10);
  // const [categoryPage, setCategoryPage] = React.useState(0);
  // const [categoryRowsPerPage, setCategoryRowsPerPage] = React.useState(10);
  const [totalContent, setTotalContent] = React.useState(0);
  // const [totalCategories, setTotalCategories] = React.useState(0);
  
  // Search states
  const [contentSearchQuery, setContentSearchQuery] = React.useState('');
  // const [categorySearchQuery, setCategorySearchQuery] = React.useState('');
  const [contentTypeFilter, setContentTypeFilter] = React.useState<'all' | ContentType>('all');
  
  // Form states
  const [contentType, setContentType] = React.useState<ContentType>('video');
  const [title, setTitle] = React.useState('');
  const [description, setDescription] = React.useState('');
  const [blogContent, setBlogContent] = React.useState('');
  const [videoFile, setVideoFile] = React.useState<File | null>(null);
  const [documentFile, setDocumentFile] = React.useState<File | null>(null);
  // const [categoryName, setCategoryName] = React.useState('');
  // const [categoryImage, setCategoryImage] = React.useState<File | null>(null);
  
  // Edit mode states
  const [isEditMode, setIsEditMode] = React.useState(false);
  const [editingContentId, setEditingContentId] = React.useState<string | null>(null);
  
  // Preview states
  const [videoPreview, setVideoPreview] = React.useState<string | null>(null);
  const [documentPreview, setDocumentPreview] = React.useState<string | null>(null);
  // const [categoryImagePreview, setCategoryImagePreview] = React.useState<string | null>(null);
  
  // Media removal states
  const [removeVideo, setRemoveVideo] = React.useState(false);
  const [removeDocument, setRemoveDocument] = React.useState(false);
  
  // Edit mode existing content state
  const [existingContent, setExistingContent] = React.useState<TrainingContent | null>(null);

  // Fetch training content
  const fetchTrainingContent = React.useCallback(async () => {
    try {
      setIsLoading(true);
      const params = {
        skip: contentPage,
        limit: contentRowsPerPage,
        ...(contentSearchQuery && { title: contentSearchQuery }),
        ...(contentTypeFilter !== 'all' && { searchType: contentTypeFilter }),
      };
      
      const response = await trainingService.fetchAllTraining(params);
      // Handle different possible response structures
      const contentData = response.data || response || [];
      const totalCount = response.totalCount || contentData.length || 0;
      
      setTrainingContent(Array.isArray(contentData) ? contentData : []);
      setTotalContent(totalCount);
    } catch (error) {
      console.error('Error fetching training content:', error);
      toast.error('Failed to fetch training content');
    } finally {
      setIsLoading(false);
    }
  }, [contentPage, contentRowsPerPage, contentSearchQuery, contentTypeFilter]);

  // Commented out category fetching functionality
  /*
  const fetchTrainingCategories = React.useCallback(async () => {
    try {
      setIsLoading(true);
      const params = {
        skip: categoryPage,
        limit: categoryRowsPerPage,
        ...(categorySearchQuery && { categoryName: categorySearchQuery }),
      };
      
      const response = await trainingService.fetchAllTrainingCategories(params);
      setTrainingCategories(response.data || []);
      setTotalCategories(response.totalCount || 0);
    } catch (error) {
      console.error('Error fetching training categories:', error);
      toast.error('Failed to fetch training categories');
    } finally {
      setIsLoading(false);
    }
  }, [categoryPage, categoryRowsPerPage, categorySearchQuery]);
  */

  // Load data on mount and when dependencies change
  React.useEffect(() => {
    fetchTrainingContent();
  }, [fetchTrainingContent]);

  // Handle tab change
  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setSelectedTab(newValue);
  };

  // Handle file uploads
  const handleVideoFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setVideoFile(file);
      const previewUrl = URL.createObjectURL(file);
      setVideoPreview(previewUrl);
    }
  };

  const handleDocumentFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setDocumentFile(file);
      setDocumentPreview(file.name);
    }
  };

  // Commented out category image handling
  /*
  const handleCategoryImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setCategoryImage(file);
      const previewUrl = URL.createObjectURL(file);
      setCategoryImagePreview(previewUrl);
    }
  };
  */

  // Handle form submissions
  const handleContentSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    
    try {
      setModalLoading(true);
      
      const data: UploadTrainingData = {};
      
      // Always include title and description if provided
      if (title) data.title = title;
      if (description) data.description = description;
      
      if (contentType === 'video') {
        if (removeVideo) {
          data.removeVideo = true;
          // If user is adding a new video after removing, include it
          if (videoFile) {
            data.videoMedia = videoFile;
          }
        } else if (videoFile) {
          data.videoMedia = videoFile;
        }
      } else if (contentType === 'document') {
        if (removeDocument) {
          data.removeDocument = true;
          // If user is adding a new document after removing, include it
          if (documentFile) {
            data.documentMedia = documentFile;
          }
        } else if (documentFile) {
          data.documentMedia = documentFile;
        }
      } else if (contentType === 'blog') {
        if (blogContent) {
          data.blogContent = blogContent;
        }
      }
      
      // Validation for new content
      if (!isEditMode) {
        if (contentType === 'video' && !videoFile) {
          toast.error('Please select a video file');
          return;
        }
        if (contentType === 'document' && !documentFile) {
          toast.error('Please select a document file');
          return;
        }
        if (contentType === 'blog' && !blogContent) {
          toast.error('Please provide blog content');
          return;
        }
      }
      
      if (isEditMode && editingContentId) {
        // Update existing content
        console.log('Updating training with data:', data);
        await trainingService.updateTraining(editingContentId, data);
        toast.success('Training content updated successfully!');
      } else {
        // Create new content
        console.log('Creating training with data:', data);
        await trainingService.uploadTraining(data);
        toast.success('Training content uploaded successfully!');
      }
      
      setContentModalOpen(false);
      resetContentForm();
      await fetchTrainingContent(); // Wait for refresh to complete
    } catch (error: any) {
      console.error('Error saving training content:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'An unexpected error occurred';
      toast.error(isEditMode ? `Failed to update: ${errorMessage}` : `Failed to upload: ${errorMessage}`);
    } finally {
      setModalLoading(false);
    }
  };

  // Commented out category submit functionality
  /*
  const handleCategorySubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    
    if (!categoryName || !categoryImage) {
      toast.error('Please provide category name and image');
      return;
    }
    
    try {
      setIsLoading(true);
      
      const data: CreateCategoryData = {
        categoryName,
        media: categoryImage,
      };
      
      await trainingService.createTrainingCategory(data);
      
      toast.success('Training category created successfully!');
      resetCategoryForm();
      fetchTrainingCategories();
    } catch (error) {
      console.error('Error creating training category:', error);
      toast.error('Failed to create training category');
    } finally {
      setIsLoading(false);
    }
  };
  */

  // Reset forms
  const resetContentForm = () => {
    setTitle('');
    setDescription('');
    setBlogContent('');
    setVideoFile(null);
    setDocumentFile(null);
    setVideoPreview(null);
    setDocumentPreview(null);
    setContentType('video');
    setIsEditMode(false);
    setEditingContentId(null);
    // Reset removal flags
    setRemoveVideo(false);
    setRemoveDocument(false);
    // Reset existing content
    setExistingContent(null);
  };

  // Commented out category form reset
  /*
  const resetCategoryForm = () => {
    setCategoryName('');
    setCategoryImage(null);
    setCategoryImagePreview(null);
  };
  */

  // Content action handlers
  const handleContentEdit = async (content: TrainingContent) => {
    try {
      setModalLoading(true);
      
      // First reset the form to clear any previous state
      resetContentForm();
      
      // Fetch the latest content data to ensure we have all fields
      let fullContent: TrainingContent;
      try {
        fullContent = await trainingService.getTrainingById(content._id);
        console.log('Fetched content for edit:', fullContent); // Debug log
      } catch (apiError) {
        console.warn('Failed to fetch latest content, using provided content:', apiError);
        // Fallback to the content passed from the card if API fails
        fullContent = content;
      }
      
      // Pre-fill the form with existing content data
      setTitle(fullContent.title || '');
      setDescription(fullContent.description || '');
      setBlogContent(fullContent.blogContent || '');
      
      // Store existing content for reference
      setExistingContent(fullContent);
      
      // Determine content type based on available media and set up previews
      if (fullContent.videoMediaData && fullContent.videoMediaData.fileUrl) {
        setContentType('video');
        // Set preview for existing video
        setVideoPreview(fullContent.videoMediaData.fileUrl);
        console.log('Setting video preview:', fullContent.videoMediaData.fileUrl);
      } else if (fullContent.documentMediaData && fullContent.documentMediaData.fileUrl) {
        setContentType('document');
        // Set preview for existing document
        setDocumentPreview(fullContent.documentMediaData.fileName || 'Document');
        console.log('Setting document preview:', fullContent.documentMediaData.fileName);
      } else if (fullContent.blogContent) {
        setContentType('blog');
        console.log('Setting blog content type');
      } else {
        // Check for legacy fields if new structure is not available
        if (fullContent.videoMedia) {
          setContentType('video');
        } else if (fullContent.documentMedia) {
          setContentType('document');
        } else {
          // Default to video if no content type can be determined
          setContentType('video');
        }
        console.log('Using fallback content type detection');
      }
      
      // Set edit mode
      setIsEditMode(true);
      setEditingContentId(content._id);
      
      // Open modal after all states are set
      setTimeout(() => {
        setContentModalOpen(true);
      }, 100); // Small delay to ensure state updates are processed
      
      toast.success('Content loaded for editing');
    } catch (error) {
      console.error('Error loading content for edit:', error);
      toast.error('Failed to load content for editing');
    } finally {
      setModalLoading(false);
    }
  };

  const handleContentDelete = (content: TrainingContent) => {
    setContentToDelete(content);
    setDeleteModalOpen(true);
  };

  const confirmDelete = async () => {
    if (!contentToDelete) return;
    
    try {
      setDeleteModalOpen(false);
      // Show a loading toast instead of the full page loader
      const loadingToast = toast.loading('Deleting content...');
      await trainingService.deleteTraining(contentToDelete._id);
      toast.dismiss(loadingToast);
      toast.success('Training content deleted successfully!');
      fetchTrainingContent(); // Refresh the list
    } catch (error) {
      console.error('Error deleting training content:', error);
      toast.error('Failed to delete training content');
    } finally {
      setContentToDelete(null);
    }
  };

  const cancelDelete = () => {
    setDeleteModalOpen(false);
    setContentToDelete(null);
  };

  const handleContentDetail = (content: TrainingContent) => {
    setSelectedContent(content);
    setDetailModalOpen(true);
  };

  // Commented out category handlers
  /*
  const handleCategoryEdit = (category: TrainingCategory) => {
    toast.info('Edit functionality will be implemented');
  };

  const handleCategoryDelete = (category: TrainingCategory) => {
    toast.info('Delete functionality will be implemented');
  };

  const handleCategoryDetail = (category: TrainingCategory) => {
    toast.info('Detail view will be implemented');
  };
  */

  return (
    <Box
      sx={{
        bgcolor: theme.palette.mode === 'dark' ? '#0f172a' : '#fafbfc',
        minHeight: '100vh',
        p: 3,
      }}
    >
      <Toaster position="top-right" />
      
      {/* Header */}
      <Stack
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        sx={{
          mb: 4,
          p: 3,
          borderRadius: 4,
          background: '#FFDD31',
          color: '#0B0504',
        }}
      >
        <Box>
          <Typography variant="h4" fontWeight={700} gutterBottom>
            🎓 Training Management
          </Typography>
          <Typography variant="body1" sx={{ opacity: 0.9 }}>
            Upload and manage training videos, documents, and blog content
          </Typography>
        </Box>
        <Button
          variant="contained"
          startIcon={<PlusIcon size={20} />}
          onClick={() => setContentModalOpen(true)}
          sx={{
            bgcolor: 'rgba(11, 5, 4, 0.8)',
            color: '#FFDD31',
            borderRadius: 3,
            px: 3,
            py: 1.5,
            fontWeight: 600,
            border: '1px solid rgba(11, 5, 4, 0.9)',
            '&:hover': {
              bgcolor: 'rgba(11, 5, 4, 0.9)',
              transform: 'translateY(-2px)',
            },
            transition: 'all 0.3s ease',
          }}
        >
          Add Content
        </Button>
      </Stack>

      {/* Filters - simplified for content only */}
      <TrainingFilters
        value={selectedTab}
        onChange={handleTabChange}
        onSearchChange={setContentSearchQuery}
        onCategorySearch={() => {}} // Placeholder since categories are disabled
        onContentTypeChange={setContentTypeFilter}
      />

      {/* Content Area */}
      <Box
        sx={{
          position: 'relative',
          p: 3,
          borderRadius: 4,
          background: theme.palette.mode === 'dark' 
            ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
            : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
          border: theme.palette.mode === 'dark' 
            ? '1px solid #475569' 
            : '1px solid rgba(255, 255, 255, 0.2)',
          boxShadow: theme.palette.mode === 'dark' 
            ? '0 8px 32px rgba(0, 0, 0, 0.3)' 
            : '0 8px 32px rgba(0, 0, 0, 0.08)',
          minHeight: '400px',
          overflow: 'hidden',
        }}
      >
        {isLoading && <AppLoader fill size="lg" label="Loading training content..." />}

        {/* Training Content Grid */}
        <Grid container spacing={3} sx={{ mt: '5px' }}>
          {trainingContent && trainingContent.length > 0 && trainingContent.map((content) => (
            <Grid key={content._id} item xs={12} sm={6} md={4} lg={3}>
              <TrainingContentCard
                content={content}
                onEdit={handleContentEdit}
                onDelete={handleContentDelete}
                onDetail={handleContentDetail}
              />
            </Grid>
          ))}
        </Grid>
        
        {trainingContent.length === 0 && !isLoading && (
          <Box sx={{ textAlign: 'center', py: 8 }}>
            <Typography variant="h6" color="text.secondary" gutterBottom>
              No training content found
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Start by adding your first training content
            </Typography>
          </Box>
        )}
        
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>
          <TablePagination
            rowsPerPageOptions={[10, 20, 50]}
            component="div"
            count={totalContent}
            rowsPerPage={contentRowsPerPage}
            page={contentPage}
            onPageChange={(_, newPage) => setContentPage(newPage)}
            onRowsPerPageChange={(event) => {
              setContentRowsPerPage(parseInt(event.target.value, 10));
              setContentPage(0);
            }}
          />
        </Box>
      </Box>

      {/* Add Content Modal */}
      <Modal
        open={contentModalOpen}
        onClose={() => {
          setContentModalOpen(false);
          resetContentForm();
        }}
        sx={{ 
          backdropFilter: 'blur(12px)',
          backgroundColor: theme.palette.mode === 'dark' 
            ? 'rgba(0, 0, 0, 0.7)' 
            : 'rgba(0, 0, 0, 0.5)',
        }}
      >
        <Box
          sx={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: '95%',
            maxWidth: 800,
            maxHeight: '95vh',
            bgcolor: 'background.paper',
            outline: 'none',
            boxShadow: theme.palette.mode === 'dark' 
              ? '0 24px 48px rgba(0, 0, 0, 0.4), 0 8px 16px rgba(0, 0, 0, 0.2)' 
              : '0 24px 48px rgba(0, 0, 0, 0.15), 0 8px 16px rgba(0, 0, 0, 0.1)',
            borderRadius: 4,
            overflowY: 'auto',
            border: theme.palette.mode === 'dark' 
              ? '1px solid rgba(255, 255, 255, 0.12)' 
              : '1px solid rgba(0, 0, 0, 0.12)',
          }}
        >
          {/* Modal Header */}
          <Box
            sx={{
              position: 'relative',
              p: 4,
              pb: 2,
              background: theme.palette.mode === 'dark' 
                ? 'linear-gradient(135deg, #ffd700 0%, #ffed4a 100%)' 
                : 'linear-gradient(135deg, #1a202c 0%, #2d3748 100%)',
              color: theme.palette.mode === 'dark' ? '#1a202c' : '#ffffff',
              borderTopLeftRadius: 16,
              borderTopRightRadius: 16,
            }}
          >
            <IconButton
              onClick={() => {
                setContentModalOpen(false);
                resetContentForm();
              }}
              sx={{
                position: 'absolute',
                top: 16,
                right: 16,
                color: theme.palette.mode === 'dark' ? '#1a202c' : '#ffffff',
              }}
            >
              <CloseIcon />
            </IconButton>
            <Typography variant="h4" component="h1" fontWeight={700} textAlign="center">
              {isEditMode ? '✏️ Edit Training Content' : '📚 Add Training Content'}
            </Typography>
            <Typography variant="body1" textAlign="center" sx={{ opacity: 0.9, mt: 1 }}>
              {isEditMode ? 'Modify and update your training content' : 'Upload videos, documents, or create blog content'}
            </Typography>
          </Box>

          {/* Modal Content */}
          <Box sx={{ p: 4 }}>
            <form onSubmit={handleContentSubmit}>
              {/* Content Type Selection */}
              <FormControl fullWidth sx={{ mb: 3 }}>
                <InputLabel>Content Type</InputLabel>
                <Select
                  value={contentType}
                  onChange={(e) => setContentType(e.target.value as ContentType)}
                  label="Content Type"
                >
                  <MenuItem value="video">
                    <Stack direction="row" alignItems="center" spacing={1}>
                      <VideoCameraIcon size={20} />
                      <span>Video</span>
                    </Stack>
                  </MenuItem>
                  <MenuItem value="document">
                    <Stack direction="row" alignItems="center" spacing={1}>
                      <FileTextIcon size={20} />
                      <span>Document</span>
                    </Stack>
                  </MenuItem>
                  <MenuItem value="blog">
                    <Stack direction="row" alignItems="center" spacing={1}>
                      <ArticleIcon size={20} />
                      <span>Blog Post</span>
                    </Stack>
                  </MenuItem>
                </Select>
              </FormControl>

              {/* Title and Description */}
              <TextField
                fullWidth
                label="Title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                sx={{ mb: 2 }}
              />
              
              <TextField
                fullWidth
                label="Description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                multiline
                rows={3}
                sx={{ mb: 3 }}
              />

              {/* Content Type Specific Fields */}
              {contentType === 'video' && (
                <Box sx={{ mb: 3 }}>
                  <Typography variant="subtitle1" gutterBottom>
                    Video Upload
                  </Typography>
                  
                  {/* Show existing video info and removal option in edit mode */}
                  {isEditMode && existingContent?.videoMediaData && !removeVideo && (
                    <Box sx={{ mb: 2, p: 2, bgcolor: theme.palette.mode === 'dark' ? '#1e293b' : '#f8fafc', borderRadius: 2 }}>
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        Current video: {existingContent.videoMediaData.fileName}
                      </Typography>
                      <Button
                        variant="outlined"
                        color="error"
                        size="small"
                        onClick={() => {
                          setRemoveVideo(true);
                          setVideoPreview(null);
                        }}
                        sx={{ mr: 1 }}
                      >
                        Remove Video
                      </Button>
                    </Box>
                  )}
                  
                  {/* Show removal confirmation in edit mode */}
                  {isEditMode && removeVideo && (
                    <Box sx={{ mb: 2, p: 2, bgcolor: '#fef2f2', border: '1px solid #fecaca', borderRadius: 2 }}>
                      <Typography variant="body2" color="error" gutterBottom>
                        Video will be removed when you save
                      </Typography>
                      <Button
                        variant="outlined"
                        size="small"
                        onClick={() => {
                          setRemoveVideo(false);
                          if (existingContent?.videoMediaData) {
                            setVideoPreview(existingContent.videoMediaData.fileUrl);
                          }
                        }}
                      >
                        Keep Video
                      </Button>
                    </Box>
                  )}
                  
                  {/* File upload button - show when creating new content, removing existing video, or no existing video */}
                  {(!isEditMode || !existingContent?.videoMediaData || removeVideo) && (
                    <Button
                      variant="outlined"
                      component="label"
                      startIcon={<UploadIcon />}
                      fullWidth
                      sx={{ mb: 2 }}
                    >
                      {removeVideo && existingContent?.videoMediaData ? 'Replace Video File' : 'Select Video File'}
                      <input
                        type="file"
                        hidden
                        accept="video/*"
                        onChange={handleVideoFileChange}
                      />
                    </Button>
                  )}
                  
                  {/* Show preview for existing video (when not removed) or new uploaded video */}
                  {videoPreview && !removeVideo && (
                    <Box sx={{ mt: 2 }}>
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        {videoFile ? 'New video preview:' : 'Current video:'}
                      </Typography>
                      <video
                        src={videoPreview}
                        controls
                        style={{ width: '100%', maxHeight: '300px', borderRadius: '8px' }}
                      />
                      {videoFile && (
                        <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
                          File: {videoFile.name}
                        </Typography>
                      )}
                    </Box>
                  )}
                </Box>
              )}

              {contentType === 'document' && (
                <Box sx={{ mb: 3 }}>
                  <Typography variant="subtitle1" gutterBottom>
                    Document Upload
                  </Typography>
                  
                  {/* Show existing document info and removal option in edit mode */}
                  {isEditMode && existingContent?.documentMediaData && !removeDocument && (
                    <Box sx={{ mb: 2, p: 2, bgcolor: theme.palette.mode === 'dark' ? '#1e293b' : '#f8fafc', borderRadius: 2 }}>
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        Current document: {existingContent.documentMediaData.fileName}
                      </Typography>
                      <Button
                        variant="outlined"
                        color="error"
                        size="small"
                        onClick={() => {
                          setRemoveDocument(true);
                          setDocumentPreview(null);
                        }}
                        sx={{ mr: 1 }}
                      >
                        Remove Document
                      </Button>
                    </Box>
                  )}
                  
                  {/* Show removal confirmation in edit mode */}
                  {isEditMode && removeDocument && (
                    <Box sx={{ mb: 2, p: 2, bgcolor: '#fef2f2', border: '1px solid #fecaca', borderRadius: 2 }}>
                      <Typography variant="body2" color="error" gutterBottom>
                        Document will be removed when you save
                      </Typography>
                      <Button
                        variant="outlined"
                        size="small"
                        onClick={() => {
                          setRemoveDocument(false);
                          if (existingContent?.documentMediaData) {
                            setDocumentPreview(existingContent.documentMediaData.fileName);
                          }
                        }}
                      >
                        Keep Document
                      </Button>
                    </Box>
                  )}
                  
                  {/* File upload button - show when creating new content, removing existing document, or no existing document */}
                  {(!isEditMode || !existingContent?.documentMediaData || removeDocument) && (
                    <Button
                      variant="outlined"
                      component="label"
                      startIcon={<UploadIcon />}
                      fullWidth
                      sx={{ mb: 2 }}
                    >
                      {removeDocument && existingContent?.documentMediaData ? 'Replace Document File' : 'Select Document File'}
                      <input
                        type="file"
                        hidden
                        accept=".pdf,.doc,.docx,.txt"
                        onChange={handleDocumentFileChange}
                      />
                    </Button>
                  )}
                  
                  {/* Show preview for existing document (when not removed) or new uploaded document */}
                  {documentPreview && !removeDocument && (
                    <Box sx={{ mt: 1 }}>
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        {documentFile ? 'New document:' : 'Current document:'}
                      </Typography>
                      <Chip
                        label={documentPreview}
                        color="primary"
                        variant="outlined"
                        sx={{ fontSize: '0.875rem' }}
                      />
                      {documentFile && (
                        <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
                          File: {documentFile.name} ({(documentFile.size / 1024 / 1024).toFixed(2)} MB)
                        </Typography>
                      )}
                    </Box>
                  )}
                </Box>
              )}

              {contentType === 'blog' && (
                <Box sx={{ mb: 3 }}>
                  <Typography variant="subtitle1" gutterBottom>
                    Blog Content
                  </Typography>
                  <Box sx={{ '& .ql-editor': { minHeight: '200px' } }}>
                    <ReactQuill
                      value={blogContent}
                      onChange={setBlogContent}
                      placeholder="Write your blog content here..."
                    />
                  </Box>
                </Box>
              )}

              {/* Submit Button */}
              <Button
                type="submit"
                fullWidth
                variant="contained"
                disabled={modalLoading}
                sx={{
                  py: 2,
                  mt: 3,
                  fontWeight: 600,
                  borderRadius: 3,
                }}
              >
                {modalLoading ? (
                  <Stack direction="row" alignItems="center" spacing={2}>
                    <AppLoader size="xs" inline color="white" />
                    <Typography>
                      {isEditMode ? 'Updating...' : 'Uploading...'}
                    </Typography>
                  </Stack>
                ) : (
                  isEditMode ? 'Update Content' : 'Upload Content'
                )}
              </Button>
            </form>
          </Box>
        </Box>
      </Modal>

      {/* Delete Confirmation Modal */}
      <Modal
        open={deleteModalOpen}
        onClose={cancelDelete}
        sx={{
          backdropFilter: 'blur(12px)',
          backgroundColor: 'rgba(0, 0, 0, 0.6)',
        }}
      >
        <Box
          sx={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: '90%',
            maxWidth: 500,
            bgcolor: 'background.paper',
            outline: 'none',
            boxShadow: theme.palette.mode === 'dark'
              ? '0 24px 48px rgba(0, 0, 0, 0.4)'
              : '0 24px 48px rgba(0, 0, 0, 0.15)',
            borderRadius: 4,
            border: theme.palette.mode === 'dark'
              ? '1px solid rgba(255, 255, 255, 0.12)'
              : '1px solid rgba(0, 0, 0, 0.12)',
            overflow: 'hidden',
          }}
        >
          {/* Modal Header */}
          <Box
            sx={{
              p: 3,
              background: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
              color: 'white',
            }}
          >
            <Stack direction="row" alignItems="center" spacing={2}>
              <Box
                sx={{
                  width: 48,
                  height: 48,
                  borderRadius: '50%',
                  bgcolor: 'rgba(255, 255, 255, 0.2)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '1.5rem',
                }}
              >
                ⚠️
              </Box>
              <Box>
                <Typography variant="h5" fontWeight={700}>
                  Confirm Delete
                </Typography>
                <Typography variant="body2" sx={{ opacity: 0.9, mt: 0.5 }}>
                  This action cannot be undone
                </Typography>
              </Box>
            </Stack>
          </Box>

          {/* Modal Content */}
          <Box sx={{ p: 4 }}>
            <Typography variant="body1" sx={{ mb: 2 }}>
              Are you sure you want to delete{' '}
              <strong>&quot;{contentToDelete?.title || 'this content'}&quot;</strong>?
            </Typography>
            <Typography variant="body2" color="text.secondary">
              All associated data will be permanently removed from the system.
            </Typography>

            {/* Action Buttons */}
            <Stack direction="row" spacing={2} sx={{ mt: 4 }}>
              <Button
                fullWidth
                variant="outlined"
                onClick={cancelDelete}
                sx={{
                  py: 1.5,
                  borderRadius: 2,
                  fontWeight: 600,
                  borderColor: theme.palette.mode === 'dark' ? '#475569' : '#e2e8f0',
                  '&:hover': {
                    borderColor: theme.palette.mode === 'dark' ? '#64748b' : '#cbd5e1',
                    bgcolor: theme.palette.mode === 'dark' ? 'rgba(71, 85, 105, 0.1)' : 'rgba(226, 232, 240, 0.1)',
                  },
                }}
              >
                Cancel
              </Button>
              <Button
                fullWidth
                variant="contained"
                onClick={confirmDelete}
                sx={{
                  py: 1.5,
                  borderRadius: 2,
                  fontWeight: 600,
                  bgcolor: '#ef4444',
                  '&:hover': {
                    bgcolor: '#dc2626',
                  },
                }}
              >
                Delete
              </Button>
            </Stack>
          </Box>
        </Box>
      </Modal>

      {/* Content Detail Modal */}
      <Modal
        open={detailModalOpen}
        onClose={() => {
          setDetailModalOpen(false);
          setSelectedContent(null);
        }}
        sx={{
          backdropFilter: 'blur(12px)',
          backgroundColor: theme.palette.mode === 'dark'
            ? 'rgba(0, 0, 0, 0.8)'
            : 'rgba(0, 0, 0, 0.6)',
        }}
      >
        <Box
          sx={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: '95%',
            maxWidth: 900,
            maxHeight: '95vh',
            bgcolor: 'background.paper',
            outline: 'none',
            boxShadow: theme.palette.mode === 'dark'
              ? '0 24px 48px rgba(0, 0, 0, 0.4), 0 8px 16px rgba(0, 0, 0, 0.2)'
              : '0 24px 48px rgba(0, 0, 0, 0.15), 0 8px 16px rgba(0, 0, 0, 0.1)',
            borderRadius: 4,
            overflowY: 'auto',
            border: theme.palette.mode === 'dark'
              ? '1px solid rgba(255, 255, 255, 0.12)'
              : '1px solid rgba(0, 0, 0, 0.12)',
          }}
        >
          {selectedContent && (
            <>
              {/* Modal Header */}
              <Box
                sx={{
                  position: 'relative',
                  p: 4,
                  pb: 2,
                  background: selectedContent.videoMediaData
                    ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)'
                    : selectedContent.documentMediaData
                    ? 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
                    : 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
                  color: 'white',
                  borderTopLeftRadius: 16,
                  borderTopRightRadius: 16,
                }}
              >
                <IconButton
                  onClick={() => {
                    setDetailModalOpen(false);
                    setSelectedContent(null);
                  }}
                  sx={{
                    position: 'absolute',
                    top: 16,
                    right: 16,
                    color: 'white',
                  }}
                >
                  <CloseIcon />
                </IconButton>
                
                <Stack direction="row" alignItems="center" spacing={2} sx={{ mb: 2 }}>
                  {selectedContent.videoMediaData && <VideoCameraIcon size={32} />}
                  {selectedContent.documentMediaData && <FileTextIcon size={32} />}
                  {selectedContent.blogContent && <ArticleIcon size={32} />}
                  
                  <Box>
                    <Typography variant="h4" component="h1" fontWeight={700}>
                      {selectedContent.title || ''}
                    </Typography>
                    <Chip
                      label={
                        selectedContent.videoMediaData ? 'Video Content' :
                        selectedContent.documentMediaData ? 'Document' :
                        'Blog Post'
                      }
                      size="small"
                      sx={{
                        bgcolor: 'rgba(255, 255, 255, 0.2)',
                        color: 'white',
                        fontWeight: 600,
                        mt: 1,
                      }}
                    />
                  </Box>
                </Stack>
              </Box>

              {/* Modal Content */}
              <Box sx={{ p: 4 }}>
                {/* Video Player */}
                {selectedContent.videoMediaData && (
                  <Box sx={{ mb: 4 }}>
                    <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <VideoCameraIcon size={20} />
                      Video Player
                    </Typography>
                    <Box
                      sx={{
                        position: 'relative',
                        borderRadius: 3,
                        overflow: 'hidden',
                        bgcolor: 'black',
                        boxShadow: theme.palette.mode === 'dark'
                          ? '0 8px 32px rgba(0, 0, 0, 0.4)'
                          : '0 8px 32px rgba(0, 0, 0, 0.15)',
                      }}
                    >
                      <video
                        src={selectedContent.videoMediaData.fileUrl}
                        controls
                        controlsList="nodownload"
                        style={{
                          width: '100%',
                          height: 'auto',
                          maxHeight: '400px',
                          display: 'block',
                        }}
                        poster={selectedContent.videoMediaData.thumbnailUrl}
                      >
                        Your browser does not support the video tag.
                      </video>
                    </Box>
                    
                    {/* Video Info */}
                    <Box sx={{ mt: 2, p: 2, bgcolor: theme.palette.mode === 'dark' ? '#1e293b' : '#f8fafc', borderRadius: 2 }}>
                      <Typography variant="body2" color="text.secondary">
                        <strong>File:</strong> {selectedContent.videoMediaData.fileName}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        <strong>Type:</strong> {selectedContent.videoMediaData.fileType}
                      </Typography>
                      {selectedContent.videoMediaData.thumbnailUrl && (
                        <Typography variant="body2" color="text.secondary">
                          <strong>Thumbnail:</strong> Available
                        </Typography>
                      )}
                    </Box>
                  </Box>
                )}

                {/* Document Viewer */}
                {selectedContent.documentMediaData && (
                  <Box sx={{ mb: 4 }}>
                    <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <FileTextIcon size={20} />
                      Document Information
                    </Typography>
                    <Box sx={{ p: 3, mb: 2, border: 1, borderColor: 'divider', borderRadius: 2 }}>
                      <Stack direction="row" alignItems="center" spacing={2}>
                        <Box
                          sx={{
                            width: 48,
                            height: 48,
                            bgcolor: '#3b82f6',
                            borderRadius: 2,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                          }}
                        >
                          <FileTextIcon size={24} color="white" />
                        </Box>
                        <Box sx={{ flexGrow: 1 }}>
                          <Typography variant="subtitle1" fontWeight={600}>
                            {selectedContent.documentMediaData.fileName}
                          </Typography>
                          <Typography variant="body2" color="text.secondary">
                            {selectedContent.documentMediaData.fileType}
                          </Typography>
                        </Box>
                        <Button
                          variant="contained"
                          href={selectedContent.documentMediaData.fileUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          sx={{ borderRadius: 2 }}
                        >
                          View Document
                        </Button>
                      </Stack>
                    </Box>
                  </Box>
                )}

                {/* Blog Content */}
                {selectedContent.blogContent && (
                  <Box sx={{ mb: 4 }}>
                    <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <ArticleIcon size={20} />
                      Blog Content
                    </Typography>
                    <Box
                      sx={{
                        p: 3,
                        border: `1px solid ${theme.palette.mode === 'dark' ? '#475569' : '#e2e8f0'}`,
                        borderRadius: 2,
                        bgcolor: theme.palette.mode === 'dark' ? '#1e293b' : '#ffffff',
                        '& img': {
                          maxWidth: '100%',
                          height: 'auto',
                          borderRadius: 1,
                        },
                        '& h1, & h2, & h3, & h4, & h5, & h6': {
                          marginTop: 2,
                          marginBottom: 1,
                        },
                        '& p': {
                          marginBottom: 1,
                          lineHeight: 1.6,
                        },
                        '& ul, & ol': {
                          marginLeft: 2,
                          marginBottom: 1,
                        },
                      }}
                      dangerouslySetInnerHTML={{ __html: selectedContent.blogContent }}
                    />
                  </Box>
                )}

                {/* Content Details */}
                <Box sx={{ mb: 3 }}>
                  <Typography variant="h6" gutterBottom>
                    Content Details
                  </Typography>
                  
                  {selectedContent.description && (
                    <Box sx={{ mb: 2 }}>
                      <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                        Description
                      </Typography>
                      <Typography variant="body1">
                        {selectedContent.description}
                      </Typography>
                    </Box>
                  )}

                  <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
                    <Box>
                      <Typography variant="subtitle2" color="text.secondary">
                        Created Date
                      </Typography>
                      <Typography variant="body2">
                        {new Date(selectedContent.createdAt).toLocaleDateString('en-US', {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit',
                        })}
                      </Typography>
                    </Box>
                    
                    <Box>
                      <Typography variant="subtitle2" color="text.secondary">
                        Last Updated
                      </Typography>
                      <Typography variant="body2">
                        {new Date(selectedContent.updatedAt).toLocaleDateString('en-US', {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit',
                        })}
                      </Typography>
                    </Box>
                  </Stack>
                </Box>

                {/* Action Buttons */}
                <Stack direction="row" spacing={2} justifyContent="flex-end">
                  <Button
                    variant="contained"
                    onClick={() => setDetailModalOpen(false)}
                    sx={{ borderRadius: 2 }}
                  >
                    Close
                  </Button>
                </Stack>
              </Box>
            </>
          )}
        </Box>
      </Modal>
    </Box>
  );
}