"use client"

import * as React from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Button, Card, CardContent, Typography, Avatar, Divider, Box, CircularProgress, Grid, IconButton, Modal, TextField, Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions } from '@mui/material';
import dayjs from 'dayjs';
import axios from 'axios';
import dynamic from "next/dynamic";
import "react-quill/dist/quill.snow.css";
const ReactQuill = dynamic(() => import("react-quill"), { ssr: false });
import { toast } from "react-hot-toast";
import { Upload, PencilSimple, Trash, ArrowLeft } from '@phosphor-icons/react';
import { updateSuccessStory, deleteSuccessStory } from '@/services/about.service';

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",
  overflow: 'auto',
};

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

interface StoryDetail {
  _id: string;
  fullName: string;
  content: string;
  profileImage?: MediaData;
  profileImageData?: MediaData;
  media?: MediaData[];
  createdAt?: string;
  updatedAt?: string;
}

export default function Page(): React.JSX.Element {
  const router = useRouter();
  const searchParams = useSearchParams();
  const storyId = searchParams.get('storyId');
  const [story, setStory] = React.useState<StoryDetail | null>(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  // Edit modal state
  const [openEditModal, setOpenEditModal] = React.useState(false);
  const [editFullName, setEditFullName] = React.useState('');
  const [editContent, setEditContent] = React.useState('');
  const [editProfileImage, setEditProfileImage] = React.useState<File | null>(null);
  const [editMedia, setEditMedia] = React.useState<File[]>([]);
  const [editProfileImagePreview, setEditProfileImagePreview] = React.useState<string | null>(null);
  const [editMediaPreviews, setEditMediaPreviews] = React.useState<string[]>([]);
  const [existingMedia, setExistingMedia] = React.useState<MediaData[]>([]);
  const [mediaToRemove, setMediaToRemove] = React.useState<string[]>([]);
  const [removeProfileImage, setRemoveProfileImage] = React.useState(false);
  const [isSubmitting, setIsSubmitting] = React.useState(false);

  // Delete dialog state
  const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false);
  const [isDeleting, setIsDeleting] = React.useState(false);

  const fetchStory = React.useCallback(() => {
    if (!storyId) return;
    setLoading(true);
    setError('');
    const token = typeof window !== 'undefined' ? localStorage.getItem('token') : '';
    axios
      .get(`${liveUrl}/api/v1/admin/fetchSpecificSuccessStory`, {
        headers: { authorization: `${token}` },
        params: { successStoryId: storyId },
      })
      .then((res) => {
        setStory(res.data.data || null);
      })
      .catch(() => {
        setError('Success Story not found.');
      })
      .finally(() => setLoading(false));
  }, [storyId]);

  React.useEffect(() => {
    fetchStory();
  }, [fetchStory]);

  const handleOpenEdit = () => {
    if (!story) return;
    setEditFullName(story.fullName);
    setEditContent(story.content);
    const profileImage = story.profileImage || story.profileImageData;
    setEditProfileImagePreview(profileImage?.fileUrl || null);
    setExistingMedia(story.media || []);
    setMediaToRemove([]);
    setRemoveProfileImage(false);
    setOpenEditModal(true);
  };

  const handleCloseEdit = () => {
    setOpenEditModal(false);
    setEditProfileImage(null);
    setEditMedia([]);
    setEditProfileImagePreview(null);
    setEditMediaPreviews([]);
    setExistingMedia([]);
    setMediaToRemove([]);
    setRemoveProfileImage(false);
  };

  const handleSubmitEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!storyId) return;

    setIsSubmitting(true);
    try {
      await updateSuccessStory(storyId, {
        fullName: editFullName,
        content: editContent,
        profileImage: editProfileImage || undefined,
        media: editMedia.length > 0 ? editMedia : undefined,
        removeMedia: mediaToRemove.length > 0 ? mediaToRemove : undefined,
        removeProfileImage: removeProfileImage || undefined,
      });
      
      toast.success('Success story updated successfully!');
      handleCloseEdit();
      fetchStory();
    } catch (error: any) {
      toast.error(error.message || 'Failed to update success story');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleRemoveExistingMedia = (mediaId: string) => {
    setMediaToRemove([...mediaToRemove, mediaId]);
    setExistingMedia(existingMedia.filter(m => m._id !== mediaId));
  };

  const handleRemoveProfileImageClick = () => {
    setRemoveProfileImage(true);
    setEditProfileImagePreview(null);
  };

  const handleOpenDelete = () => {
    setDeleteDialogOpen(true);
  };

  const handleCloseDelete = () => {
    setDeleteDialogOpen(false);
  };

  const handleConfirmDelete = async () => {
    if (!storyId) return;

    setIsDeleting(true);
    try {
      await deleteSuccessStory(storyId);
      toast.success('Success story deleted successfully!');
      router.push('/dashboard/about');
    } catch (error: any) {
      toast.error(error.message || 'Failed to delete success story');
    } finally {
      setIsDeleting(false);
      setDeleteDialogOpen(false);
    }
  };

  if (!storyId) {
    return <Typography variant="h6">No success story selected.</Typography>;
  }
  if (loading) {
    return <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}><CircularProgress /></Box>;
  }
  if (error) {
    return <Typography variant="h6" color="error">{error}</Typography>;
  }
  if (!story) {
    return <Typography variant="h6">Success Story not found.</Typography>;
  }

  const profileImage = story.profileImage || story.profileImageData;
  const mediaFiles = story.media || [];

  return (
    <Box sx={{ maxWidth: 900, mx: 'auto', mt: 4, p: 3 }}>
      {/* Back Button */}
      <Button
        startIcon={<ArrowLeft />}
        onClick={() => router.push('/dashboard/about')}
        sx={{ mb: 2 }}
      >
        Back to About
      </Button>

      <Card>
        <CardContent>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 3 }}>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Avatar src={profileImage?.fileUrl} sx={{ width: 80, height: 80, mr: 3 }} />
              <Box>
                <Typography variant="h4" fontWeight={700}>{story.fullName}</Typography>
                {story.createdAt && (
                  <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                    Created: {dayjs(story.createdAt).format('MMM D, YYYY')}
                  </Typography>
                )}
                {story.updatedAt && (
                  <Typography variant="body2" color="text.secondary">
                    Updated: {dayjs(story.updatedAt).format('MMM D, YYYY')}
                  </Typography>
                )}
              </Box>
            </Box>
            
            {/* Action Buttons */}
            <Box sx={{ display: 'flex', gap: 1 }}>
              <IconButton
                onClick={handleOpenEdit}
                sx={{
                  bgcolor: 'primary.main',
                  color: 'white',
                  '&:hover': { bgcolor: 'primary.dark' },
                }}
              >
                <PencilSimple size={20} />
              </IconButton>
              <IconButton
                onClick={handleOpenDelete}
                sx={{
                  bgcolor: 'error.main',
                  color: 'white',
                  '&:hover': { bgcolor: 'error.dark' },
                }}
              >
                <Trash size={20} />
              </IconButton>
            </Box>
          </Box>
          
          <Divider sx={{ mb: 3 }} />
          
          <Typography variant="h6" fontWeight={600} sx={{ mb: 2 }}>
            Success Story Content
          </Typography>
          <Box 
            sx={{ 
              mb: 3,
              '& p': { mb: 1 },
              '& h1, & h2, & h3, & h4, & h5, & h6': { fontWeight: 600, mb: 1 },
            }} 
            dangerouslySetInnerHTML={{ __html: story.content }} 
          />
          
          {mediaFiles.length > 0 && (
            <>
              <Divider sx={{ mb: 3 }} />
              <Typography variant="h6" fontWeight={600} sx={{ mb: 2 }}>
                Media ({mediaFiles.length})
              </Typography>
              <Grid container spacing={2}>
                {mediaFiles.map((media) => (
                  <Grid item xs={12} sm={6} md={4} key={media._id}>
                    <Card sx={{ height: '100%' }}>
                      <Box sx={{ position: 'relative', paddingTop: '75%', bgcolor: 'grey.100' }}>
                        {media.fileType.startsWith('image/') ? (
                          <Box
                            component="img"
                            src={media.fileUrl}
                            alt={media.fileName}
                            sx={{
                              position: 'absolute',
                              top: 0,
                              left: 0,
                              width: '100%',
                              height: '100%',
                              objectFit: 'cover',
                            }}
                          />
                        ) : media.fileType.startsWith('video/') ? (
                          <Box
                            component="video"
                            controls
                            poster={media.thumbnailUrl}
                            sx={{
                              position: 'absolute',
                              top: 0,
                              left: 0,
                              width: '100%',
                              height: '100%',
                              objectFit: 'cover',
                            }}
                          >
                            <source src={media.fileUrl} type={media.fileType} />
                            Your browser does not support the video tag.
                          </Box>
                        ) : (
                          <Box
                            sx={{
                              position: 'absolute',
                              top: 0,
                              left: 0,
                              width: '100%',
                              height: '100%',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                            }}
                          >
                            <Typography variant="caption" color="text.secondary">
                              {media.fileType}
                            </Typography>
                          </Box>
                        )}
                      </Box>
                      <CardContent sx={{ p: 1.5 }}>
                        <Typography 
                          variant="caption" 
                          color="text.secondary"
                          sx={{ 
                            display: 'block',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                          }}
                        >
                          {media.fileName}
                        </Typography>
                        <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
                          {media.fileType}
                        </Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            </>
          )}
        </CardContent>
      </Card>

      {/* Edit Modal */}
      <Modal
        open={openEditModal}
        onClose={handleCloseEdit}
        aria-labelledby="edit-story-modal"
        style={{ backdropFilter: 'blur(5px)' }}
      >
        <Box sx={boxStyle}>
          <Typography id="edit-story-modal" variant="h6" component="h1" sx={{ fontWeight: 'bold', mb: 3 }}>
            Edit Success Story
          </Typography>
          <form onSubmit={handleSubmitEdit}>
            <TextField
              required
              fullWidth
              margin="normal"
              label="Full Name"
              variant="outlined"
              value={editFullName}
              onChange={(e) => setEditFullName(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: 2, gap: 2 }}>
              {/* Current Profile Image */}
              {editProfileImagePreview && !editProfileImage && (
                <Box>
                  <Typography variant="caption" sx={{ display: 'block', mb: 1, textAlign: 'center' }}>
                    Current Profile Image
                  </Typography>
                  <Box sx={{ position: 'relative' }}>
                    <Avatar src={editProfileImagePreview} sx={{ width: 60, height: 60 }} />
                    <IconButton
                      onClick={handleRemoveProfileImageClick}
                      sx={{
                        position: 'absolute',
                        top: -8,
                        right: -8,
                        bgcolor: 'error.main',
                        color: 'white',
                        width: 24,
                        height: 24,
                        '&:hover': { bgcolor: 'error.dark' },
                      }}
                    >
                      <Typography sx={{ fontSize: 16 }}>×</Typography>
                    </IconButton>
                  </Box>
                </Box>
              )}
              
              {/* New Profile Image Preview */}
              {editProfileImage && (
                <Box>
                  <Typography variant="caption" sx={{ display: 'block', mb: 1, textAlign: 'center', color: 'success.main' }}>
                    New Profile Image
                  </Typography>
                  <Box sx={{ position: 'relative' }}>
                    <Avatar src={editProfileImagePreview || ''} sx={{ width: 60, height: 60 }} />
                    <IconButton
                      onClick={() => {
                        setEditProfileImage(null);
                        setEditProfileImagePreview(story?.profileImage?.fileUrl || story?.profileImageData?.fileUrl || null);
                      }}
                      sx={{
                        position: 'absolute',
                        top: -8,
                        right: -8,
                        bgcolor: 'error.main',
                        color: 'white',
                        width: 24,
                        height: 24,
                        '&:hover': { bgcolor: 'error.dark' },
                      }}
                    >
                      <Typography sx={{ fontSize: 16 }}>×</Typography>
                    </IconButton>
                  </Box>
                </Box>
              )}
              
              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', color: 'black' },
                }}
                startIcon={<Upload size={24} weight="fill" />}
              >
                {editProfileImagePreview ? 'Change Profile Image' : 'Upload Profile Image'}
                <input 
                  type="file" 
                  hidden 
                  accept="image/*" 
                  onChange={(e) => {
                    if (e.target.files && e.target.files[0]) {
                      setEditProfileImage(e.target.files[0]);
                      setEditProfileImagePreview(URL.createObjectURL(e.target.files[0]));
                      setRemoveProfileImage(false);
                    }
                  }} 
                />
              </Button>

              {/* Existing Media */}
              {existingMedia.length > 0 && (
                <Box sx={{ width: '100%' }}>
                  <Typography variant="caption" sx={{ display: 'block', mb: 1, fontWeight: 600 }}>
                    Current Media ({existingMedia.length})
                  </Typography>
                  <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', justifyContent: 'center' }}>
                    {existingMedia.map((media) => (
                      <Box key={media._id} sx={{ position: 'relative' }}>
                        {media.fileType.startsWith('image/') ? (
                          <Box
                            component="img"
                            src={media.fileUrl}
                            alt={media.fileName}
                            sx={{ width: 60, height: 60, borderRadius: '8px', objectFit: 'cover' }}
                          />
                        ) : media.fileType.startsWith('video/') ? (
                          <Box
                            component="video"
                            src={media.fileUrl}
                            sx={{ width: 60, height: 60, borderRadius: '8px', objectFit: 'cover' }}
                          />
                        ) : (
                          <Box
                            sx={{
                              width: 60,
                              height: 60,
                              borderRadius: '8px',
                              bgcolor: 'grey.200',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                            }}
                          >
                            <Typography variant="caption" sx={{ fontSize: 10 }}>
                              {media.fileType.split('/')[0]}
                            </Typography>
                          </Box>
                        )}
                        <IconButton
                          onClick={() => handleRemoveExistingMedia(media._id)}
                          sx={{
                            position: 'absolute',
                            top: -8,
                            right: -8,
                            bgcolor: 'error.main',
                            color: 'white',
                            width: 20,
                            height: 20,
                            '&:hover': { bgcolor: 'error.dark' },
                          }}
                        >
                          <Typography sx={{ fontSize: 14 }}>×</Typography>
                        </IconButton>
                      </Box>
                    ))}
                  </Box>
                </Box>
              )}

              <Button
                variant="contained"
                component="label"
                sx={{
                  backgroundColor: 'black',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', color: 'black' },
                }}
                startIcon={<Upload size={24} weight="fill" />}
              >
                Add New Media
                <input 
                  type="file" 
                  multiple 
                  hidden 
                  accept="image/*,video/*" 
                  onChange={(e) => {
                    const selectedFiles = Array.from(e.target.files || []);
                    setEditMedia([...editMedia, ...selectedFiles]);
                    const previews = selectedFiles.map((file) => URL.createObjectURL(file));
                    setEditMediaPreviews([...editMediaPreviews, ...previews]);
                  }} 
                />
              </Button>
              
              {editMediaPreviews.length > 0 && (
                <Box sx={{ width: '100%' }}>
                  <Typography variant="caption" sx={{ display: 'block', mb: 1, fontWeight: 600, color: 'success.main' }}>
                    New Media to Add ({editMediaPreviews.length})
                  </Typography>
                  <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', justifyContent: 'center' }}>
                    {editMediaPreviews.map((preview, index) => (
                      <Box key={index} sx={{ position: 'relative' }}>
                        <Box
                          component="img"
                          src={preview}
                          alt={`Preview ${index + 1}`}
                          sx={{ width: 60, height: 60, borderRadius: '8px', objectFit: 'cover' }}
                        />
                        <IconButton
                          onClick={() => {
                            const updated = editMedia.filter((_, i) => i !== index);
                            const updatedPreviews = editMediaPreviews.filter((_, i) => i !== index);
                            setEditMedia(updated);
                            setEditMediaPreviews(updatedPreviews);
                          }}
                          sx={{
                            position: 'absolute',
                            top: -8,
                            right: -8,
                            bgcolor: 'error.main',
                            color: 'white',
                            width: 20,
                            height: 20,
                            '&:hover': { bgcolor: 'error.dark' },
                          }}
                        >
                          <Typography sx={{ fontSize: 14 }}>×</Typography>
                        </IconButton>
                      </Box>
                    ))}
                  </Box>
                </Box>
              )}
            </Box>

            <Box sx={{ mb: 2 }}>
              <ReactQuill
                value={editContent}
                onChange={setEditContent}
                theme="snow"
                style={{ height: '200px', marginBottom: '60px' }}
              />
            </Box>

            <Box sx={{ display: 'flex', gap: 2, mt: 2 }}>
              <Button
                type="button"
                fullWidth
                variant="outlined"
                onClick={handleCloseEdit}
                disabled={isSubmitting}
                sx={{ borderRadius: '25px' }}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                fullWidth
                variant="contained"
                disabled={isSubmitting}
                sx={{
                  backgroundColor: '#000000',
                  color: '#FFDD31',
                  fontWeight: 'bold',
                  borderRadius: '25px',
                  '&:hover': { backgroundColor: '#FFDD31', color: '#000000' },
                }}
              >
                {isSubmitting ? 'Updating...' : 'Update'}
              </Button>
            </Box>
          </form>
        </Box>
      </Modal>

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