'use client';

import * as React from 'react';
import type { Metadata } from 'next';
import dynamic from 'next/dynamic';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { useTheme } from '@mui/material/styles';
import { Download as DownloadIcon } from '@phosphor-icons/react/dist/ssr/Download';
import { Plus as PlusIcon } from '@phosphor-icons/react/dist/ssr/Plus';
import { PlusCircle } from '@phosphor-icons/react/dist/ssr/PlusCircle';
import { Upload as UploadIcon } from '@phosphor-icons/react/dist/ssr/Upload';
import axios, { AxiosError } from 'axios';
import dayjs from 'dayjs';

import { config } from '@/config';
import { AboutFilters } from '@/components/dashboard/about/about-filters';
import { AboutTable } from '@/components/dashboard/about/about-table';
import type { Customer } from '@/components/dashboard/about/about-table';

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

import { useRouter } from 'next/navigation';
import {
  Card,
  CardContent,
  CardHeader,
  Divider,
  FormControl,
  Grid,
  InputLabel,
  Modal,
  OutlinedInput,
  Paper,
  TablePagination,
  TextField,
} from '@mui/material';
import { Box } from '@mui/system';
import { Upload } from '@phosphor-icons/react';
import { toast, Toaster } from 'react-hot-toast';

import { AboutStories } from '@/components/dashboard/about/about-stories';
import { AboutTestimonials } from '@/components/dashboard/about/about-testimonials';
import { 
  updateTestimonial, 
  deleteTestimonial, 
  updateSuccessStory, 
  deleteSuccessStory 
} from '@/services/about.service';
import { 
  Dialog, 
  DialogTitle, 
  DialogContent, 
  DialogActions,
  DialogContentText 
} from '@mui/material';

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

// export const metadata = { title: `About | Dashboard | ${config.site.name}` } satisfies Metadata;

const liveUrl = process.env.NEXT_PUBLIC_LIVE_API_URL;

const boxStyle = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: '90%',
  maxWidth: 700,
  maxHeight: '90vh',
  bgcolor: 'background.paper',
  border: 'none',
  outline: 'none',
  boxShadow: 24,
  p: 4,
  borderRadius: '25px',
};

interface AboutData {
  _id: string;
  isDeleted: boolean;
  content: string;
  organizationName: string;
  contactInfo: string;
  sinceYear: string;
}

interface MediaData {
  _id: string;
  fileName: string;
  fileType: string;
  isDeleted: boolean;
  createdAt: string;
  updatedAt: string;
  fileUrl: string;
  thumbnail: string | null;
}

interface Testimonial {
  _id: string;
  fullName: string;
  designation: string;
  content: string;
  createdAt: string;
  updatedAt: string;
  profileImageData: MediaData;
}

interface TestimonialData {
  data: Testimonial[];
  totalTestimonials: number;
}
interface Stories {
  _id: string;
  fullName: string;
  content: string;
  createdAt: string;
  updatedAt: string;
  profileImageData: MediaData;
}

interface StoriesData {
  data: Stories[];
  totalSuccessStories: number;
}

