'use client';

import { useState, useEffect } from 'react';
import Swal from 'sweetalert2';

const ScholarshipComments = ({ scholarshipId }) => {
  const [comments, setComments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showCommentForm, setShowCommentForm] = useState(false);
  const [replyingTo, setReplyingTo] = useState(null);
  const [formData, setFormData] = useState({
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    comment: ''
  });

  // Fetch comments
  const fetchComments = async () => {
    try {
      const response = await fetch(`/api/frontend/scholarships/comments?scholarship_id=${scholarshipId}`);
      const data = await response.json();
      
      if (response.ok) {
        setComments(data.comments || []);
      }
    } catch (error) {
      console.error('Error fetching comments:', error);
      // Show error alert
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load comments',
        timer: 3000,
        showConfirmButton: false
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchComments();
  }, [scholarshipId]);

  // Handle form input changes
  const handleInputChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  // Show success message
  const showSuccessMessage = (isReply = false) => {
    Swal.fire({
      icon: 'success',
      title: 'Success!',
      html: `
        <div class="text-center">
          <p class="mb-2">Your ${isReply ? 'reply' : 'comment'} has been submitted successfully!</p>
          <p class="text-sm text-gray-600">It will be visible after admin approval.</p>
        </div>
      `,
      confirmButtonColor: '#0B6F78',
      confirmButtonText: 'OK',
      timer: 5000,
      showClass: {
        popup: 'animate__animated animate__fadeInDown'
      },
      hideClass: {
        popup: 'animate__animated animate__fadeOutUp'
      }
    });
  };

  // Show error message
  const showErrorMessage = (message) => {
    Swal.fire({
      icon: 'error',
      title: 'Error',
      text: message || 'Error submitting comment',
      confirmButtonColor: '#dc2626',
      timer: 4000
    });
  };

  // Show confirmation dialog for cancel
  const showCancelConfirmation = () => {
    return Swal.fire({
      title: 'Are you sure?',
      text: 'Your unsaved changes will be lost.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#0B6F78',
      cancelButtonColor: '#6b7280',
      confirmButtonText: 'Yes, cancel it!',
      cancelButtonText: 'Continue editing'
    });
  };

  // Submit comment or reply
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    try {
      const payload = {
        scholarship_id: scholarshipId,
        ...formData
      };

      // Add parent_id if this is a reply
      if (replyingTo) {
        payload.parent_id = replyingTo;
      }

      // Show loading state
      Swal.fire({
        title: 'Submitting...',
        text: 'Please wait',
        allowOutsideClick: false,
        didOpen: () => {
          Swal.showLoading();
        }
      });

      const response = await fetch('/api/frontend/scholarships/comments', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      const data = await response.json();

      Swal.close();

      if (response.ok) {
        showSuccessMessage(!!replyingTo);
        setFormData({
          first_name: '',
          last_name: '',
          email: '',
          phone: '',
          comment: ''
        });
        setShowCommentForm(false);
        setReplyingTo(null);
        // Refresh comments
        fetchComments();
      } else {
        showErrorMessage(data.error);
      }
    } catch (error) {
      console.error('Error submitting comment:', error);
      Swal.close();
      showErrorMessage('Network error. Please try again.');
    }
  };

  // Handle cancel
  const handleCancel = async () => {
    // Check if form has any data
    const hasData = Object.values(formData).some(value => value.trim() !== '');
    
    if (!hasData) {
      // No data, just close
      setShowCommentForm(false);
      setReplyingTo(null);
      setFormData({
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        comment: ''
      });
      return;
    }

    // Show confirmation if there's data
    const result = await showCancelConfirmation();
    if (result.isConfirmed) {
      setShowCommentForm(false);
      setReplyingTo(null);
      setFormData({
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        comment: ''
      });
    }
  };

  // Format date
  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  if (loading) {
    return (
      <div className="bg-white rounded-2xl shadow-lg p-8">
        <div className="animate-pulse">
          <div className="h-6 bg-gray-200 rounded w-1/4 mb-4"></div>
          <div className="space-y-3">
            <div className="h-4 bg-gray-200 rounded"></div>
            <div className="h-4 bg-gray-200 rounded w-5/6"></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-2xl shadow-lg p-8">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-2xl font-bold text-gray-900">
          Comments ({comments.reduce((total, comment) => total + 1 + (comment.replies?.length || 0), 0)})
        </h2>
        <button
          onClick={() => setShowCommentForm(true)}
          className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white px-6 py-2 rounded-lg font-semibold hover:shadow-lg transition-all"
        >
          Add Comment
        </button>
      </div>

      {/* Comment Form */}
      {(showCommentForm || replyingTo) && (
        <div className="mb-8 p-6 bg-gray-50 rounded-lg">
          <h3 className="text-lg font-semibold mb-4">
            {replyingTo ? 'Leave a Reply' : 'Add a Comment'}
          </h3>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  First Name *
                </label>
                <input
                  type="text"
                  name="first_name"
                  value={formData.first_name}
                  onChange={handleInputChange}
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#0B6F78]"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Last Name *
                </label>
                <input
                  type="text"
                  name="last_name"
                  value={formData.last_name}
                  onChange={handleInputChange}
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#0B6F78]"
                />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Email *
                </label>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#0B6F78]"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Phone
                </label>
                <input
                  type="tel"
                  name="phone"
                  value={formData.phone}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#0B6F78]"
                />
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Comment *
              </label>
              <textarea
                name="comment"
                value={formData.comment}
                onChange={handleInputChange}
                required
                rows="4"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#0B6F78]"
                placeholder={replyingTo ? 'Write your reply...' : 'Share your thoughts about this scholarship...'}
              />
            </div>
            <div className="flex gap-3">
              <button
                type="submit"
                className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white px-6 py-2 rounded-md font-semibold hover:shadow-lg transition-all"
              >
                Submit {replyingTo ? 'Reply' : 'Comment'}
              </button>
              <button
                type="button"
                onClick={handleCancel}
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-md font-semibold hover:bg-gray-50 transition-all"
              >
                Cancel
              </button>
            </div>
          </form>
        </div>
      )}

      {/* Comments List */}
      <div className="space-y-6">
        {comments.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            No comments yet. Be the first to comment!
          </div>
        ) : (
          comments.map((comment) => (
            <div key={comment.id} className="border-b border-gray-200 pb-6 last:border-b-0">
              {/* Main Comment */}
              <div className="flex space-x-4">
                <div className="flex-shrink-0">
                  <div className="w-10 h-10 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-full flex items-center justify-center text-white font-semibold">
                    {comment.first_name[0]}{comment.last_name[0]}
                  </div>
                </div>
                <div className="flex-1">
                  <div className="flex items-center justify-between">
                    <h4 className="font-semibold text-gray-900">
                      {comment.first_name} {comment.last_name}
                    </h4>
                    <span className="text-sm text-gray-500">
                      {formatDate(comment.created_at)}
                    </span>
                  </div>
                  <p className="text-gray-700 mt-2 whitespace-pre-wrap">{comment.comment}</p>
                  <button
                    onClick={() => setReplyingTo(comment.id)}
                    className="text-sm text-[#0B6F78] hover:text-[#0a306b] font-medium mt-2"
                  >
                    Reply
                  </button>
                </div>
              </div>

              {/* Replies */}
              {comment.replies && comment.replies.length > 0 && (
                <div className="ml-14 mt-4 space-y-4">
                  {comment.replies.map((reply) => (
                    <div key={reply.id} className="flex space-x-4">
                      <div className="flex-shrink-0">
                        <div className="w-8 h-8 bg-gray-400 rounded-full flex items-center justify-center text-white font-semibold text-sm">
                          {reply.first_name[0]}{reply.last_name[0]}
                        </div>
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center justify-between">
                          <h5 className="font-medium text-gray-900">
                            {reply.first_name} {reply.last_name}
                          </h5>
                          <span className="text-xs text-gray-500">
                            {formatDate(reply.created_at)}
                          </span>
                        </div>
                        <p className="text-gray-700 mt-1 text-sm whitespace-pre-wrap">
                          {reply.comment}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))
        )}
      </div>
    </div>
  );
};

export default ScholarshipComments;