import { useState, useEffect, useCallback } from 'react';
import { List, Input, Button, Typography, Space, Popconfirm, message, Empty, Skeleton } from 'antd';
import { DeleteOutlined, SendOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import type { SharedViewComment } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

interface CalendarCommentsProps {
  viewId: string;
  date: string;
  currentUserId: string;
}

export default function CalendarComments({ viewId, date, currentUserId }: CalendarCommentsProps) {
  const [comments, setComments] = useState<SharedViewComment[]>([]);
  const [loading, setLoading] = useState(true);
  const [newComment, setNewComment] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const fetchComments = useCallback(async () => {
    try {
      const { data } = await api.get<SharedViewComment[]>(
        `/calendar/shared/${viewId}/comments`,
        { params: { date } },
      );
      setComments(data);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, [viewId, date]);

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

  const handleSubmit = async () => {
    if (!newComment.trim()) return;
    setSubmitting(true);
    try {
      await api.post(`/calendar/shared/${viewId}/comments`, {
        itemDate: date,
        content: newComment.trim(),
      });
      setNewComment('');
      await fetchComments();
    } catch {
      message.error('Failed to post comment');
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (commentId: string) => {
    try {
      await api.delete(`/calendar/shared/${viewId}/comments/${commentId}`);
      setComments((prev) => prev.filter((c) => c.id !== commentId));
    } catch {
      message.error('Failed to delete comment');
    }
  };

  if (loading) return <Skeleton active paragraph={{ rows: 2 }} />;

  return (
    <div>
      <Text strong style={{ fontSize: 13, marginBottom: 8, display: 'block' }}>
        Comments
      </Text>

      {comments.length === 0 ? (
        <Empty description="No comments yet" image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <List
          size="small"
          dataSource={comments}
          renderItem={(comment) => (
            <List.Item
              style={{ padding: '6px 0', alignItems: 'flex-start' }}
              actions={
                comment.userId === currentUserId
                  ? [
                      <Popconfirm
                        key="delete"
                        title="Delete comment?"
                        onConfirm={() => handleDelete(comment.id)}
                        okText="Delete"
                        okType="danger"
                      >
                        <Button type="text" size="small" danger icon={<DeleteOutlined />} />
                      </Popconfirm>,
                    ]
                  : undefined
              }
            >
              <div>
                <Space size={4}>
                  <div
                    style={{
                      width: 24,
                      height: 24,
                      borderRadius: '50%',
                      background: 'rgba(157, 78, 221, 0.3)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: 11,
                      flexShrink: 0,
                    }}
                  >
                    {(comment.user.name || comment.user.email)[0]?.toUpperCase()}
                  </div>
                  <Text strong style={{ fontSize: 12 }}>
                    {comment.user.name || comment.user.email}
                  </Text>
                  <Text type="secondary" style={{ fontSize: 11 }}>
                    {dayjs(comment.createdAt).fromNow()}
                  </Text>
                </Space>
                <div style={{ marginLeft: 28, marginTop: 2, fontSize: 13 }}>
                  {comment.content}
                </div>
              </div>
            </List.Item>
          )}
        />
      )}

      <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
        <Input
          size="small"
          placeholder="Add a comment..."
          value={newComment}
          onChange={(e) => setNewComment(e.target.value)}
          onPressEnter={handleSubmit}
          disabled={submitting}
        />
        <Button
          size="small"
          type="primary"
          icon={<SendOutlined />}
          onClick={handleSubmit}
          loading={submitting}
          disabled={!newComment.trim()}
        />
      </div>
    </div>
  );
}
