import { useState, useEffect, useCallback } from 'react';
import {
  Typography,
  Card,
  Button,
  Row,
  Col,
  Tag,
  Input,
  Radio,
  Checkbox,
  Select,
  message,
  Spin,
  Result,
  Grid,
  Space,
  Divider,
  Alert,
  Collapse,
} from 'antd';
import {
  CalendarOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  CheckCircleOutlined,
  SendOutlined,
  EyeOutlined,
  LockOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { useParams, useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import type {
  PollDetailResponse,
  PollVoteValue,
} from '@/types/api';
import {
  POLL_STATUS_COLORS,
  POLL_STATUS_LABELS,
  VOTE_VALUE_COLORS,
  VOTE_VALUE_LABELS,
} from '@/types/api';
import { useAuthStore } from '@/stores/auth.store';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { Title, Text, Paragraph } = Typography;

const VOTER_TOKEN_KEY = 'poll_voter_token_';

export default function SchedulingPollPage() {
  const { slug } = useParams<{ slug: string }>();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const navigate = useNavigate();
  const { user } = useAuthStore();

  const [poll, setPoll] = useState<PollDetailResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  // Vote form state
  const [voterName, setVoterName] = useState(user?.name || '');
  const [voterEmail, setVoterEmail] = useState(user?.email || '');
  const [votes, setVotes] = useState<Record<string, PollVoteValue>>({});
  const [submitting, setSubmitting] = useState(false);
  const [hasVoted, setHasVoted] = useState(false);
  const [voteSuccess, setVoteSuccess] = useState(false);

  // Participant needs state
  const [needsExpanded, setNeedsExpanded] = useState(false);
  const [participantNeeds, setParticipantNeeds] = useState<Record<string, any>>({});

  const updateNeed = (key: string, value: any) => {
    setParticipantNeeds((prev) => ({ ...prev, [key]: value }));
  };

  // Comment form state
  const [commentName, setCommentName] = useState(user?.name || '');
  const [commentContent, setCommentContent] = useState('');
  const [commentSubmitting, setCommentSubmitting] = useState(false);

  const fetchPoll = useCallback(async () => {
    if (!slug) return;
    setLoading(true);
    try {
      const { data } = await api.get<PollDetailResponse>(`/meeting-planner/public/${slug}`);
      setPoll(data);

      // Check if user has already voted (by token or auth)
      const storedToken = localStorage.getItem(VOTER_TOKEN_KEY + slug);
      if (storedToken || user) {
        const existingVoter = data.voters?.find((v) => {
          if (user) return data.votes?.some((vote) => vote.userId === user.id && v.name === vote.voterName);
          return false;
        });
        if (existingVoter) {
          setVoterName(existingVoter.name);
          setVotes(existingVoter.votes);
          setHasVoted(true);
        } else if (storedToken) {
          // Find voter by checking if any vote has our token
          // We can't see tokens in the response, but if we stored one, we know we voted
          setHasVoted(true);
        }
      }
    } catch {
      setError(true);
    } finally {
      setLoading(false);
    }
  }, [slug, user]);

  useEffect(() => { fetchPoll(); }, [fetchPoll]);

  const handleVoteChange = (optionId: string, value: PollVoteValue) => {
    setVoteSuccess(false);
    setVotes((prev) => ({ ...prev, [optionId]: value }));
  };

  const handleSubmitVotes = async () => {
    if (!poll || !voterName.trim()) {
      message.warning('Please enter your name');
      return;
    }
    if (!Object.keys(votes).length) {
      message.warning('Please vote on at least one option');
      return;
    }
    const trimmedEmail = voterEmail.trim();
    if (trimmedEmail && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmedEmail)) {
      message.warning('Please enter a valid email address, or leave the email field blank');
      return;
    }

    setSubmitting(true);
    try {
      const storedToken = localStorage.getItem(VOTER_TOKEN_KEY + slug);
      const hasNeeds = Object.values(participantNeeds).some((v) => v === true || (typeof v === 'string' && v.trim()));
      const { data } = await api.post(`/meeting-planner/public/${slug}/vote`, {
        voterName: voterName.trim(),
        voterEmail: trimmedEmail || undefined,
        voterToken: storedToken || undefined,
        votes: Object.entries(votes).map(([optionId, value]) => ({ optionId, value })),
        ...(hasNeeds ? { participantNeeds } : {}),
      });

      // Store voter token for anonymous edit access
      if (data.voterToken) {
        localStorage.setItem(VOTER_TOKEN_KEY + slug, data.voterToken);
      }

      message.success(hasVoted ? 'Votes updated' : 'Votes submitted');
      setHasVoted(true);
      setVoteSuccess(true);
      fetchPoll();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to submit votes'));
    } finally {
      setSubmitting(false);
    }
  };

  const handleSubmitComment = async () => {
    if (!commentName.trim() || !commentContent.trim()) {
      message.warning('Please enter your name and comment');
      return;
    }
    setCommentSubmitting(true);
    try {
      await api.post(`/meeting-planner/public/${slug}/comment`, {
        authorName: commentName.trim(),
        content: commentContent.trim(),
      });
      message.success('Comment added');
      setCommentContent('');
      fetchPoll();
    } catch {
      message.error('Failed to add comment');
    } finally {
      setCommentSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 80 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (error || !poll) {
    return (
      <Result
        status="404"
        title="Poll Not Found"
        subTitle="This scheduling poll may have been removed or the link is invalid."
      />
    );
  }

  if (poll.requiresAuth) {
    return (
      <div style={{ maxWidth: 500, margin: '0 auto', padding: isMobile ? '40px 16px' : '80px 16px' }}>
        <Result
          icon={<LockOutlined style={{ color: '#faad14' }} />}
          title={poll.title}
          subTitle="This poll is private. Please sign in to view the details and participate."
          extra={
            <Button
              type="primary"
              size="large"
              onClick={() => navigate(`/login?redirect=/poll/${slug}`)}
            >
              Sign In to View
            </Button>
          }
        />
      </div>
    );
  }

  const isOpen = poll.status === 'OPEN';
  const isFinalized = poll.status === 'FINALIZED';
  const bestScore = poll.options?.length ? Math.max(...poll.options.map((o) => o.score ?? 0)) : 0;

  return (
    <div style={{ maxWidth: 900, margin: '0 auto', padding: isMobile ? '16px 12px' : '24px 16px' }}>
      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <Title level={isMobile ? 3 : 2} style={{ marginBottom: 8 }}>
          <CalendarOutlined style={{ marginRight: 8 }} />
          {poll.title}
        </Title>
        {poll.description && (
          <Paragraph style={{ fontSize: 16, opacity: 0.85, marginBottom: 12 }}>
            {poll.description}
          </Paragraph>
        )}
        <Space wrap>
          <Tag color={POLL_STATUS_COLORS[poll.status]}>{POLL_STATUS_LABELS[poll.status]}</Tag>
          {poll.location && (
            <Text type="secondary">
              <EnvironmentOutlined style={{ marginRight: 4 }} />
              {poll.location}
            </Text>
          )}
          <Text type="secondary">
            <ClockCircleOutlined style={{ marginRight: 4 }} />
            {poll.timezone}
          </Text>
          {poll.createdBy && (
            <Text type="secondary">
              by {poll.createdBy.name || poll.createdBy.email}
            </Text>
          )}
        </Space>
      </div>

      {/* Deadline banner */}
      {poll.votingDeadline && isOpen && (
        <Alert
          type={dayjs(poll.votingDeadline).isBefore(dayjs()) ? 'error' : 'info'}
          message={
            dayjs(poll.votingDeadline).isBefore(dayjs())
              ? 'Voting deadline has passed'
              : `Voting deadline: ${dayjs(poll.votingDeadline).format('MMM D, YYYY h:mm A')}`
          }
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      {/* Finalized banner */}
      {isFinalized && poll.finalizedOption && (
        <Alert
          type="success"
          message="Date Confirmed"
          description={
            <Space>
              <CheckCircleOutlined />
              <Text strong>
                {dayjs(poll.finalizedOption.date).format('dddd, MMMM D, YYYY')} — {poll.finalizedOption.startTime}–{poll.finalizedOption.endTime}
              </Text>
            </Space>
          }
          showIcon
          style={{ marginBottom: 24 }}
        />
      )}

      {/* Voting */}
      {isMobile ? (
        /* Mobile: vertical cards */
        <div style={{ marginBottom: 24 }}>
          {poll.options?.map((opt) => (
            <Card
              key={opt.id}
              size="small"
              style={{
                marginBottom: 12,
                border: isFinalized && poll.finalizedOptionId === opt.id ? '2px solid #52c41a' : undefined,
                background: opt.score === bestScore && bestScore > 0 ? 'rgba(82, 196, 26, 0.05)' : undefined,
              }}
            >
              <Row justify="space-between" align="middle">
                <Col>
                  <Text strong>{dayjs(opt.date).format('ddd, MMM D')}</Text>
                  <br />
                  <Text type="secondary">{opt.startTime} – {opt.endTime}</Text>
                </Col>
                <Col>
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    {opt.yesCount}Y / {opt.ifNeedBeCount}M / {opt.noCount}N
                  </Text>
                </Col>
              </Row>
              {isOpen && (
                <div style={{ marginTop: 12 }}>
                  <Radio.Group
                    value={votes[opt.id]}
                    onChange={(e) => handleVoteChange(opt.id, e.target.value)}
                    optionType="button"
                    buttonStyle="solid"
                    size="small"
                  >
                    <Radio.Button value="YES" style={{ color: votes[opt.id] === 'YES' ? '#fff' : undefined }}>Yes</Radio.Button>
                    <Radio.Button value="IF_NEED_BE">If Need Be</Radio.Button>
                    <Radio.Button value="NO">No</Radio.Button>
                  </Radio.Group>
                </div>
              )}
            </Card>
          ))}

          {/* Mobile: collapsible voter responses */}
          {(poll.voters?.length ?? 0) > 0 && (
            <Collapse
              ghost
              style={{ marginBottom: 12 }}
              items={[{
                key: 'responses',
                label: (
                  <Space>
                    <EyeOutlined />
                    <span>View Responses ({poll.voters?.length})</span>
                  </Space>
                ),
                children: (
                  <div>
                    {poll.voters?.map((voter, i) => (
                      <div
                        key={i}
                        style={{
                          padding: '10px 0',
                          borderBottom: i < (poll.voters?.length ?? 0) - 1 ? '1px solid #252525' : undefined,
                        }}
                      >
                        <Text strong style={{ display: 'block', marginBottom: 6 }}>{voter.name}</Text>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                          {poll.options?.map((opt) => {
                            const value = voter.votes[opt.id] as PollVoteValue | undefined;
                            return value ? (
                              <Tag
                                key={opt.id}
                                color={value === 'YES' ? 'green' : value === 'IF_NEED_BE' ? 'gold' : 'default'}
                                style={{ fontSize: 11 }}
                              >
                                {dayjs(opt.date).format('M/D')} {VOTE_VALUE_LABELS[value]}
                              </Tag>
                            ) : null;
                          })}
                        </div>
                      </div>
                    ))}
                    {/* Score summary */}
                    <Divider style={{ margin: '8px 0' }} />
                    <Text strong style={{ display: 'block', marginBottom: 6 }}>Scores</Text>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                      {poll.options?.map((opt) => (
                        <Tag
                          key={opt.id}
                          color={opt.score === bestScore && bestScore > 0 ? 'green' : 'default'}
                          style={{ fontSize: 11 }}
                        >
                          {dayjs(opt.date).format('M/D')}: {opt.score ?? 0}
                        </Tag>
                      ))}
                    </div>
                  </div>
                ),
              }]}
            />
          )}
        </div>
      ) : (
        /* Desktop: voting matrix */
        <Card size="small" style={{ marginBottom: 24 }}>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr>
                  <th style={{ padding: '10px 14px', borderBottom: '2px solid #303030', textAlign: 'left', minWidth: 140 }}>
                    Participant
                  </th>
                  {poll.options?.map((opt) => (
                    <th
                      key={opt.id}
                      style={{
                        padding: '10px 14px',
                        borderBottom: '2px solid #303030',
                        textAlign: 'center',
                        minWidth: 110,
                        background: isFinalized && poll.finalizedOptionId === opt.id
                          ? 'rgba(82, 196, 26, 0.15)'
                          : opt.score === bestScore && bestScore > 0
                            ? 'rgba(82, 196, 26, 0.08)'
                            : undefined,
                      }}
                    >
                      <div style={{ fontWeight: 600 }}>{dayjs(opt.date).format('ddd, MMM D')}</div>
                      <div style={{ fontSize: 11, opacity: 0.7 }}>{opt.startTime}–{opt.endTime}</div>
                      {isFinalized && poll.finalizedOptionId === opt.id && (
                        <Tag color="green" style={{ marginTop: 4, fontSize: 10 }}>Confirmed</Tag>
                      )}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {poll.voters?.map((voter, i) => (
                  <tr key={i}>
                    <td style={{ padding: '8px 14px', borderBottom: '1px solid #252525' }}>
                      {voter.name}
                    </td>
                    {poll.options?.map((opt) => {
                      const value = voter.votes[opt.id] as PollVoteValue | undefined;
                      return (
                        <td
                          key={opt.id}
                          style={{
                            padding: '8px 14px',
                            borderBottom: '1px solid #252525',
                            textAlign: 'center',
                            background: value ? `${VOTE_VALUE_COLORS[value]}18` : undefined,
                          }}
                        >
                          {value && (
                            <Tag
                              color={value === 'YES' ? 'green' : value === 'IF_NEED_BE' ? 'gold' : 'default'}
                              style={{ margin: 0 }}
                            >
                              {VOTE_VALUE_LABELS[value]}
                            </Tag>
                          )}
                        </td>
                      );
                    })}
                  </tr>
                ))}
                {/* Score row */}
                <tr style={{ fontWeight: 600 }}>
                  <td style={{ padding: '10px 14px', borderTop: '2px solid #303030' }}>Score</td>
                  {poll.options?.map((opt) => (
                    <td
                      key={opt.id}
                      style={{
                        padding: '10px 14px',
                        borderTop: '2px solid #303030',
                        textAlign: 'center',
                        background: opt.score === bestScore && bestScore > 0 ? 'rgba(82, 196, 26, 0.12)' : undefined,
                      }}
                    >
                      <div style={{ fontSize: 16 }}>{opt.score ?? 0}</div>
                      <div style={{ fontSize: 11, opacity: 0.7 }}>
                        {opt.yesCount}Y / {opt.ifNeedBeCount}M / {opt.noCount}N
                      </div>
                    </td>
                  ))}
                </tr>
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* Vote Form */}
      {isOpen && (
        <Card
          size="small"
          title={hasVoted ? 'Update Your Votes' : 'Cast Your Votes'}
          style={{ marginBottom: 24 }}
        >
          <Row gutter={[12, 12]} style={{ marginBottom: 16 }}>
            <Col xs={24} sm={12}>
              <Input
                placeholder="Your name"
                value={voterName}
                onChange={(e) => setVoterName(e.target.value)}
                disabled={!!user}
              />
            </Col>
            <Col xs={24} sm={12}>
              <Input
                placeholder="Email (optional, for notifications)"
                value={voterEmail}
                onChange={(e) => setVoterEmail(e.target.value)}
                disabled={!!user}
              />
            </Col>
          </Row>

          {/* Desktop: inline radio buttons per option */}
          {!isMobile && poll.options?.map((opt) => (
            <Row key={opt.id} gutter={12} align="middle" style={{ marginBottom: 8 }}>
              <Col flex="200px">
                <Text>{dayjs(opt.date).format('ddd, MMM D')} {opt.startTime}–{opt.endTime}</Text>
              </Col>
              <Col flex="auto">
                <Radio.Group
                  value={votes[opt.id]}
                  onChange={(e) => handleVoteChange(opt.id, e.target.value)}
                  optionType="button"
                  buttonStyle="solid"
                  size="small"
                >
                  <Radio.Button value="YES">Yes</Radio.Button>
                  <Radio.Button value="IF_NEED_BE">If Need Be</Radio.Button>
                  <Radio.Button value="NO">No</Radio.Button>
                </Radio.Group>
              </Col>
            </Row>
          ))}

          {/* Participant Needs (collapsible) */}
          <Collapse
            ghost
            activeKey={needsExpanded ? ['needs'] : []}
            onChange={(keys) => setNeedsExpanded(keys.includes('needs'))}
            style={{ marginTop: 16 }}
            items={[{
              key: 'needs',
              label: (
                <Text style={{ fontSize: 13 }}>
                  Accessibility & Needs (optional)
                </Text>
              ),
              children: (
                <div>
                  <Text type="secondary" style={{ display: 'block', marginBottom: 12, fontSize: 12 }}>
                    Help us prepare an accessible and inclusive space. This info is shared only with organizers by default.
                  </Text>

                  {/* Mobility / Accessibility */}
                  <Text strong style={{ display: 'block', marginBottom: 6, fontSize: 13 }}>Accessibility</Text>
                  <Row gutter={[8, 4]} style={{ marginBottom: 12 }}>
                    <Col xs={24} sm={12}>
                      <Checkbox checked={participantNeeds.needsWheelchair} onChange={(e) => updateNeed('needsWheelchair', e.target.checked)}>
                        Wheelchair accessible
                      </Checkbox>
                    </Col>
                    <Col xs={24} sm={12}>
                      <Checkbox checked={participantNeeds.needsGroundFloor} onChange={(e) => updateNeed('needsGroundFloor', e.target.checked)}>
                        Ground floor / no stairs
                      </Checkbox>
                    </Col>
                    <Col xs={24} sm={12}>
                      <Checkbox checked={participantNeeds.needsHearingLoop} onChange={(e) => updateNeed('needsHearingLoop', e.target.checked)}>
                        Hearing loop
                      </Checkbox>
                    </Col>
                    <Col xs={24} sm={12}>
                      <Checkbox checked={participantNeeds.needsSignLanguage} onChange={(e) => updateNeed('needsSignLanguage', e.target.checked)}>
                        Sign language interpretation
                      </Checkbox>
                    </Col>
                    <Col xs={24}>
                      <Input
                        placeholder="Other accessibility needs..."
                        size="small"
                        value={participantNeeds.otherAccessibility || ''}
                        onChange={(e) => updateNeed('otherAccessibility', e.target.value || null)}
                        style={{ marginTop: 4 }}
                      />
                    </Col>
                  </Row>

                  {/* Dietary */}
                  <Text strong style={{ display: 'block', marginBottom: 6, fontSize: 13 }}>Dietary</Text>
                  <Row gutter={[8, 4]} style={{ marginBottom: 12 }}>
                    <Col xs={12} sm={8}><Checkbox checked={participantNeeds.isVegan} onChange={(e) => updateNeed('isVegan', e.target.checked)}>Vegan</Checkbox></Col>
                    <Col xs={12} sm={8}><Checkbox checked={participantNeeds.isVegetarian} onChange={(e) => updateNeed('isVegetarian', e.target.checked)}>Vegetarian</Checkbox></Col>
                    <Col xs={12} sm={8}><Checkbox checked={participantNeeds.isGlutenFree} onChange={(e) => updateNeed('isGlutenFree', e.target.checked)}>Gluten-free</Checkbox></Col>
                    <Col xs={12} sm={8}><Checkbox checked={participantNeeds.isHalal} onChange={(e) => updateNeed('isHalal', e.target.checked)}>Halal</Checkbox></Col>
                    <Col xs={12} sm={8}><Checkbox checked={participantNeeds.isKosher} onChange={(e) => updateNeed('isKosher', e.target.checked)}>Kosher</Checkbox></Col>
                    <Col xs={12} sm={8}><Checkbox checked={participantNeeds.hasNutAllergy} onChange={(e) => updateNeed('hasNutAllergy', e.target.checked)}>Nut allergy</Checkbox></Col>
                    <Col xs={24}>
                      <Input
                        placeholder="Other dietary needs..."
                        size="small"
                        value={participantNeeds.otherDietary || ''}
                        onChange={(e) => updateNeed('otherDietary', e.target.value || null)}
                        style={{ marginTop: 4 }}
                      />
                    </Col>
                  </Row>

                  {/* Care Needs */}
                  <Text strong style={{ display: 'block', marginBottom: 6, fontSize: 13 }}>Care &amp; Transportation</Text>
                  <Row gutter={[8, 4]} style={{ marginBottom: 12 }}>
                    <Col xs={24} sm={12}>
                      <Checkbox checked={participantNeeds.needsChildcare} onChange={(e) => updateNeed('needsChildcare', e.target.checked)}>
                        I need childcare
                      </Checkbox>
                      {participantNeeds.needsChildcare && (
                        <Input
                          placeholder="Ages, number of children..."
                          size="small"
                          value={participantNeeds.childcareDetails || ''}
                          onChange={(e) => updateNeed('childcareDetails', e.target.value || null)}
                          style={{ marginTop: 4 }}
                        />
                      )}
                    </Col>
                    <Col xs={24} sm={12}>
                      <Checkbox checked={participantNeeds.needsTransportation} onChange={(e) => updateNeed('needsTransportation', e.target.checked)}>
                        I need transportation
                      </Checkbox>
                      {participantNeeds.needsTransportation && (
                        <Input
                          placeholder="Where from, any notes..."
                          size="small"
                          value={participantNeeds.transportationNotes || ''}
                          onChange={(e) => updateNeed('transportationNotes', e.target.value || null)}
                          style={{ marginTop: 4 }}
                        />
                      )}
                    </Col>
                  </Row>

                  {/* Language */}
                  <Text strong style={{ display: 'block', marginBottom: 6, fontSize: 13 }}>Language</Text>
                  <Row gutter={[8, 8]} style={{ marginBottom: 8 }}>
                    <Col xs={24} sm={12}>
                      <Checkbox checked={participantNeeds.needsTranslation} onChange={(e) => updateNeed('needsTranslation', e.target.checked)}>
                        I need translation / interpretation
                      </Checkbox>
                      {participantNeeds.needsTranslation && (
                        <Input
                          placeholder="Which language?"
                          size="small"
                          value={participantNeeds.translationLanguage || ''}
                          onChange={(e) => updateNeed('translationLanguage', e.target.value || null)}
                          style={{ marginTop: 4 }}
                        />
                      )}
                    </Col>
                    <Col xs={24} sm={12}>
                      <Select
                        placeholder="Who can see this info?"
                        size="small"
                        value={participantNeeds.visibilityConsent || 'organizer_only'}
                        onChange={(v) => updateNeed('visibilityConsent', v)}
                        style={{ width: '100%', marginTop: 4 }}
                        options={[
                          { value: 'organizer_only', label: 'Organizer only' },
                          { value: 'shared_with_hosts', label: 'Shared with hosts' },
                          { value: 'public', label: 'Visible to all participants' },
                        ]}
                      />
                    </Col>
                  </Row>
                </div>
              ),
            }]}
          />

          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSubmitVotes}
            loading={submitting}
            block
            style={{ marginTop: 16 }}
          >
            {hasVoted ? 'Update Votes' : 'Submit Votes'}
          </Button>

          {voteSuccess && (
            <Alert
              type="success"
              message="Your votes have been recorded!"
              showIcon
              icon={<CheckCircleOutlined />}
              style={{ marginTop: 12 }}
              closable
              onClose={() => setVoteSuccess(false)}
            />
          )}
        </Card>
      )}

      {/* Comments Section */}
      <Card
        size="small"
        title={`Comments (${poll.comments?.length ?? 0})`}
        style={{ marginBottom: 24 }}
      >
        {poll.comments?.map((comment) => (
          <div key={comment.id} style={{ marginBottom: 12, paddingBottom: 12, borderBottom: '1px solid #252525' }}>
            <Row justify="space-between">
              <Col>
                <Text strong>{comment.authorName}</Text>
                <Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
                  {dayjs(comment.createdAt).format('MMM D, h:mm A')}
                </Text>
              </Col>
            </Row>
            <Text style={{ display: 'block', marginTop: 4 }}>{comment.content}</Text>
          </div>
        ))}

        {poll.status !== 'CANCELLED' && (
          <>
            <Divider style={{ margin: '12px 0' }} />
            <Row gutter={[8, 8]}>
              <Col xs={24} sm={6}>
                <Input
                  placeholder="Your name"
                  value={commentName}
                  onChange={(e) => setCommentName(e.target.value)}
                  size="small"
                />
              </Col>
              <Col xs={24} sm={14}>
                <Input.TextArea
                  placeholder="Add a comment..."
                  value={commentContent}
                  onChange={(e) => setCommentContent(e.target.value)}
                  rows={1}
                  size="small"
                />
              </Col>
              <Col xs={24} sm={4}>
                <Button
                  type="primary"
                  size="small"
                  onClick={handleSubmitComment}
                  loading={commentSubmitting}
                  block
                >
                  Post
                </Button>
              </Col>
            </Row>
          </>
        )}
      </Card>
    </div>
  );
}
