import { useState, useEffect, useCallback, useRef } from 'react';
import commentService, { type CommentData, type MentionUser } from '../services/commentService';

// ============================================================
// useComments – reusable hook for any doctype's comment section
// ============================================================

interface UseCommentsOptions {
  referenceDoctype: string;
  referenceName: string | null;
  /** Auto-refresh interval in ms (0 = off). Default 30 000 */
  pollInterval?: number;
}

interface UseCommentsReturn {
  comments: CommentData[];
  loading: boolean;
  posting: boolean;
  error: string | null;
  currentUser: string;
  refetch: () => Promise<void>;
  postComment: (content: string) => Promise<void>;
  deleteComment: (commentName: string) => Promise<void>;
  // Mention helpers
  mentionUsers: MentionUser[];
  mentionLoading: boolean;
  searchMentionUsers: (query: string) => Promise<void>;
}

export function useComments({
  referenceDoctype,
  referenceName,
  pollInterval = 30000,
}: UseCommentsOptions): UseCommentsReturn {
  const [comments, setComments] = useState<CommentData[]>([]);
  const [loading, setLoading] = useState(true);
  const [posting, setPosting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentUser, setCurrentUser] = useState('');

  // Mention state
  const [mentionUsers, setMentionUsers] = useState<MentionUser[]>([]);
  const [mentionLoading, setMentionLoading] = useState(false);

  const mentionSearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  // ── Fetch current user once ─────────────────────────────
  useEffect(() => {
    commentService.getCurrentUser().then(setCurrentUser).catch(() => {});
  }, []);

  // ── Fetch comments ──────────────────────────────────────
  const fetchComments = useCallback(async () => {
    if (!referenceName) {
      setComments([]);
      setLoading(false);
      return;
    }
    try {
      const data = await commentService.getComments(referenceDoctype, referenceName);
      setComments(data);
      setError(null);
    } catch (err: any) {
      console.error('Error fetching comments:', err);
      setError(err.message || 'Failed to load comments');
    } finally {
      setLoading(false);
    }
  }, [referenceDoctype, referenceName]);

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

  // ── Optional polling ────────────────────────────────────
  useEffect(() => {
    if (!pollInterval || !referenceName) return;
    const id = setInterval(fetchComments, pollInterval);
    return () => clearInterval(id);
  }, [pollInterval, fetchComments, referenceName]);

  // ── Post comment ────────────────────────────────────────
  const postComment = useCallback(
    async (content: string) => {
      if (!referenceName) return;
      setPosting(true);
      try {
        await commentService.postComment(referenceDoctype, referenceName, content);
        await fetchComments();
      } catch (err: any) {
        throw err; // let caller handle toast
      } finally {
        setPosting(false);
      }
    },
    [referenceDoctype, referenceName, fetchComments]
  );

  // ── Delete comment ──────────────────────────────────────
  const deleteComment = useCallback(
    async (commentName: string) => {
      try {
        await commentService.deleteComment(commentName);
        setComments((prev) => prev.filter((c) => c.name !== commentName));
      } catch (err: any) {
        throw err;
      }
    },
    []
  );

  // ── Mention user search (debounced) ─────────────────────
  const searchMentionUsers = useCallback(async (query: string) => {
    if (mentionSearchTimer.current) clearTimeout(mentionSearchTimer.current);

    setMentionLoading(true);
    mentionSearchTimer.current = setTimeout(async () => {
      try {
        const users = await commentService.searchUsers(query);
        setMentionUsers(users);
      } catch {
        setMentionUsers([]);
      } finally {
        setMentionLoading(false);
      }
    }, 250);
  }, []);

  return {
    comments,
    loading,
    posting,
    error,
    currentUser,
    refetch: fetchComments,
    postComment,
    deleteComment,
    mentionUsers,
    mentionLoading,
    searchMentionUsers,
  };
}