import { useState, useEffect } from 'react';
import {
  List,
  Input,
  Button,
  Space,
  Typography,
  message,
  Empty,
  Spin,
  Avatar,
  theme,
} from 'antd';
import { UserOutlined, SendOutlined } from '@ant-design/icons';
import { mediaPublicApi, getOrCreateSessionId } from '@/lib/media-public-api';
import { useAuthStore } from '@/stores/auth.store';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import axios from 'axios';

dayjs.extend(relativeTime);

const { TextArea } = Input;
const { Text } = Typography;

interface Comment {
  id: number;
  content: string;
  userId: number | null;
  sessionId: string;
  createdAt: string;
  safetyStatus: string;
}

interface CommentSectionProps {
  videoId: number;
}

export default function CommentSection({ videoId }: CommentSectionProps) {
  const { token } = theme.useToken();
  const [comments, setComments] = useState<Comment[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [commentText, setCommentText] = useState('');
  const [hasMore, setHasMore] = useState(false);
  const [offset, setOffset] = useState(0);
  const limit = 20;

  const fetchComments = async (append = false) => {
    try {
      setLoading(true);
      const currentOffset = append ? offset : 0;

      const response = await mediaPublicApi.get(`/public/${videoId}/comments`, {
        params: { limit, offset: currentOffset },
      });

      if (append) {
        setComments((prev) => [...prev, ...response.data.comments]);
      } else {
        setComments(response.data.comments);
      }

      setHasMore(response.data.pagination.hasMore);
      setOffset(currentOffset + limit);
    } catch (error) {
      console.error('Failed to fetch comments:', error);
      message.error('Failed to load comments');
    } finally {
      setLoading(false);
    }
  };

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

  const handleSubmit = async () => {
    if (!commentText.trim()) {
      message.warning('Please enter a comment');
      return;
    }

    if (commentText.length > 1000) {
      message.error('Comment is too long (max 1000 characters)');
      return;
    }

    // Check if user is logged in
    if (!useAuthStore.getState().isAuthenticated) {
      message.warning('Please log in to comment');
      return;
    }

    try {
      setSubmitting(true);

      const sessionId = getOrCreateSessionId();

      const response = await mediaPublicApi.post(`/public/${videoId}/comments`, {
        sessionId,
        content: commentText.trim(),
      });

      // Add new comment to top of list
      setComments((prev) => [response.data.comment, ...prev]);
      setCommentText('');
      message.success('Comment posted!');
    } catch (error: unknown) {
      if (axios.isAxiosError(error) && error.response?.status === 401) {
        message.error('Please log in to comment');
      } else {
        message.error('Failed to post comment');
      }
      console.error('Failed to post comment:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const handleLoadMore = () => {
    fetchComments(true);
  };

  return (
    <div>
      {/* Comment form */}
      <div
        style={{
          marginBottom: 24,
          padding: 16,
          background: token.colorBgContainer,
          borderRadius: 12,
          border: `1px solid ${token.colorBorderSecondary}`,
        }}
      >
        <TextArea
          value={commentText}
          onChange={(e) => setCommentText(e.target.value)}
          placeholder="Add a comment..."
          autoSize={{ minRows: 3, maxRows: 6 }}
          maxLength={1000}
          showCount
          style={{ marginBottom: 12 }}
        />
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Button
            type="primary"
            icon={<SendOutlined />}
            loading={submitting}
            onClick={handleSubmit}
            disabled={!commentText.trim()}
          >
            Post Comment
          </Button>
        </div>
      </div>

      {/* Comments list */}
      <div>
        <Text strong style={{ fontSize: 16, marginBottom: 16, display: 'block' }}>
          Comments ({comments.length})
        </Text>

        {loading && comments.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 40 }}>
            <Spin />
          </div>
        ) : comments.length === 0 ? (
          <Empty
            description="No comments yet. Be the first to comment!"
            style={{ padding: 40 }}
          />
        ) : (
          <>
            <List
              dataSource={comments}
              renderItem={(comment) => (
                <List.Item
                  style={{
                    padding: '16px 0',
                    borderBottom: `1px solid ${token.colorBorderSecondary}`,
                  }}
                >
                  <List.Item.Meta
                    avatar={
                      <Avatar
                        icon={<UserOutlined />}
                        style={{
                          background: token.colorPrimary,
                        }}
                      />
                    }
                    title={
                      <Space size={8}>
                        <Text strong>
                          {comment.userId ? `User #${comment.userId}` : 'Anonymous'}
                        </Text>
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          {dayjs(comment.createdAt).fromNow()}
                        </Text>
                      </Space>
                    }
                    description={
                      <Text style={{ fontSize: 14, whiteSpace: 'pre-wrap' }}>
                        {comment.content}
                      </Text>
                    }
                  />
                </List.Item>
              )}
            />

            {/* Load more button */}
            {hasMore && (
              <div style={{ textAlign: 'center', marginTop: 16 }}>
                <Button onClick={handleLoadMore} loading={loading}>
                  Load More Comments
                </Button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
