'use client';

import { useState } from "react";
import Input from '../../atoms/Input';
import Button from "../../atoms/Button";
import { FaUser, FaPhone } from "react-icons/fa";
import { MdOutlineMailLock } from "react-icons/md";
import { Send, Shield } from 'lucide-react';
import Swal from "sweetalert2";
import { toast } from "sonner";

export default function CommentForm({ article, onCommentSubmitted }) {
  const [formData, setFormData] = useState({
    first_name: '',
    last_name: '',
    phone_number: '',
    email: '',
    comment: ''
  });
  const [isLoading, setIsLoading] = useState(false);

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!article) return;

    setIsLoading(true);

    try {
      const response = await fetch('/api/frontend/comments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          article_id: article.id,
          article_url: typeof window !== 'undefined' ? window.location.href : '',
          type: 'blog',
          status: 'pending'
        })
      });

      const data = await response.json();

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

      Swal.fire({
        title: 'Thank you!',
        text: 'Your comment is awaiting approval.',
        icon: 'success',
        background: '#ffffff',
        color: '#1f2937',
        confirmButtonText: 'OK',
        timer: 3000,
        customClass: {
          confirmButton: 'bg-linear-to-r from-teal-600 to-blue-500 text-white px-6 py-3 rounded-xl font-semibold'
        }
      });

      setFormData({ first_name: '', last_name: '', phone_number: '', email: '', comment: '' });
      
      if (onCommentSubmitted) {
        await onCommentSubmitted();
      }

    } catch (error) {
      toast.error(error.message || "An error occurred while submitting your comment");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto mb-16">
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-8 border border-teal-100 shadow-sm mb-8">
        <div className="flex items-center gap-3 mb-6">
          <div className="p-2 rounded-lg bg-linear-to-r from-teal-50 to-blue-50">
            <Send className="w-6 h-6 text-teal-600" />
          </div>
          <div>
            <h3 className="text-xl font-bold text-gray-900">Post a Comment</h3>
            <p className="text-gray-600 text-sm">Share your thoughts with the community</p>
          </div>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid md:grid-cols-2 gap-6">
            <Input 
              name="first_name" 
              icon={<FaUser className="text-teal-600" />} 
              placeholder="First Name" 
              value={formData.first_name}
              onChange={handleInputChange}
              required
              className="bg-white border-gray-200 focus:border-teal-500 hover:border-teal-300 rounded-xl"
            />
            <Input 
              name="last_name"
              icon={<FaUser className="text-teal-600" />} 
              placeholder="Last Name" 
              value={formData.last_name}
              onChange={handleInputChange}
              required
              className="bg-white border-gray-200 focus:border-teal-500 hover:border-teal-300 rounded-xl"
            />
            <Input 
              name="phone_number" 
              icon={<FaPhone className="text-teal-600" />} 
              placeholder="Phone Number" 
              value={formData.phone_number}
              onChange={handleInputChange}
              className="bg-white border-gray-200 focus:border-teal-500 hover:border-teal-300 rounded-xl"
            />
            <Input 
              name="email" 
              type="email"
              icon={<MdOutlineMailLock className="text-teal-600" />} 
              placeholder="Email Address" 
              value={formData.email}
              onChange={handleInputChange}
              required
              className="bg-white border-gray-200 focus:border-teal-500 hover:border-teal-300 rounded-xl"
            />
          </div>

          <div className="relative">
            <textarea
              name="comment"
              placeholder="Share your thoughts and experiences..."
              className="w-full px-6 py-4 rounded-xl border border-gray-200 bg-white placeholder-gray-500 resize-none h-40 focus:outline-none focus:ring-2 focus:ring-teal-500/30 focus:border-teal-500 transition-all"
              value={formData.comment}
              onChange={handleInputChange}
              required
            />
            <div className="absolute bottom-4 right-4 text-xs text-gray-500">
              {formData.comment.length}/1000
            </div>
          </div>

          <div className="flex flex-col sm:flex-row items-center justify-between pt-4 gap-4">
            <div className="flex items-center gap-2 text-sm text-gray-500 order-2 sm:order-1">
              <Shield className="w-4 h-4 text-teal-600 shrink-0" />
              <span className="text-center sm:text-left">Your comment is moderated for quality</span>
            </div>
            
            <Button 
              type="submit" 
              disabled={isLoading}
              className="bg-linear-to-r from-teal-600 to-blue-500 hover:from-teal-700 hover:to-blue-600 py-4 px-8 text-lg font-semibold rounded-xl hover:shadow-lg transition-all w-full sm:w-auto order-1 sm:order-2"
            >
              {isLoading ? (
                <div className="flex items-center justify-center gap-2">
                  <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  Posting Comment...
                </div>
              ) : (
                <>
                  <Send className="w-5 h-5 mr-2" />
                  Post Comment
                </>
              )}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}