'use client';

import { useState } from 'react';
import { formatDistanceToNow } from 'date-fns';
import { tr } from 'date-fns/locale';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { apiFetchJson } from '@/lib/auth';

interface FeedCommentItem {
  id: string;
  content: string;
  author: {
    id: string;
    firstName: string;
    lastName: string;
    role: string;
  };
  createdAt: string;
}

interface PostCommentsProps {
  postId: string;
  previewComments?: FeedCommentItem[];
  totalCount?: number;
}

export function PostComments({ postId, previewComments = [], totalCount = 0 }: PostCommentsProps) {
  const [comments, setComments] = useState<FeedCommentItem[]>(previewComments);
  const [newComment, setNewComment] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [hasMore, setHasMore] = useState(totalCount > previewComments.length);

  const handleSubmit = async () => {
    if (!newComment.trim()) return;
    setIsSubmitting(true);
    try {
      const res = await apiFetchJson<FeedCommentItem>(`/v1/feed/${postId}/comments`, {
        method: 'POST',
        body: JSON.stringify({ content: newComment }),
      });
      if (res.data) {
        setComments((prev) => [...prev, res.data as FeedCommentItem]);
        setNewComment('');
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="px-5 pb-5 pt-3 bg-gray-50/50">
      <div className="space-y-4 mb-4">
        {comments.map((comment) => (
          <div key={comment.id} className="flex items-start gap-3">
            <div className="flex items-center justify-center w-8 h-8 rounded-full bg-gray-100 text-xs font-semibold flex-shrink-0">
              {comment.author.firstName?.[0] ?? ''}{comment.author.lastName?.[0] ?? ''}
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2">
                <span className="font-semibold text-xs text-gray-900">
                  {comment.author.firstName} {comment.author.lastName}
                </span>
                <span className="text-xs text-gray-400">
                  {formatDistanceToNow(new Date(comment.createdAt), { addSuffix: true, locale: tr })}
                </span>
              </div>
              <p className="text-xs text-gray-700 mt-1">{comment.content}</p>
            </div>
          </div>
        ))}
        {hasMore && (
          <Button variant="secondary" size="sm" className="w-full text-xs">
            Daha fazla yorum
          </Button>
        )}
      </div>

      <div className="flex items-center gap-2">
        <Textarea
          value={newComment}
          onChange={(e) => setNewComment(e.target.value)}
          placeholder="Bir yorum yazın..."
          className="flex-1 bg-gray-50 border-0 rounded-xl focus-visible:ring-2 focus-visible:ring-violet-500 text-sm"
          rows={1}
        />
        <Button
          onClick={handleSubmit}
          disabled={!newComment.trim() || isSubmitting}
          size="sm"
          className="bg-violet-600 hover:bg-violet-700 text-white rounded-xl px-4 text-xs"
        >
          {isSubmitting ? 'Yorum yapılıyor...' : 'Yorum'}
        </Button>
      </div>
    </div>
  );
}