export default function Page(): React.JSX.Element {
  const router = useRouter();
  const theme = useTheme();
  const [open, setOpen] = React.useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);
  const [open1, setOpen1] = React.useState(false);
  const handleOpen1 = () => setOpen1(true);
  const handleClose1 = () => setOpen1(false);
  const [open2, setOpen2] = React.useState(false);
  const handleOpen2 = () => setOpen2(true);
  const handleClose2 = () => setOpen2(false);
  const [organizationName, setOrganizationName] = React.useState('');
  const [contactInfo, setContactInfo] = React.useState('');
  const [sinceYear, setSinceYear] = React.useState('');
  const [content, setContent] = React.useState('');
  const [content1, setContent1] = React.useState('');
  const [fullName, setFullName] = React.useState('');
  const [designation, setDesignation] = React.useState('');
  const [file, setFile] = React.useState<File[]>([]);
  const [profileImage, setProfileImage] = React.useState<File | null>(null);
  const [fullName1, setFullName1] = React.useState('');
  const [content2, setContent2] = React.useState('');
  const [file1, setFile1] = React.useState<File[]>([]);
  const [profileImage1, setProfileImage1] = React.useState<File | null>(null);
  const [aboutData, setAboutData] = React.useState<AboutData | null>(null);
  const [selectedTab, setSelectedTab] = React.useState(0);
  const [testimonials, setTestimonials] = React.useState<TestimonialData | null>(null);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [page, setPage] = React.useState(0);
  const [searchQuery, setSearchQuery] = React.useState('');
  const [stories, setStories] = React.useState<StoriesData | null>(null);
  const [rowsPerPage1, setRowsPerPage1] = React.useState(10);
  const [page1, setPage1] = React.useState(0);
  const [searchQuery1, setSearchQuery1] = React.useState('');
  const [imagePreview, setImagePreview] = React.useState<string | null>(null);
  const [imagePreviews, setImagePreviews] = React.useState<string[]>([]);
  const [imagePreview1, setImagePreview1] = React.useState<string | null>(null);
  const [imagePreviews1, setImagePreviews1] = React.useState<string[]>([]);
  
  // Edit testimonial state
  const [openEditTestimonial, setOpenEditTestimonial] = React.useState(false);
  const [editingTestimonial, setEditingTestimonial] = React.useState<Testimonial | null>(null);
  const [editTestimonialFullName, setEditTestimonialFullName] = React.useState('');
  const [editTestimonialDesignation, setEditTestimonialDesignation] = React.useState('');
  const [editTestimonialContent, setEditTestimonialContent] = React.useState('');
  const [editTestimonialProfileImage, setEditTestimonialProfileImage] = React.useState<File | null>(null);
  const [editTestimonialMedia, setEditTestimonialMedia] = React.useState<File[]>([]);
  const [editTestimonialImagePreview, setEditTestimonialImagePreview] = React.useState<string | null>(null);
  const [editTestimonialImagePreviews, setEditTestimonialImagePreviews] = React.useState<string[]>([]);
  
  // Edit success story state
  const [openEditStory, setOpenEditStory] = React.useState(false);
  const [editingStory, setEditingStory] = React.useState<Stories | null>(null);
  const [editStoryFullName, setEditStoryFullName] = React.useState('');
  const [editStoryContent, setEditStoryContent] = React.useState('');
  const [editStoryProfileImage, setEditStoryProfileImage] = React.useState<File | null>(null);
  const [editStoryMedia, setEditStoryMedia] = React.useState<File[]>([]);
  const [editStoryImagePreview, setEditStoryImagePreview] = React.useState<string | null>(null);
  const [editStoryImagePreviews, setEditStoryImagePreviews] = React.useState<string[]>([]);
  
  // Delete confirmation state
  const [deleteConfirmOpen, setDeleteConfirmOpen] = React.useState(false);
  const [deleteTarget, setDeleteTarget] = React.useState<{ id: string; type: 'testimonial' | 'story' } | null>(null);
  const [isDeleting, setIsDeleting] = React.useState(false);

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

  React.useEffect(() => {
    if (aboutData) {
      setOrganizationName(aboutData?.organizationName);
      setContactInfo(aboutData?.contactInfo);
      setSinceYear(aboutData?.sinceYear);
      setContent(aboutData?.content);
    }
  }, [aboutData]);

  const fetchHomeCategoryAbout = async () => {
    const token = localStorage.getItem('token');
    try {
      const response = await axios.get(`${liveUrl}/api/v1/admin/fetchHomeCategoryAbout`, {
        headers: {
          authorization: `${token}`,
        },
      });
      if (response.data.data) {
        setAboutData(response.data.data);
        console.log(response.data.data);
      }
    } catch (error: unknown) {
      let message: string;

      if (error instanceof AxiosError && error.response?.data?.message) {
        message = error.response.data.message;
      } else if (error instanceof Error) {
        message = error.message;
      } else {
        message = 'Something went wrong...';
      }
      console.log(message);
    }
  };

  const fetchTestimonialsData = async () => {
    const token = localStorage.getItem('token');
    try {
      const response = await axios.get(`${liveUrl}/api/v1/admin/fetchAllTestimonials`, {
        headers: {
          authorization: `${token}`,
        },
        params: {
          skip: page,
          limit: rowsPerPage,
          fullName: searchQuery || undefined,
        },
      });
      if (response.data.data) {
        setTestimonials(response.data.data);
        console.log('Testimonials: ', response.data.data);
      }
    } catch (error: unknown) {
      let message: string;

      if (error instanceof AxiosError && error.response?.data?.message) {
        message = error.response.data.message;
      } else if (error instanceof Error) {
        message = error.message;
      } else {
        message = 'Something went wrong...';
      }
      console.log(message);
    }
  };

  const fetchSuccessStoriesData = async () => {
    const token = localStorage.getItem('token');
    try {
      const response = await axios.get(`${liveUrl}/api/v1/admin/fetchAllSuccessStories`, {
        headers: {
          authorization: `${token}`,
        },
        params: {
          skip: page1,
          limit: rowsPerPage1,
          fullName: searchQuery1 || undefined,
        },
      });
      if (response.data.data) {
        setStories(response.data.data);
        console.log('Success Stories: ', response.data.data);
      }
    } catch (error: unknown) {
      let message: string;

      if (error instanceof AxiosError && error.response?.data?.message) {
        message = error.response.data.message;
      } else if (error instanceof Error) {
        message = error.message;
      } else {
        message = 'Something went wrong...';
      }
      console.log(message);
    }
  };

  React.useEffect(() => {
    if (typeof window !== 'undefined') {
      

      

      fetchHomeCategoryAbout();
      fetchTestimonialsData();
      fetchSuccessStoriesData();
    }
  }, [page, rowsPerPage, searchQuery, page1, rowsPerPage1, searchQuery1]);

  const handleSearchQueryChange = (query: string) => {
    setSearchQuery(query);
  };

  const handleSearchQueryChange1 = (query: string) => {
    setSearchQuery1(query);
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newRowsPerPage = parseInt(event.target.value, 10);
    setRowsPerPage(newRowsPerPage);
    setPage(0);
  };

  const handleChangePage = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    console.log(newPage);

    setPage(newPage);
  };

  const handleChangeRowsPerPage1 = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newRowsPerPage = parseInt(event.target.value, 10);
    setRowsPerPage1(newRowsPerPage);
    setPage1(0);
  };

  const handleChangePage1 = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    console.log(newPage);

    setPage1(newPage);
  };

  const handleContent = (content: string) => {
    setContent(content);
  };

  const handleOrganizationName: React.ChangeEventHandler<HTMLInputElement> = (event) => {
    setOrganizationName(event.target.value);
  };

  const handleContactInfo = (event: React.ChangeEvent<HTMLInputElement>) => {
    setContactInfo(event.target.value);
  };

  const handleSinceYear = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSinceYear(event.target.value);
  };
  const handleDesignation = (event: React.ChangeEvent<HTMLInputElement>) => {
    setDesignation(event.target.value);
  };

  const handleFullName = (event: React.ChangeEvent<HTMLInputElement>) => {
    setFullName(event.target.value);
  };

  const handleContent1 = (content: string) => {
    setContent1(content);
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = Array.from(event.target.files || []);

    // if (file.length + selectedFiles.length > 3) {
    //   toast.error("You can only upload up to 3 images.");
    //   return;
    // }

    const newFiles = [...file, ...selectedFiles];
    setFile(newFiles);

    const previews = newFiles.map((file) => URL.createObjectURL(file));
    setImagePreviews(previews);
  };

  const handleRemoveImage1 = (index: number) => {
    const updatedFiles = file.filter((_, i) => i !== index);
    const updatedPreviews = imagePreviews.filter((_, i) => i !== index);

    setFile(updatedFiles);
    setImagePreviews(updatedPreviews);
  };

  const handleProfileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      setProfileImage(event.target.files[0]);

      const previewUrl = URL.createObjectURL(event.target.files[0]);
      setImagePreview(previewUrl);
      console.log('Image Preview: ', previewUrl);
      event.target.value = '';
    }
  };

  const handleRemoveImage = () => {
    setProfileImage(null);
    setImagePreview(null);
  };

  const handleFullName1 = (event: React.ChangeEvent<HTMLInputElement>) => {
    setFullName1(event.target.value);
  };

  const handleFileChange1 = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = Array.from(event.target.files || []);
    const newFiles = [...file1, ...selectedFiles];
    setFile1(newFiles);

    const previews = newFiles.map((file) => URL.createObjectURL(file));
    setImagePreviews1(previews);
  };

  const handleRemoveImage3 = (index: number) => {
    const updatedFiles = file1.filter((_, i) => i !== index);
    const updatedPreviews = imagePreviews1.filter((_, i) => i !== index);

    setFile1(updatedFiles);
    setImagePreviews1(updatedPreviews);
  };

  const handleProfileChange1 = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      setProfileImage1(event.target.files[0]);

      const previewUrl = URL.createObjectURL(event.target.files[0]);
      setImagePreview1(previewUrl);
      console.log('Image Preview: ', previewUrl);
      event.target.value = '';
    }
  };

  const handleRemoveImage2 = () => {
    setProfileImage1(null);
    setImagePreview1(null);
  };

  const handleContent2 = (content: string) => {
    setContent2(content);
  };

  const handleError = (msg: string) => {
    toast.error(msg);
  };

  const handleSuccess = (msg: string) => {
    toast.success(msg);
    if (msg === 'About added successfully!') {
      setOrganizationName('');
      setContactInfo('');
      setSinceYear('');
      setContent('');
      handleClose();
    }
    if (msg === 'Testimonial added successfully!') {
      setContent1('');
      setFullName('');
      setDesignation('');
      setFile([]);
      setProfileImage(null);
      setImagePreview(null);
      setImagePreviews([]);
      handleClose1();
    }
    if (msg === 'Success story added successfully!') {
      setContent2('');
      setFullName1('');
      setFile1([]);
      setProfileImage1(null);
      setImagePreview1(null);
      setImagePreviews1([]);
      handleClose2();
    }
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    try {
      const token = localStorage.getItem('token');
      const response = await axios.post(
        `${liveUrl}/api/v1/admin/createHomeCategoryAbout`,
        {
          organizationName,
          contactInfo,
          sinceYear,
          content,
        },
        {
          headers: {
            authorization: token,
          },
        }
      );
      fetchHomeCategoryAbout();
      return handleSuccess('About added successfully!');
    } catch (e: unknown) {
      if (e instanceof AxiosError && e.response) {
        return handleError(e.response.data.message);
      } else if (e instanceof Error) {
        return handleError(e.message);
      } else {
        return handleError('Something went wrong...');
      }
    }
  };

  const handleSubmit1 = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    try {
      const token = localStorage.getItem('token');
      console.log(file, 'file');
      const formData = new FormData();
      formData.append('fullName', fullName);
      formData.append('designation', designation);
      formData.append('content', content1);
      file.forEach((file, index) => {
        formData.append(`media`, file);
      });
      if (profileImage) {
        formData.append('profileImage', profileImage);
      }

      const response = await axios.post(`${liveUrl}/api/v1/admin/createHomeCategoryTestimonial`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          authorization: token,
        },
      });

      return handleSuccess('Testimonial added successfully!');
    } catch (e: unknown) {
      if (e instanceof AxiosError && e.response) {
        return handleError(e.response.data.message);
      } else if (e instanceof Error) {
        return handleError(e.message);
      } else {
        return handleError('Something went wrong...');
      }
    }
  };

  const handleSubmit2 = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    try {
      const token = localStorage.getItem('token');
      console.log(file, 'file');
      const formData = new FormData();
      formData.append('fullName', fullName1);
      formData.append('content', content2);
      file1.forEach((file, index) => {
        formData.append(`media`, file);
      });
      if (profileImage1) {
        formData.append('profileImage', profileImage1);
      }
      const response = await axios.post(`${liveUrl}/api/v1/admin/createHomeCategorySuccessStory`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          authorization: token,
        },
      });

      return handleSuccess('Success story added successfully!');
    } catch (e: unknown) {
      if (e instanceof AxiosError && e.response) {
        return handleError(e.response.data.message);
      } else if (e instanceof Error) {
        return handleError(e.message);
      } else {
        return handleError('Something went wrong...');
      }
    }
  };

  // Edit Testimonial Handlers
  const handleEditTestimonial = (testimonial: Testimonial) => {
    setEditingTestimonial(testimonial);
    setEditTestimonialFullName(testimonial.fullName);
    setEditTestimonialDesignation(testimonial.designation);
    setEditTestimonialContent(testimonial.content);
    setEditTestimonialImagePreview(testimonial.profileImageData?.fileUrl || null);
    setEditTestimonialProfileImage(null);
    setEditTestimonialMedia([]);
    setEditTestimonialImagePreviews([]);
    setOpenEditTestimonial(true);
  };

  const handleCloseEditTestimonial = () => {
    setOpenEditTestimonial(false);
    setEditingTestimonial(null);
    setEditTestimonialFullName('');
    setEditTestimonialDesignation('');
    setEditTestimonialContent('');
    setEditTestimonialProfileImage(null);
    setEditTestimonialMedia([]);
    setEditTestimonialImagePreview(null);
    setEditTestimonialImagePreviews([]);
  };

  const handleSubmitEditTestimonial = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!editingTestimonial) return;

    try {
      await updateTestimonial(editingTestimonial._id, {
        fullName: editTestimonialFullName,
        designation: editTestimonialDesignation,
        content: editTestimonialContent,
        profileImage: editTestimonialProfileImage || undefined,
        media: editTestimonialMedia.length > 0 ? editTestimonialMedia : undefined,
      });

      handleSuccess('Testimonial updated successfully!');
      handleCloseEditTestimonial();
      fetchTestimonialsData();
    } catch (e: unknown) {
      if (e instanceof Error) {
        handleError(e.message);
      } else {
        handleError('Failed to update testimonial');
      }
    }
  };

  // Edit Success Story Handlers
  const handleEditStory = (story: Stories) => {
    setEditingStory(story);
    setEditStoryFullName(story.fullName);
    setEditStoryContent(story.content);
    setEditStoryImagePreview(story.profileImageData?.fileUrl || null);
    setEditStoryProfileImage(null);
    setEditStoryMedia([]);
    setEditStoryImagePreviews([]);
    setOpenEditStory(true);
  };

  const handleCloseEditStory = () => {
    setOpenEditStory(false);
    setEditingStory(null);
    setEditStoryFullName('');
    setEditStoryContent('');
    setEditStoryProfileImage(null);
    setEditStoryMedia([]);
    setEditStoryImagePreview(null);
    setEditStoryImagePreviews([]);
  };

  const handleSubmitEditStory = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!editingStory) return;

    try {
      await updateSuccessStory(editingStory._id, {
        fullName: editStoryFullName,
        content: editStoryContent,
        profileImage: editStoryProfileImage || undefined,
        media: editStoryMedia.length > 0 ? editStoryMedia : undefined,
      });

      handleSuccess('Success story updated successfully!');
      handleCloseEditStory();
      fetchSuccessStoriesData();
    } catch (e: unknown) {
      if (e instanceof Error) {
        handleError(e.message);
      } else {
        handleError('Failed to update success story');
      }
    }
  };

  // Delete Handlers
  const handleDeleteClick = (id: string, type: 'testimonial' | 'story') => {
    setDeleteTarget({ id, type });
    setDeleteConfirmOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!deleteTarget) return;

    setIsDeleting(true);
    try {
      if (deleteTarget.type === 'testimonial') {
        await deleteTestimonial(deleteTarget.id);
        handleSuccess('Testimonial deleted successfully!');
        fetchTestimonialsData();
      } else {
        await deleteSuccessStory(deleteTarget.id);
        handleSuccess('Success story deleted successfully!');
        fetchSuccessStoriesData();
      }
      setDeleteConfirmOpen(false);
      setDeleteTarget(null);
    } catch (e: unknown) {
      if (e instanceof Error) {
        handleError(e.message);
      } else {
        handleError('Failed to delete item');
      }
    } finally {
      setIsDeleting(false);
    }
  };

  const handleDeleteCancel = () => {
    setDeleteConfirmOpen(false);
    setDeleteTarget(null);
  };

  return (
    <Box sx={{ minHeight: '100vh', p: 3 }}>
      <Toaster />
      {/* Modern Header Section */}
      <Paper
        elevation={0}
        sx={{
          p: 3,
          mb: 3,
          borderRadius: 4,
          background: '#FFDD31',
          color: '#0B0504',
        }}
      >
        <Stack direction="row" justifyContent="space-between" alignItems="center">
          <Box>
            <Typography variant="h4" fontWeight={700} gutterBottom>
              About WFC
            </Typography>
            <Typography variant="body1" sx={{ opacity: 0.9 }}>
              Manage organization information, testimonials, and success stories
            </Typography>
          </Box>
          <Stack direction="row" spacing={2}>
            <Button
              variant="contained"
              startIcon={<PlusIcon size={20} />}
              onClick={handleOpen}
              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',
              }}
            >
              {aboutData ? 'Update' : 'Create'} About
            </Button>
            <Button
              variant="contained"
              startIcon={<PlusIcon size={20} />}
              onClick={handleOpen1}
              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',
              }}
            >
              Create Testimonials
            </Button>
            <Button
              variant="contained"
              startIcon={<PlusIcon size={20} />}
              onClick={handleOpen2}
              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',
              }}
            >
              Create Success Story
            </Button>
          </Stack>
        </Stack>
      </Paper>
      <AboutFilters
        value={selectedTab}
        onChange={handleTabChange}
        onSearchChange={handleSearchQueryChange}
        onSearchChange1={handleSearchQueryChange1}
      />
      {(() => {
        if (selectedTab === 0) {
          return (
            <Paper
              elevation={0}
              sx={{
                borderRadius: 4,
                background: theme.palette.mode === 'dark' 
                  ? 'linear-gradient(145deg, #1a202c 0%, #2d3748 100%)' 
                  : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
                border: theme.palette.mode === 'dark' 
                  ? '1px solid #4a5568' 
                  : '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)',
                overflow: 'hidden',
              }}
            >
              <Box sx={{ p: 4 }}>
                <Stack
                  direction="row"
                  spacing={0}
                  sx={{ mb: 3, display: 'flex', justifyContent: 'space-between' }}
                >
                  <Stack spacing={1}>
                    <Typography variant="h4" fontWeight={700} color="text.primary">
                      {aboutData?.organizationName || 'Warrior For Children'}
                    </Typography>
                    <Typography variant="body1" color="text.secondary" sx={{ fontWeight: 500 }}>
                      Since {aboutData?.sinceYear}
                    </Typography>
                  </Stack>
                  <Stack spacing={1} alignItems="flex-end">
                    <Typography variant="h6" fontWeight={600} color="text.primary">
                      Contact Info
                    </Typography>
                    <Typography variant="body1" color="text.secondary">
                      {aboutData?.contactInfo}
                    </Typography>
                  </Stack>
                </Stack>
                <Divider sx={{ my: 3, borderColor: theme.palette.divider }} />
                <Box
                  component="div"
                  dangerouslySetInnerHTML={{ __html: aboutData?.content || '' }}
                  sx={{
                    typography: 'body1',
                    color: 'text.secondary',
                    lineHeight: 1.8,
                    '& p': {
                      marginBottom: 2,
                      color: 'text.secondary',
                    },
                    '& h1, & h2, & h3, & h4, & h5, & h6': {
                      color: 'text.primary',
                      fontWeight: 600,
                      marginBottom: 1,
                      marginTop: 2,
                    },
                  }}
                />
              </Box>
            </Paper>
          );
        } else if (selectedTab === 1) {
          return (
            <>
              <Box sx={{ maxWidth: 1200, mx: 'auto', px: 6 }}>
                <Grid container spacing={8} sx={{ mt: '5px', justifyContent: 'flex-start' }}>
                  {testimonials?.data.map((testimonials) => (
                    <Grid key={testimonials._id} lg={4} md={6} sm={12} xs={12} sx={{ mb: 5, px: 2 }}>
                      <AboutTestimonials 
                        testimonial={testimonials}
                        onEdit={handleEditTestimonial}
                        onDelete={(id) => handleDeleteClick(id, 'testimonial')}
                        onRefetch={fetchTestimonialsData}
                      />
                    </Grid>
                  ))}
                </Grid>
              </Box>
              <Box sx={{ display: 'flex', justifyContent: 'center' }}>
                {testimonials && (
                  <TablePagination
                    sx={{ mt: '-25px' }}
                    rowsPerPageOptions={[10, 8, 5]}
                    component="div"
                    count={testimonials.totalTestimonials}
                    rowsPerPage={rowsPerPage}
                    page={page}
                    onPageChange={handleChangePage}
                    onRowsPerPageChange={handleChangeRowsPerPage}
                  />
                )}
              </Box>
            </>
          );
        } else if (selectedTab === 2) {
          return (
            <>
              <Box sx={{ maxWidth: 1200, mx: 'auto', px: 6 }}>
                <Grid container spacing={8} sx={{ mt: '5px', justifyContent: 'flex-start' }}>
                  {stories?.data.map((stories) => (
                    <Grid key={stories._id} lg={4} md={6} sm={12} xs={12} sx={{ mb: 5, px: 2 }}>
                      <AboutStories 
                        story={stories}
                        onEdit={handleEditStory}
                        onDelete={(id) => handleDeleteClick(id, 'story')}
                        onRefetch={fetchSuccessStoriesData}
                      />
                    </Grid>
                  ))}
                </Grid>
              </Box>
              <Box sx={{ display: 'flex', justifyContent: 'center' }}>
                {stories && (
                  <TablePagination
                    sx={{ mt: '-25px' }}
                    rowsPerPageOptions={[10, 8, 2]}
                    component="div"
                    count={stories.totalSuccessStories}
                    rowsPerPage={rowsPerPage1}
                    page={page1}
                    onPageChange={handleChangePage1}
                    onRowsPerPageChange={handleChangeRowsPerPage1}
                  />
                )}
              </Box>
            </>
          );
        }
        return null;
      })()}
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
        style={{ backdropFilter: 'blur(5px)' }}
      >
        <Box sx={boxStyle}>
          <Typography id="modal-modal-title" variant="h6" component="h1" sx={{ fontWeight: 'bold' }}>
            {aboutData ? 'Update' : 'Create'} About
          </Typography>
          <form onSubmit={handleSubmit}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Organization Name"
              variant="outlined"
              value={organizationName}
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: '10px',
                },
                '& .MuiOutlinedInput-root.Mui-focused': {
                  '& fieldset': {
                    borderColor: '#FFDD31',
                  },
                },
                '& .MuiInputLabel-root.Mui-focused': {
                  color: '#000000',
                },
              }}
              onChange={handleOrganizationName}
            />
            <TextField
              required
              fullWidth
              margin="normal"
              label="Contact Info"
              variant="outlined"
              value={contactInfo}
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: '10px',
                },
                '& .MuiOutlinedInput-root.Mui-focused': {
                  '& fieldset': {
                    borderColor: '#FFDD31',
                  },
                },
                '& .MuiInputLabel-root.Mui-focused': {
                  color: '#000000',
                },
              }}
              onChange={handleContactInfo}
            />
            <TextField
              required
              fullWidth
              margin="normal"
              label="Since Year"
              variant="outlined"
              value={sinceYear}
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: '10px',
                },
                '& .MuiOutlinedInput-root.Mui-focused': {
                  '& fieldset': {
                    borderColor: '#FFDD31',
                  },
                },
                '& .MuiInputLabel-root.Mui-focused': {
                  color: '#000000',
                },
              }}
              onChange={handleSinceYear}
            />

            <ReactQuill
              value={content}
              onChange={handleContent}
              theme="snow"
              style={{
                height: '180px', // Set a fixed height for the editor
                overflowY: 'auto', // Enable vertical scroll when content exceeds height
              }}
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{
                marginTop: '16px',
                backgroundColor: '#000000',
                color: '#FFDD31',
                fontWeight: 'bold',
                borderRadius: '25px',
                '&:hover': {
                  backgroundColor: '#FFDD31',
                  borderColor: '#000000',
                  color: '#000000',
                },
              }}
              size="large"
            >
              {aboutData ? 'Update' : 'Create'}
            </Button>
          </form>
        </Box>
      </Modal>
      <Modal
        open={open1}
        onClose={handleClose1}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
        style={{ backdropFilter: 'blur(5px)' }}
      >
        <Box sx={boxStyle}>
          <Typography id="modal-modal-title" variant="h6" component="h1" sx={{ fontWeight: 'bold' }}>
            Create Testimonial
          </Typography>
          <form onSubmit={handleSubmit1}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Full Name"
              variant="outlined"
              value={fullName}
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: '10px',
                },
                '& .MuiOutlinedInput-root.Mui-focused': {
                  '& fieldset': {
                    borderColor: '#FFDD31',
                  },
                },
                '& .MuiInputLabel-root.Mui-focused': {
                  color: '#000000',
                },
              }}
              onChange={handleFullName}
            />
            <TextField
              required
              fullWidth
              margin="none"
              label="Designation"
              variant="outlined"
              value={designation}
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: '10px',
                },
                '& .MuiOutlinedInput-root.Mui-focused': {
                  '& fieldset': {
                    borderColor: '#FFDD31',
                  },
                },
                '& .MuiInputLabel-root.Mui-focused': {
                  color: '#000000',
                },
              }}
              onChange={handleDesignation}
            />
            <Box
              sx={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                my: '10px',
                gap: '10px',
              }}
            >
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': {
                    backgroundColor: '#FFDD31',
                    borderColor: '#FFDD31',
                    color: 'black',
                  },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Upload Profile Image
                <input type="file" hidden accept="image/*" onChange={handleProfileChange} />
              </Button>

              {imagePreview && (
                <Box
                  sx={{
                    position: 'relative',
                    mt: 2,
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                >
                  <img
                    src={imagePreview}
                    alt="Uploaded Preview"
                    style={{
                      maxWidth: '60px',
                      height: '60px',
                      borderRadius: '10px',
                      objectFit: 'cover',
                    }}
                  />
                  <Button
                    onClick={handleRemoveImage}
                    sx={{
                      position: 'absolute',
                      top: '2px',
                      right: '2px',
                      minWidth: 'unset',
                      color: 'black',
                      backgroundColor: 'rgba(255, 255, 255, 0.6)',
                      backdropFilter: 'blur(2px)',
                      '&:hover': {
                        color: '#FFDD31',
                        backgroundColor: 'black',
                      },
                      borderRadius: '50%',
                      padding: '0',
                      fontSize: '15px',
                      width: '18px',
                      height: '18px',
                    }}
                  >
                    &times;
                  </Button>
                </Box>
              )}

              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': {
                    backgroundColor: '#FFDD31',
                    borderColor: '#FFDD31',
                    color: 'black',
                  },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Upload Files
                <input type="file" multiple hidden accept="image/*,video/*" onChange={handleFileChange} />
              </Button>
              <Box
                sx={{
                  display: 'flex',
                  gap: '10px',
                  overflowX: 'auto',
                }}
              >
                {imagePreviews.map((preview, index) => (
                  <Box
                    key={index}
                    sx={{
                      position: 'relative',
                      width: '60px',
                      height: '60px',
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}
                  >
                    <img
                      src={preview}
                      alt={`Uploaded Preview ${index + 1}`}
                      style={{
                        width: '100%',
                        height: '100%',
                        borderRadius: '10px',
                        objectFit: 'cover',
                      }}
                    />
                    <Button
                      onClick={() => handleRemoveImage1(index)}
                      sx={{
                        position: 'absolute',
                        top: '2px',
                        right: '2px',
                        minWidth: 'unset',
                        color: 'black',
                        backgroundColor: 'rgba(255, 255, 255, 0.6)',
                        backdropFilter: 'blur(2px)',
                        '&:hover': {
                          color: '#FFDD31',
                          backgroundColor: 'black',
                        },
                        borderRadius: '50%',
                        padding: '0',
                        fontSize: '15px',
                        width: '18px',
                        height: '18px',
                      }}
                    >
                      &times;
                    </Button>
                  </Box>
                ))}
              </Box>
            </Box>

            <ReactQuill
              value={content1}
              onChange={handleContent1}
              theme="snow"
              style={{
                height: '180px',
                overflowY: 'auto',
              }}
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{
                marginTop: '16px',
                backgroundColor: '#000000',
                color: '#FFDD31',
                fontWeight: 'bold',
                borderRadius: '25px',
                '&:hover': {
                  backgroundColor: '#FFDD31',
                  borderColor: '#000000',
                  color: '#000000',
                },
              }}
              size="large"
            >
              Create
            </Button>
          </form>
        </Box>
      </Modal>
      <Modal
        open={open2}
        onClose={handleClose2}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
        style={{ backdropFilter: 'blur(5px)' }}
      >
        <Box sx={boxStyle}>
          <Typography id="modal-modal-title" variant="h6" component="h1" sx={{ fontWeight: 'bold' }}>
            Create Success Story
          </Typography>
          <form onSubmit={handleSubmit2}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Full Name"
              variant="outlined"
              value={fullName1}
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: '10px',
                },
                '& .MuiOutlinedInput-root.Mui-focused': {
                  '& fieldset': {
                    borderColor: '#FFDD31',
                  },
                },
                '& .MuiInputLabel-root.Mui-focused': {
                  color: '#000000',
                },
              }}
              onChange={handleFullName1}
            />
            <Box
              sx={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                my: '10px',
                gap: '10px',
              }}
            >
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': {
                    backgroundColor: '#FFDD31',
                    borderColor: '#FFDD31',
                    color: 'black',
                  },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Upload Profile Image
                <input type="file" hidden accept="image/*" onChange={handleProfileChange1} />
              </Button>
              {imagePreview1 && (
                <Box
                  sx={{
                    position: 'relative',
                    mt: 2,
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                >
                  <img
                    src={imagePreview1}
                    alt="Uploaded Preview"
                    style={{
                      maxWidth: '60px',
                      height: '60px',
                      borderRadius: '10px',
                      objectFit: 'cover',
                    }}
                  />
                  <Button
                    onClick={handleRemoveImage2}
                    sx={{
                      position: 'absolute',
                      top: '2px',
                      right: '2px',
                      minWidth: 'unset',
                      color: 'black',
                      backgroundColor: 'rgba(255, 255, 255, 0.6)',
                      backdropFilter: 'blur(2px)',
                      '&:hover': {
                        color: '#FFDD31',
                        backgroundColor: 'black',
                      },
                      borderRadius: '50%',
                      padding: '0',
                      fontSize: '15px',
                      width: '18px',
                      height: '18px',
                    }}
                  >
                    &times;
                  </Button>
                </Box>
              )}
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': {
                    backgroundColor: '#FFDD31',
                    borderColor: '#FFDD31',
                    color: 'black',
                  },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Upload Files
                <input type="file" multiple hidden accept="image/*,video/*" onChange={handleFileChange1} />
              </Button>

              <Box
                sx={{
                  display: 'flex',
                  gap: '10px',
                  overflowX: 'auto',
                }}
              >
                {imagePreviews1.map((preview, index) => (
                  <Box
                    key={index}
                    sx={{
                      position: 'relative',
                      width: '60px',
                      height: '60px',
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}
                  >
                    <img
                      src={preview}
                      alt={`Uploaded Preview ${index + 1}`}
                      style={{
                        width: '100%',
                        height: '100%',
                        borderRadius: '10px',
                        objectFit: 'cover',
                      }}
                    />
                    <Button
                      onClick={() => handleRemoveImage3(index)}
                      sx={{
                        position: 'absolute',
                        top: '2px',
                        right: '2px',
                        minWidth: 'unset',
                        color: 'black',
                        backgroundColor: 'rgba(255, 255, 255, 0.6)',
                        backdropFilter: 'blur(2px)',
                        '&:hover': {
                          color: '#FFDD31',
                          backgroundColor: 'black',
                        },
                        borderRadius: '50%',
                        padding: '0',
                        fontSize: '15px',
                        width: '18px',
                        height: '18px',
                      }}
                    >
                      &times;
                    </Button>
                  </Box>
                ))}
              </Box>
            </Box>

            <ReactQuill
              value={content2}
              onChange={handleContent2}
              theme="snow"
              style={{
                height: '180px',
                overflowY: 'auto',
              }}
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{
                marginTop: '16px',
                backgroundColor: '#000000',
                color: '#FFDD31',
                fontWeight: 'bold',
                borderRadius: '25px',
                '&:hover': {
                  backgroundColor: '#FFDD31',
                  borderColor: '#000000',
                  color: '#000000',
                },
              }}
              size="large"
            >
              Create
            </Button>
          </form>
        </Box>
      </Modal>

      {/* Edit Testimonial Modal */}
      <Modal
        open={openEditTestimonial}
        onClose={handleCloseEditTestimonial}
        aria-labelledby="edit-testimonial-modal"
        style={{ backdropFilter: 'blur(5px)' }}
      >
        <Box sx={boxStyle}>
          <Typography id="edit-testimonial-modal" variant="h6" component="h1" sx={{ fontWeight: 'bold' }}>
            Edit Testimonial
          </Typography>
          <form onSubmit={handleSubmitEditTestimonial}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Full Name"
              variant="outlined"
              value={editTestimonialFullName}
              onChange={(e) => setEditTestimonialFullName(e.target.value)}
              sx={{
                '& .MuiOutlinedInput-root': { borderRadius: '10px' },
                '& .MuiOutlinedInput-root.Mui-focused': { '& fieldset': { borderColor: '#FFDD31' }},
                '& .MuiInputLabel-root.Mui-focused': { color: '#000000' },
              }}
            />
            <TextField
              required
              fullWidth
              margin="none"
              label="Designation"
              variant="outlined"
              value={editTestimonialDesignation}
              onChange={(e) => setEditTestimonialDesignation(e.target.value)}
              sx={{
                '& .MuiOutlinedInput-root': { borderRadius: '10px' },
                '& .MuiOutlinedInput-root.Mui-focused': { '& fieldset': { borderColor: '#FFDD31' }},
                '& .MuiInputLabel-root.Mui-focused': { color: '#000000' },
              }}
            />
            <Box sx={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', my: '10px', gap: '10px' }}>
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', color: 'black' },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Update Profile Image
                <input type="file" hidden accept="image/*" onChange={(e) => {
                  if (e.target.files && e.target.files[0]) {
                    setEditTestimonialProfileImage(e.target.files[0]);
                    setEditTestimonialImagePreview(URL.createObjectURL(e.target.files[0]));
                  }
                }} />
              </Button>
              {editTestimonialImagePreview && (
                <Box sx={{ position: 'relative', mt: 2 }}>
                  <img src={editTestimonialImagePreview} alt="Preview" style={{ maxWidth: '60px', height: '60px', borderRadius: '10px', objectFit: 'cover' }} />
                  <Button
                    onClick={() => {
                      setEditTestimonialProfileImage(null);
                      setEditTestimonialImagePreview(null);
                    }}
                    sx={{
                      position: 'absolute',
                      top: '2px',
                      right: '2px',
                      minWidth: 'unset',
                      color: 'black',
                      backgroundColor: 'rgba(255, 255, 255, 0.6)',
                      '&:hover': { color: '#FFDD31', backgroundColor: 'black' },
                      borderRadius: '50%',
                      padding: '0',
                      fontSize: '15px',
                      width: '18px',
                      height: '18px',
                    }}
                  >
                    &times;
                  </Button>
                </Box>
              )}
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', color: 'black' },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Add More Files
                <input type="file" multiple hidden accept="image/*,video/*" onChange={(e) => {
                  const selectedFiles = Array.from(e.target.files || []);
                  setEditTestimonialMedia([...editTestimonialMedia, ...selectedFiles]);
                  const previews = selectedFiles.map((file) => URL.createObjectURL(file));
                  setEditTestimonialImagePreviews([...editTestimonialImagePreviews, ...previews]);
                }} />
              </Button>
              <Box sx={{ display: 'flex', gap: '10px', overflowX: 'auto' }}>
                {editTestimonialImagePreviews.map((preview, index) => (
                  <Box key={index} sx={{ position: 'relative', width: '60px', height: '60px' }}>
                    <img src={preview} alt={`Preview ${index + 1}`} style={{ width: '100%', height: '100%', borderRadius: '10px', objectFit: 'cover' }} />
                    <Button
                      onClick={() => {
                        const updated = editTestimonialMedia.filter((_, i) => i !== index);
                        const updatedPreviews = editTestimonialImagePreviews.filter((_, i) => i !== index);
                        setEditTestimonialMedia(updated);
                        setEditTestimonialImagePreviews(updatedPreviews);
                      }}
                      sx={{
                        position: 'absolute',
                        top: '2px',
                        right: '2px',
                        minWidth: 'unset',
                        color: 'black',
                        backgroundColor: 'rgba(255, 255, 255, 0.6)',
                        '&:hover': { color: '#FFDD31', backgroundColor: 'black' },
                        borderRadius: '50%',
                        padding: '0',
                        fontSize: '15px',
                        width: '18px',
                        height: '18px',
                      }}
                    >
                      &times;
                    </Button>
                  </Box>
                ))}
              </Box>
            </Box>
            <ReactQuill
              value={editTestimonialContent}
              onChange={setEditTestimonialContent}
              theme="snow"
              style={{ height: '180px', overflowY: 'auto' }}
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{
                marginTop: '16px',
                backgroundColor: '#000000',
                color: '#FFDD31',
                fontWeight: 'bold',
                borderRadius: '25px',
                '&:hover': { backgroundColor: '#FFDD31', color: '#000000' },
              }}
              size="large"
            >
              Update
            </Button>
          </form>
        </Box>
      </Modal>

      {/* Edit Success Story Modal */}
      <Modal
        open={openEditStory}
        onClose={handleCloseEditStory}
        aria-labelledby="edit-story-modal"
        style={{ backdropFilter: 'blur(5px)' }}
      >
        <Box sx={boxStyle}>
          <Typography id="edit-story-modal" variant="h6" component="h1" sx={{ fontWeight: 'bold' }}>
            Edit Success Story
          </Typography>
          <form onSubmit={handleSubmitEditStory}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Full Name"
              variant="outlined"
              value={editStoryFullName}
              onChange={(e) => setEditStoryFullName(e.target.value)}
              sx={{
                '& .MuiOutlinedInput-root': { borderRadius: '10px' },
                '& .MuiOutlinedInput-root.Mui-focused': { '& fieldset': { borderColor: '#FFDD31' }},
                '& .MuiInputLabel-root.Mui-focused': { color: '#000000' },
              }}
            />
            <Box sx={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', my: '10px', gap: '10px' }}>
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', color: 'black' },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Update Profile Image
                <input type="file" hidden accept="image/*" onChange={(e) => {
                  if (e.target.files && e.target.files[0]) {
                    setEditStoryProfileImage(e.target.files[0]);
                    setEditStoryImagePreview(URL.createObjectURL(e.target.files[0]));
                  }
                }} />
              </Button>
              {editStoryImagePreview && (
                <Box sx={{ position: 'relative', mt: 2 }}>
                  <img src={editStoryImagePreview} alt="Preview" style={{ maxWidth: '60px', height: '60px', borderRadius: '10px', objectFit: 'cover' }} />
                  <Button
                    onClick={() => {
                      setEditStoryProfileImage(null);
                      setEditStoryImagePreview(null);
                    }}
                    sx={{
                      position: 'absolute',
                      top: '2px',
                      right: '2px',
                      minWidth: 'unset',
                      color: 'black',
                      backgroundColor: 'rgba(255, 255, 255, 0.6)',
                      '&:hover': { color: '#FFDD31', backgroundColor: 'black' },
                      borderRadius: '50%',
                      padding: '0',
                      fontSize: '15px',
                      width: '18px',
                      height: '18px',
                    }}
                  >
                    &times;
                  </Button>
                </Box>
              )}
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', color: 'black' },
                }}
                startIcon={<Upload size={32} weight="fill" />}
                size="large"
              >
                Add More Files
                <input type="file" multiple hidden accept="image/*,video/*" onChange={(e) => {
                  const selectedFiles = Array.from(e.target.files || []);
                  setEditStoryMedia([...editStoryMedia, ...selectedFiles]);
                  const previews = selectedFiles.map((file) => URL.createObjectURL(file));
                  setEditStoryImagePreviews([...editStoryImagePreviews, ...previews]);
                }} />
              </Button>
              <Box sx={{ display: 'flex', gap: '10px', overflowX: 'auto' }}>
                {editStoryImagePreviews.map((preview, index) => (
                  <Box key={index} sx={{ position: 'relative', width: '60px', height: '60px' }}>
                    <img src={preview} alt={`Preview ${index + 1}`} style={{ width: '100%', height: '100%', borderRadius: '10px', objectFit: 'cover' }} />
                    <Button
                      onClick={() => {
                        const updated = editStoryMedia.filter((_, i) => i !== index);
                        const updatedPreviews = editStoryImagePreviews.filter((_, i) => i !== index);
                        setEditStoryMedia(updated);
                        setEditStoryImagePreviews(updatedPreviews);
                      }}
                      sx={{
                        position: 'absolute',
                        top: '2px',
                        right: '2px',
                        minWidth: 'unset',
                        color: 'black',
                        backgroundColor: 'rgba(255, 255, 255, 0.6)',
                        '&:hover': { color: '#FFDD31', backgroundColor: 'black' },
                        borderRadius: '50%',
                        padding: '0',
                        fontSize: '15px',
                        width: '18px',
                        height: '18px',
                      }}
                    >
                      &times;
                    </Button>
                  </Box>
                ))}
              </Box>
            </Box>
            <ReactQuill
              value={editStoryContent}
              onChange={setEditStoryContent}
              theme="snow"
              style={{ height: '180px', overflowY: 'auto' }}
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{
                marginTop: '16px',
                backgroundColor: '#000000',
                color: '#FFDD31',
                fontWeight: 'bold',
                borderRadius: '25px',
                '&:hover': { backgroundColor: '#FFDD31', color: '#000000' },
              }}
              size="large"
            >
              Update
            </Button>
          </form>
        </Box>
      </Modal>

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={handleDeleteCancel}
        aria-labelledby="delete-dialog-title"
        aria-describedby="delete-dialog-description"
      >
        <DialogTitle id="delete-dialog-title">Confirm Delete</DialogTitle>
        <DialogContent>
          <DialogContentText id="delete-dialog-description">
            Are you sure you want to delete this {deleteTarget?.type === 'testimonial' ? 'testimonial' : 'success story'}? This action cannot be undone.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleDeleteCancel} disabled={isDeleting}>
            Cancel
          </Button>
          <Button onClick={handleDeleteConfirm} color="error" disabled={isDeleting} autoFocus>
            {isDeleting ? 'Deleting...' : 'Delete'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
