'use client';

import { useState, useEffect, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { Alert, Button, Form } from 'react-bootstrap';
import { useAuth } from '@/contexts/AuthContext';
import { getCommentsByEvenement, createComment, deleteComment, updateComment } from '@/services/commentService';
import { Comment } from '@/types/comment';
import Link from 'next/link';

interface CommentSectionProps {
  evenementId: number;
}

export default function CommentSection({ evenementId }: CommentSectionProps) {
  const t = useTranslations('Comments');
  const { isAuthenticated, user } = useAuth();

  const [comments, setComments] = useState<Comment[]>([]);
  const [newComment, setNewComment] = useState('');
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [editing, setEditing] = useState<Comment | null>(null);
  const [editText, setEditText] = useState('');

  const loadComments = useCallback(async () => {
    try {
      setLoading(true);
      const data = await getCommentsByEvenement(evenementId);
      setComments(data);
    } catch {
      setError(t('error_load'));
    } finally {
      setLoading(false);
    }
  }, [evenementId, t]);

  useEffect(() => {
    loadComments();
  }, [loadComments]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newComment.trim()) return;

    setSubmitting(true);
    setError('');

    try {
      const comment = await createComment(evenementId, newComment);
      setComments(prev => [comment, ...prev]);
      setNewComment('');
    } catch {
      setError(t('error_create'));
    } finally {
      setSubmitting(false);
    }
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editing || !editText.trim()) return;
    setSubmitting(true);
    setError('');
    try {
      const updated = await updateComment(editing.id, editText.trim());
      setComments(prev => prev.map(c => (c.id === updated.id ? updated : c)));
      setEditing(null);
      setEditText('');
    } catch {
      setError(t('error_update'));
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (commentId: number) => {
    if (!confirm(t('delete_confirm'))) return;

    try {
      await deleteComment(commentId);
      setComments(prev => prev.filter(c => c.id !== commentId));
    } catch {
      setError(t('error_delete'));
    }
  };

  return (
    <div className="comment-section mt-4">
      <h3>{t('title')}</h3>

      {error && <Alert variant="danger" dismissible onClose={() => setError('')}>{error}</Alert>}

      {isAuthenticated ? (
        <Form onSubmit={handleSubmit} className="mb-4">
          <Form.Group className="mb-2">
            <Form.Control
              as="textarea"
              rows={3}
              placeholder={t('placeholder')}
              value={newComment}
              onChange={(e) => setNewComment(e.target.value)}
              disabled={submitting}
            />
          </Form.Group>
          <Button type="submit" variant="primary" disabled={submitting || !newComment.trim()}>
            {t('submit')}
          </Button>
        </Form>
      ) : (
        <p className="text-muted mb-4">
          <Link href="/connexion">
            {t('login_to_comment')}
          </Link>
        </p>
      )}

      {loading ? (
        <p className="text-muted">...</p>
      ) : comments.length === 0 ? (
        <p className="text-muted">{t('empty')}</p>
      ) : (
        <div className="comments-list">
          {comments.map((comment) => (
            <div key={comment.id} className="comment-item border-bottom py-3">
              <div className="d-flex justify-content-between align-items-start">
                <div>
                  <strong>{comment.auteur?.pseudo || 'Anonyme'}</strong>
                  <small className="text-muted ms-2">
                    {comment.date} {comment.heure && `à ${comment.heure}`}
                  </small>
                </div>
                {isAuthenticated && user?.username === comment.auteur?.pseudo && (
                  <span className="d-flex gap-2">
                    <Button variant="link" size="sm" className="p-0" onClick={() => { setEditing(comment); setEditText(comment.texte); }}>
                      {t('edit')}
                    </Button>
                    <Button
                      variant="link"
                      size="sm"
                      className="text-danger p-0"
                      onClick={() => handleDelete(comment.id)}
                    >
                      {t('delete')}
                    </Button>
                  </span>
                )}
              </div>
              {editing?.id === comment.id ? (
                <Form onSubmit={handleUpdate} className="mt-2">
                  <Form.Group className="mb-2" controlId={`comment-edit-${comment.id}`}>
                    <Form.Label className="visually-hidden">{t('edit_label')}</Form.Label>
                    <Form.Control as="textarea" rows={3} value={editText} onChange={(e) => setEditText(e.target.value)} disabled={submitting} />
                  </Form.Group>
                  <div className="d-flex gap-2">
                    <Button type="submit" size="sm" variant="primary" disabled={submitting || !editText.trim()}>{t('save')}</Button>
                    <Button size="sm" variant="secondary" onClick={() => setEditing(null)} disabled={submitting}>{t('cancel')}</Button>
                  </div>
                </Form>
              ) : (
                <p className="mb-0 mt-1">{comment.texte}</p>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
