import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';
import { format } from 'date-fns';
import { Image as ImageIcon, X } from 'lucide-react';
import { useManageFeedbackContext } from '../hooks/useManageFeedbackMemberContext';
import { Button } from '@/components/ui/button';
import FeedbackEditDialog from './EditDialog';

interface ImageModalProps {
  isOpen: boolean;
  onClose: () => void;
  imageUrl: string;
}

// New Image Modal Component
const ImageModal: React.FC<ImageModalProps> = ({ isOpen, onClose, imageUrl }) => {
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75">
      <div className="relative w-11/12 h-5/6 max-w-4xl">
        <button
          onClick={onClose}
          className="absolute top-4 right-4 bg-white rounded-full p-1 shadow-lg z-10"
        >
          <X size={24} className="text-gray-800" />
        </button>
        <img src={imageUrl} alt="Enlarged view" className="w-full h-full object-contain" />
      </div>
    </div>
  );
};

const ScreenshotGrid = ({ title, images }: { title: string; images: string[] }) => {
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  const openImageModal = (url: string) => {
    setSelectedImage(url);
  };

  const closeImageModal = () => {
    setSelectedImage(null);
  };

  return (
    <div className="space-y-2">
      <h3 className="text-sm font-semibold text-gray-600">{title}</h3>
      {images && images.length > 0 ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {images.map((url, index) => (
            <div
              key={`${title}-${index}`}
              className="relative h-48 rounded-md overflow-hidden border border-gray-200 bg-white cursor-pointer hover:opacity-90 transition-opacity"
              onClick={() => url && openImageModal(url)}
            >
              {url ? (
                <img
                  src={url}
                  alt={`${title} ${index + 1}`}
                  className="w-full h-full object-cover rounded-md"
                />
              ) : (
                <div className="flex justify-center items-center h-full bg-gray-100">
                  <ImageIcon size={48} className="text-gray-400" />
                </div>
              )}
            </div>
          ))}
        </div>
      ) : (
        <p className="text-sm text-gray-800">N/A</p>
      )}

      <ImageModal
        isOpen={!!selectedImage}
        onClose={closeImageModal}
        imageUrl={selectedImage || ''}
      />
    </div>
  );
};

