import React, { useState, useRef } from 'react';
import useSWRInfinite from 'swr/infinite';
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { Textarea } from "@/components/ui/textarea";
import { ScrollArea } from "@/components/ui/scroll-area";
import { MessageCircle, Reply, X } from "lucide-react";
import { APP_BASE_URL } from '@/utils/constants';
import { getEduConnectAccessToken } from '@/helpers/token.helper';
import { usePathname } from 'next/navigation';
import { fetchHeader } from '@/helpers/fetch.helper';

// Updated Types
interface Message {
  id: string;
  isSelf: number;
  text: string;
  timestamp: string;
  userId: string;
  username: string;
}

interface ApiResponse {
  count: number;
  messages: Message[];
}

interface PageData {
  messages: Message[];
  hasMore: boolean;
}

interface DiscussionSectionProps {
  courseUuid: string;
}

// Key generator for SWR
const getKey = (courseUuid: string) => (pageIndex: number, previousPageData: PageData | null) => {
  if (previousPageData && !previousPageData.messages.length) return null;
  return `${APP_BASE_URL}/api/chat/get`;
};

// Updated fetcher function
const fetcher = async (url: string, courseUuid: string): Promise<PageData> => {
  const formData = new FormData();
  formData.append('course_id', courseUuid);
  
  const response = await fetch(url, {
    method: 'POST',
    body: formData,
    headers: {
      Authorization: `Bearer ${getEduConnectAccessToken()}`
    }
  });
  
  if (!response.ok) {
    throw new Error('Failed to fetch discussions');
  }
  
  const data: ApiResponse = await response.json();
  return {
    messages: data.messages.map(message => ({
      ...message,
      timestamp: new Date(message.timestamp).toLocaleString()
    })),
    hasMore: data.count > data.messages.length
  };
};

const EnhancedDiscussionSection: React.FC<DiscussionSectionProps> = ({ courseUuid }) => {
  const [comment, setComment] = useState('');
  const [replyingTo, setReplyingTo] = useState<any>(null);
  const loadingRef = useRef<HTMLDivElement>(null);
  const pathname = usePathname();
  const id = pathname.split('/')?.at(-1);

  const {
    data,
    error,
    size,
    setSize,
    isValidating,
    mutate
  } = useSWRInfinite(
    getKey(courseUuid),
    (url) => fetcher(url, id!),
    {
      revalidateFirstPage: false,
      revalidateOnFocus: false,
      persistSize: true
    }
  );

  const allMessages = data ? data.flatMap(page => page.messages) : [];
  const hasMore = data ? data[data.length - 1]?.hasMore : true;
  const isLoadingMore = !data && !error || (size > 0 && data && typeof data[size - 1] === "undefined");

  // Intersection Observer for infinite loading
  React.useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasMore && !isValidating) {
          setSize(size + 1);
        }
      },
      { threshold: 0.1 }
    );

    if (loadingRef.current) {
      observer.observe(loadingRef.current);
    }

    return () => observer.disconnect();
  }, [hasMore, isValidating, setSize, size]);

    const handleSubmit = async () => {
      if (comment.trim()) {
        const formData = new FormData();
        formData.append('course_id', courseUuid);
        formData.append('message', comment);
        // if (replyingTo) {
        //   formData.append('parent_id', replyingTo.commentId.toString());
        // }

        try {
          const response = await fetch(`${APP_BASE_URL}/api/chat/send`, {
            method: 'POST',
            body: formData,
            headers : fetchHeader()
          });

          if (!response.ok) {
            throw new Error('Failed to post comment');
          }


          // Optimistically update the UI
          

          await mutate();
          setComment('');
          setReplyingTo(null);
        } catch (error) {
          console.error('Failed to post comment:', error);
          // You might want to show an error message to the user here
        }
      }
    };

    const handleReply = (commentId: number, userName: string) => {
      setReplyingTo({ commentId, userName });
      setComment(`@${userName} `);
    };

    const cancelReply = () => {
      setReplyingTo(null);
      setComment('');
    };

    if (error) {
      return (
        <div className="text-red-500 p-4 text-center">
          Error loading discussions. Please try again later.
        </div>
      );
    }

  // Rest of your component implementation remains similar, just update the rendering logic:
  return (
    <div className="w-full max-w-3xl mx-auto">
      <ScrollArea className="h-[600px]">
        <div className="space-y-6 p-4">
          {allMessages.map((message) => (
            <Card key={message.id} className="p-4">
              <div className="space-y-4">
                <div className="flex gap-4">
                  <Avatar className="w-8 h-8">
                    <AvatarImage src="/api/placeholder/32/32" alt={message.username} />
                    <AvatarFallback>{message.username[0]}</AvatarFallback>
                  </Avatar>
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="font-medium">{message.username}</span>
                      <span className="text-sm text-gray-500">{message.timestamp}</span>
                    </div>
                    <p className="text-gray-700 mb-2">{message.text}</p>
                  </div>
                </div>
              </div>
            </Card>
          ))}

          <div ref={loadingRef} className="h-10 flex items-center justify-center">
            {isLoadingMore && (
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900" />
            )}
            {!hasMore && allMessages.length > 0 && (
              <div className="text-gray-500">No more messages</div>
            )}
          </div>
        </div>
      </ScrollArea>

      <div className="my-6 px-4">
        <div className="flex items-start gap-4">
          <Avatar className="w-8 h-8">
            <AvatarImage src="/api/placeholder/32/32" alt="User" />
            <AvatarFallback>U</AvatarFallback>
          </Avatar>
          <div className="flex-1">
            <Textarea
              placeholder="Add to the discussion..."
              value={comment}
              onChange={(e) => setComment(e.target.value)}
              className="min-h-24 mb-6"
            />
            <div className="w-fit ml-auto">
              <Button onClick={handleSubmit} className="bg-purple-700">
                Post Message
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EnhancedDiscussionSection;