import React from 'react';
import { X, Eye } from 'lucide-react';

export const ResponseModal = ({
  showResponseModal,
  selectedItemResponses,
  responsesData,
  loadingResponses,
  responseTab,
  setShowResponseModal,
  setSelectedItemResponses,
  setResponsesData,
  setResponseTab,
  formatDuration,
  calculateQuestionStats
}) => {
  if (!showResponseModal || !selectedItemResponses) return null;

  const handleClose = () => {
    setShowResponseModal(false);
    setSelectedItemResponses(null);
    setResponsesData(null);
  };
  
  // NOTE: Replaced the problematic `alert` with a simple console log for View Details.
  const handleViewDetails = (response) => {
    console.log('Response Details:', JSON.stringify(response.answers, null, 2));
    // In a real application, replace this with a custom detail modal.
    alert('Details logged to console. Use a custom modal in production.');
  };

  return (
    <div className="fixed inset-0 backdrop-blur-sm bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white shadow-xl w-full max-w-5xl max-h-[90vh] flex flex-col">
        <div className="bg-blue-600 text-white p-6">
          <div className="flex items-center justify-between mb-2">
            <h2 className="text-2xl font-bold">{selectedItemResponses.title}</h2>
            <button 
              className="text-white hover:text-gray-200"
              onClick={handleClose}
            >
              <X className="w-6 h-6" />
            </button>
          </div>
          <div className="flex items-center gap-3 text-sm">
            <span className="px-2 py-1 bg-white text-blue-600 rounded font-medium">
              {selectedItemResponses.type === 'poll' ? 'Poll' : 'Survey'}
            </span>
            <span className={`px-2 py-1 rounded font-medium ${
              selectedItemResponses.status === 'active' ? 'bg-green-100 text-green-800' :
              selectedItemResponses.status === 'draft' ? 'bg-gray-100 text-gray-800' :
              selectedItemResponses.status === 'closed' ? 'bg-red-100 text-red-800' :
              'bg-blue-100 text-blue-800'
            }`}>
              {selectedItemResponses.status}
            </span>
            <span className="text-white">
              {formatDuration(selectedItemResponses.start_date, selectedItemResponses.end_date)}
            </span>
            <span className="ml-auto text-white font-semibold">
              Total Responses: {responsesData?.length || 0}
            </span>
          </div>
        </div>

        <div className="flex border-b bg-gray-50">
          <button
            className={`px-6 py-3 font-medium ${
              responseTab === 'overview'
                ? 'text-blue-600 border-b-2 border-blue-600 bg-white'
                : 'text-gray-600 hover:text-blue-600'
            }`}
            onClick={() => setResponseTab('overview')}
          >
            Overview
          </button>
          <button
            className={`px-6 py-3 font-medium ${
              responseTab === 'byQuestion'
                ? 'text-blue-600 border-b-2 border-blue-600 bg-white'
                : 'text-gray-600 hover:text-blue-600'
            }`}
            onClick={() => setResponseTab('byQuestion')}
          >
            By Question
          </button>
          <button
            className={`px-6 py-3 font-medium ${
              responseTab === 'individual'
                ? 'text-blue-600 border-b-2 border-blue-600 bg-white'
                : 'text-gray-600 hover:text-blue-600'
            }`}
            onClick={() => setResponseTab('individual')}
          >
            Individual Responses
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-6">
          {loadingResponses ? (
            <div className="flex items-center justify-center h-64">
              <div className="text-blue-600 text-lg">Loading responses...</div>
            </div>
          ) : !responsesData || responsesData.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-64 text-gray-400">
              <Eye className="w-16 h-16 mb-4" />
              <p className="text-lg">No responses yet</p>
            </div>
          ) : (
            <>
              {responseTab === 'overview' && (
                <div className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                      <div className="text-blue-600 text-sm font-medium mb-1">Total Responses</div>
                      <div className="text-3xl font-bold text-blue-900">{responsesData.length}</div>
                    </div>
                    <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                      <div className="text-blue-600 text-sm font-medium mb-1">Questions</div>
                      <div className="text-3xl font-bold text-blue-900">
                        {selectedItemResponses.questions?.length || 0}
                      </div>
                    </div>
                    <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                      <div className="text-blue-600 text-sm font-medium mb-1">Response Period</div>
                      <div className="text-sm font-medium text-blue-900">
                        {responsesData.length > 0 ? (
                          <>
                            {new Date(responsesData[0].submitted_at).toLocaleDateString()} - 
                            {new Date(responsesData[responsesData.length - 1].submitted_at).toLocaleDateString()}
                          </>
                        ) : 'N/A'}
                      </div>
                    </div>
                  </div>

                  <div className="bg-white border rounded-lg p-6">
                    <h3 className="text-lg font-bold text-blue-900 mb-4">Quick Summary</h3>
                    <div className="space-y-4">
                      {selectedItemResponses.questions?.map((question, idx) => {
                        const stats = calculateQuestionStats(question, responsesData);
                        if (!stats) return null;

                        return (
                          <div key={question.id} className="border-b pb-4 last:border-b-0">
                            <div className="font-medium text-blue-900 mb-2">
                              Q{idx + 1}: {question.question_text}
                            </div>
                            <div className="text-sm text-gray-600">
                              {stats.type === 'rating' && (
                                <span className="text-blue-600 font-semibold">
                                  Average Rating: {stats.average} / {question.rating_max || 5}
                                </span>
                              )}
                              {stats.type === 'options' && (
                                <span className="text-blue-600 font-semibold">
                                  {stats.total} total selections
                                </span>
                              )}
                              {stats.type === 'text' && (
                                <span className="text-blue-600 font-semibold">
                                  {stats.total} text responses
                                </span>
                              )}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>
              )}

              {responseTab === 'byQuestion' && (
                <div className="space-y-6">
                  {selectedItemResponses.questions?.map((question, idx) => {
                    const stats = calculateQuestionStats(question, responsesData);
                    if (!stats) return null;

                    return (
                      <div key={question.id} className="bg-white border rounded-lg p-6">
                        <h3 className="text-lg font-bold text-blue-900 mb-4">
                          Question {idx + 1}: {question.question_text}
                        </h3>
                        <div className="text-sm text-gray-500 mb-4">
                          Type: {question.question_type} • {stats.total} responses
                        </div>

                        {stats.type === 'options' && (
                          <div className="space-y-3">
                            {Object.entries(stats.data).map(([option, count]) => {
                              const percentage = stats.total > 0 ? ((count / stats.total) * 100).toFixed(1) : 0;
                              return (
                                <div key={option}>
                                  <div className="flex justify-between mb-1">
                                    <span className="text-sm font-medium text-gray-700">{option}</span>
                                    <span className="text-sm text-gray-600">{count} ({percentage}%)</span>
                                  </div>
                                  <div className="w-full bg-gray-200 rounded-full h-3">
                                    <div
                                      className="bg-blue-600 h-3 rounded-full transition-all"
                                      style={{ width: `${percentage}%` }}
                                    ></div>
                                  </div>
                                </div>
                              );
                            })}
                          </div>
                        )}

                        {stats.type === 'rating' && (
                          <div className="space-y-4">
                            <div className="text-center py-4 bg-blue-50 rounded-lg border border-blue-200">
                              <div className="text-4xl font-bold text-blue-900">{stats.average}</div>
                              <div className="text-sm text-gray-600">Average Rating (out of {question.rating_max || 5})</div>
                            </div>
                            <div className="space-y-2">
                              {Object.entries(stats.distribution).reverse().map(([rating, count]) => {
                                const percentage = stats.total > 0 ? ((count / stats.total) * 100).toFixed(1) : 0;
                                return (
                                  <div key={rating} className="flex items-center gap-3">
                                    <span className="text-sm font-medium text-gray-700 w-12">{rating} ⭐</span>
                                    <div className="flex-1">
                                      <div className="w-full bg-gray-200 rounded-full h-3">
                                        <div
                                          className="bg-blue-600 h-3 rounded-full transition-all"
                                          style={{ width: `${percentage}%` }}
                                        ></div>
                                      </div>
                                    </div>
                                    <span className="text-sm text-gray-600 w-20 text-right">{count} ({percentage}%)</span>
                                  </div>
                                );
                              })}
                            </div>
                          </div>
                        )}

                        {stats.type === 'text' && (
                          <div className="space-y-3 max-h-96 overflow-y-auto">
                            {stats.responses.map((response, idx) => (
                              <div key={idx} className="bg-gray-50 border rounded p-3">
                                <div className="text-sm text-gray-700">{response}</div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}

              {responseTab === 'individual' && (
                <div className="overflow-x-auto">
                  <table className="min-w-full border">
                    <thead className="bg-blue-600">
                      <tr>
                        <th className="text-white px-3 py-2 text-left">#</th>
                        <th className="text-white px-3 py-2 text-left">Submitted At</th>
                        <th className="text-white px-3 py-2 text-left">Respondent</th>
                        <th className="text-white px-3 py-2 text-left">Responses</th>
                      </tr>
                    </thead>
                    <tbody>
                      {responsesData.map((response, idx) => (
                        <tr key={response.id} className="border-b hover:bg-gray-50">
                          <td className="px-3 py-2">{idx + 1}</td>
                          <td className="px-3 py-2 text-sm">
                            {new Date(response.submitted_at).toLocaleString()}
                          </td>
                          <td className="px-3 py-2 text-sm">
                            {response.user_email || response.user_name || 'Anonymous'}
                          </td>
                          <td className="px-3 py-2">
                            <button
                              className="text-blue-600 hover:underline text-sm"
                              onClick={() => handleViewDetails(response)}
                            >
                              View Details
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default ResponseModal;