'use client';

import { useEffect, useState } from "react";
import Input from '../../atoms/Input';
import Button from "../../atoms/Button";
import { FaTimes } from "react-icons/fa";
import Swal from "sweetalert2";
import { toast } from "sonner";

export default function ReplyModal({ isOpen, onClose, replyingTo, article, onReplySubmitted }) {
  const [formData, setFormData] = useState({
    first_name: '',
    last_name: '',
    email: '',
    comment: '',
    phone_number: ''
  });
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }

    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isOpen]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!replyingTo || !formData.comment.trim()) return;

    setIsLoading(true);

    try {
      const isReplyToReply = replyingTo.hasOwnProperty('reply_id');
      const payload = {
        ...formData,
        article_id: article.id.toString(),
        article_url: typeof window !== 'undefined' ? window.location.href : '',
        type: 'blog',
        phone_number: formData.phone_number || '',
        status: 'pending'
      };

      if (isReplyToReply) {
        payload.parent_reply_id = replyingTo.reply_id;
        payload.parent_comment_id = replyingTo.parent_comment_id;
      } else {
        payload.parent_comment_id = replyingTo.comment_id;
      }

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

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'Failed to submit reply');
      }

      Swal.fire({
        title: 'Thank you!',
        text: 'Your reply is awaiting approval.',
        icon: 'success',
        background: '#fff',
        confirmButtonColor: '#0B6F78'
      });
      
      setFormData({ first_name: '', last_name: '', email: '', comment: '', phone_number: '' });
      
      if (onReplySubmitted) {
        await onReplySubmitted();
      }
    } catch (error) {
      toast.error(error.message || "An error occurred while submitting your reply");
    } finally {
      setIsLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      <div 
        className="fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm transition-opacity"
        onClick={onClose}
        aria-hidden="true"
      />
      
      <div className="flex items-center justify-center min-h-screen p-4">
        <div 
          className="relative bg-white rounded-2xl shadow-2xl transform transition-all w-full max-w-lg"
          onClick={(e) => e.stopPropagation()}
        >
          <div className="bg-white p-6 rounded-2xl">
            <div className="flex justify-between items-center mb-6">
              <h3 className="text-xl font-semibold text-gray-900">
                Reply to {replyingTo?.first_name}
              </h3>
              <button 
                onClick={onClose}
                className="text-gray-500 hover:text-gray-700 transition-colors"
              >
                <FaTimes />
              </button>
            </div>
            
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <Input
                  name="first_name"
                  placeholder="First Name"
                  value={formData.first_name}
                  onChange={handleInputChange}
                  required
                />
                <Input
                  name="last_name"
                  placeholder="Last Name"
                  value={formData.last_name}
                  onChange={handleInputChange}
                  required
                />
              </div>
              
              <Input
                name="email"
                type="email"
                placeholder="Email Address"
                value={formData.email}
                onChange={handleInputChange}
                required
              />
              
              <Input
                name="phone_number"
                placeholder="Phone Number (Optional)"
                value={formData.phone_number}
                onChange={handleInputChange}
              />
              
              <textarea
                name="comment"
                placeholder="Write your reply..."
                value={formData.comment}
                onChange={handleInputChange}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent h-32 resize-none"
                required
              />
              
              <div className="flex justify-end gap-3 pt-4">
                <Button
                  variant="outline"
                  onClick={onClose}
                  type="button"
                  className="border-gray-300 text-gray-700 hover:border-gray-400"
                >
                  Cancel
                </Button>
                <Button 
                  type="submit"
                  disabled={isLoading}
                  className="bg-linear-to-r from-[#0B6F78] to-[#0a306b] hover:from-[#0a306b] hover:to-[#0B6F78]"
                >
                  {isLoading ? "Posting..." : "Post Reply"}
                </Button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}