import { useState, useEffect } from 'react';
import { Card, Row, Col, Tag, Typography, Spin, Empty, Grid } from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import type { StrawPoll } from '@/types/api';
import { STRAW_POLL_TYPE_LABELS } from '@/types/api';

dayjs.extend(relativeTime);

const { Title, Text, Paragraph } = Typography;

const apiBase = '/api';

export default function StrawPollsListPage() {
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [polls, setPolls] = useState<StrawPoll[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios.get(`${apiBase}/straw-polls/public`, { params: { limit: 50 } })
      .then(res => setPolls(res.data.polls))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
  if (polls.length === 0) return <Empty description="No active polls" style={{ marginTop: 80 }} />;

  return (
    <div style={{ padding: isMobile ? 16 : 32, maxWidth: 1000, margin: '0 auto' }}>
      <Title level={2} style={{ textAlign: 'center', marginBottom: 32 }}>Straw Polls</Title>
      <Row gutter={[16, 16]}>
        {polls.map(poll => (
          <Col key={poll.id} xs={24} sm={12} md={8}>
            <Card
              hoverable
              onClick={() => navigate(`/straw-poll/${poll.slug}`)}
              style={{ height: '100%' }}
            >
              <Tag style={{ marginBottom: 8 }}>{STRAW_POLL_TYPE_LABELS[poll.type]}</Tag>
              <Title level={5} style={{ marginTop: 0, marginBottom: 8 }}>{poll.title}</Title>
              {poll.description && (
                <Paragraph ellipsis={{ rows: 2 }} type="secondary" style={{ marginBottom: 8 }}>
                  {poll.description}
                </Paragraph>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Text type="secondary">{poll._count?.votes ?? 0} votes</Text>
                {poll.closesAt && (
                  <Text type="secondary">Closes {dayjs(poll.closesAt).fromNow()}</Text>
                )}
              </div>
            </Card>
          </Col>
        ))}
      </Row>
    </div>
  );
}