const FeedbackDetail = () => {
  const [loading, setLoading] = useState(false);
  const [feedbackDetail, setFeedbackDetail] = useState<any>(null);
  const { GetData } = useCallApi();
  const API_URL = apiConfig.service_feedback;
  const {
    handleDetailDialog,
    selectedFeedback,
    showDetailDialog,
    handleEditDialog,
    showEditDialog
  } = useManageFeedbackContext();

  const formatDateTime = (dateString: string) => {
    if (!dateString) return 'N/A';
    try {
      return format(new Date(dateString), 'MMM dd, yyyy HH:mm');
    } catch {
      return 'N/A';
    }
  };

  const formatValue = (value: any) => {
    if (value === null || value === undefined || (typeof value === 'string' && value.trim() === ''))
      return 'N/A';
    return value;
  };

  const getEmotionLabel = (emotion: string) => {
    const emotions: Record<string, string> = {
      '1': 'Very Dissatisfied',
      '2': 'Dissatisfied',
      '3': 'Neutral',
      '4': 'Satisfied',
      '5': 'Very Satisfied'
    };
    return emotions[emotion] || 'N/A';
  };

  const getStatusLabel = (status: string) => {
    if (!status) return { label: 'N/A', color: 'text-gray-500' };

    const statuses: Record<string, { label: string; color: string }> = {
      W: { label: 'Waiting', color: 'text-yellow-500' },
      Y: { label: 'Accepted', color: 'text-green-500' },
      N: { label: 'Rejected', color: 'text-red-500' },
      C: { label: 'Completed', color: 'text-blue-500' },
      R: { label: 'Rejected', color: 'text-red-500' }
    };
    return statuses[status] || { label: 'N/A', color: 'text-gray-500' };
  };

  const fetchFeedbackDetail = async () => {
    if (!selectedFeedback) return;
    try {
      setLoading(true);
      const timestamp = new Date().getTime();
      const response = await GetData(`${API_URL}/feedback/detail/${selectedFeedback}`, {
        id: selectedFeedback,
        _t: timestamp
      });

      if (!response || !response.data) {
        console.error('Invalid response format');
        return;
      }

      const data = response.data;

      const normalizedData = {
        ...data,
        feedback_screenshoot: Array.isArray(data?.feedback_screenshoot)
          ? data.feedback_screenshoot
          : data?.feedback_screenshoot
            ? [data.feedback_screenshoot]
            : [],
        review_screenshoot: Array.isArray(data?.review_screenshoot)
          ? data.review_screenshoot
          : data?.review_screenshoot
            ? [data.review_screenshoot]
            : []
      };

      setFeedbackDetail(normalizedData);
    } catch (error) {
      console.error('Error fetching feedback detail:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (showDetailDialog && selectedFeedback) {
      fetchFeedbackDetail();
    } else if (!showDetailDialog) {
      setFeedbackDetail(null);
    }
  }, [showDetailDialog, selectedFeedback]);

  const handleReviewClick = () => {
    handleEditDialog(true, selectedFeedback);
  };

  return (
    <>
      <Dialog
        open={showDetailDialog}
        onOpenChange={(open) => {
          if (!open) {
            setFeedbackDetail(null);
          }
          handleDetailDialog(open, open ? selectedFeedback : null);
        }}
      >
        <DialogContent className="sm:max-w-4xl rounded-2xl p-6 shadow-lg border border-gray-200">
          <DialogHeader>
            <DialogTitle className="text-xl font-bold">Feedback Detail</DialogTitle>
            <DialogDescription className="text-sm text-gray-500"></DialogDescription>
          </DialogHeader>

          {loading ? (
            <div className="flex justify-center items-center h-60">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary" />
            </div>
          ) : feedbackDetail ? (
            <div className="space-y-8">
              <div className="p-4 border border-gray-200 rounded-lg">
                <h3 className="text-md font-semibold mb-4 border-b pb-2">Feedback Information</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <p className="text-sm font-semibold text-gray-600">Feedback ID</p>
                    <p className="text-sm text-gray-800">{formatValue(feedbackDetail.id)}</p>
                  </div>

                  <div>
                    <p className="text-sm font-semibold text-gray-600">Created By</p>
                    <p className="text-sm text-gray-800">
                      {formatValue(feedbackDetail.created_by?.fullname)}
                    </p>
                  </div>

                  <div>
                    <p className="text-sm font-semibold text-gray-600">Created Date</p>
                    <p className="text-sm text-gray-800">
                      {formatDateTime(feedbackDetail.created_at)}
                    </p>
                  </div>

                  <div>
                    <p className="text-sm font-semibold text-gray-600">Emotion</p>
                    <p className="text-sm text-gray-800">
                      {getEmotionLabel(feedbackDetail.emotion)}
                    </p>
                  </div>
                </div>

                <div className="mt-4">
                  <p className="text-sm font-semibold text-gray-600">Feedback Notes</p>
                  <p className="text-sm text-gray-800 whitespace-pre-wrap mt-1 p-2 bg-gray-50 rounded">
                    {formatValue(feedbackDetail.feedback_notes)}
                  </p>
                </div>
              </div>

              <div className="p-4 border border-gray-200 rounded-lg">
                <h3 className="text-md font-semibold mb-4 border-b pb-2">Feedback Screenshots</h3>
                <ScreenshotGrid title="" images={feedbackDetail.feedback_screenshoot} />
              </div>

              <div className="p-4 border border-gray-200 rounded-lg">
                <h3 className="text-md font-semibold mb-4 border-b pb-2">Review Information</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <p className="text-sm font-semibold text-gray-600">Reviewed By</p>
                    <p className="text-sm text-gray-800">{formatValue(feedbackDetail.review_by)}</p>
                  </div>

                  <div>
                    <p className="text-sm font-semibold text-gray-600">Status</p>
                    <p
                      className={`text-sm font-semibold ${getStatusLabel(feedbackDetail.status).color}`}
                    >
                      {getStatusLabel(feedbackDetail.status).label}
                    </p>
                  </div>
                </div>

                <div className="mt-4">
                  <p className="text-sm font-semibold text-gray-600">Review Notes</p>
                  <p className="text-sm text-gray-800 whitespace-pre-wrap mt-1 p-2 bg-gray-50 rounded">
                    {formatValue(feedbackDetail.review_notes)}
                  </p>
                </div>
              </div>

              {feedbackDetail.status !== 'C' && feedbackDetail.status !== 'R' && (
                <div className="flex justify-end">
                  <Button
                    onClick={handleReviewClick}
                    className="bg-primary hover:bg-primary/90 text-white"
                  >
                    Review Feedback
                  </Button>
                </div>
              )}
            </div>
          ) : null}
        </DialogContent>
      </Dialog>
    </>
  );
};

export default FeedbackDetail;
