import { useState, useEffect } from 'react';
import {
  Typography,
  Card,
  Button,
  Row,
  Col,
  Tag,
  Spin,
  Grid,
  Space,
  Empty,
} from 'antd';
import {
  CalendarOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  TeamOutlined,
  LockOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import type { SchedulingPoll, PollsListResponse, SchedulingPollStatus } from '@/types/api';
import { POLL_STATUS_COLORS, POLL_STATUS_LABELS } from '@/types/api';

const { Title, Text, Paragraph } = Typography;

export default function PollsListPage() {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const navigate = useNavigate();
  const { user } = useAuthStore();

  const [polls, setPolls] = useState<SchedulingPoll[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchPolls = async () => {
      try {
        const { data } = await api.get<PollsListResponse>('/meeting-planner/public');
        setPolls(data.polls);
      } catch {
        // If unauthorized, try the public listing approach
        setPolls([]);
      } finally {
        setLoading(false);
      }
    };
    fetchPolls();
  }, []);

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

  return (
    <div style={{ maxWidth: 900, margin: '0 auto', padding: isMobile ? '16px 12px' : '24px 16px' }}>
      <Title level={isMobile ? 3 : 2} style={{ marginBottom: 24 }}>
        <CalendarOutlined style={{ marginRight: 8 }} />
        Scheduling Polls
      </Title>

      {polls.length === 0 ? (
        <Empty description="No open polls at the moment" />
      ) : (
        <Row gutter={[16, 16]}>
          {polls.map((poll) => {
            const optionCount = poll._count?.options ?? 0;
            const voteCount = poll._count?.votes ?? 0;

            return (
              <Col xs={24} sm={12} key={poll.id}>
                <Card
                  hoverable
                  onClick={() => navigate(`/poll/${poll.slug}`)}
                  style={{ height: '100%' }}
                >
                  <Space direction="vertical" size="small" style={{ width: '100%' }}>
                    <Row justify="space-between" align="top">
                      <Col flex="auto">
                        <Text strong style={{ fontSize: 16 }}>
                          {poll.isPrivate && <LockOutlined style={{ marginRight: 6, color: '#faad14' }} />}
                          {poll.title}
                        </Text>
                      </Col>
                      <Col>
                        <Tag color={POLL_STATUS_COLORS[poll.status as SchedulingPollStatus]}>
                          {POLL_STATUS_LABELS[poll.status as SchedulingPollStatus]}
                        </Tag>
                      </Col>
                    </Row>

                    {poll.description && (
                      <Paragraph
                        type="secondary"
                        ellipsis={{ rows: 2 }}
                        style={{ marginBottom: 0 }}
                      >
                        {poll.description}
                      </Paragraph>
                    )}

                    <Space split={<span style={{ opacity: 0.3 }}>|</span>} wrap>
                      <Text type="secondary" style={{ fontSize: 13 }}>
                        <CalendarOutlined style={{ marginRight: 4 }} />
                        {optionCount} options
                      </Text>
                      <Text type="secondary" style={{ fontSize: 13 }}>
                        <TeamOutlined style={{ marginRight: 4 }} />
                        {voteCount} votes
                      </Text>
                      {poll.location && (
                        <Text type="secondary" style={{ fontSize: 13 }}>
                          <EnvironmentOutlined style={{ marginRight: 4 }} />
                          {poll.location}
                        </Text>
                      )}
                    </Space>

                    {poll.votingDeadline && (
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        <ClockCircleOutlined style={{ marginRight: 4 }} />
                        Deadline: {dayjs(poll.votingDeadline).format('MMM D, YYYY h:mm A')}
                      </Text>
                    )}

                    <Button type="primary" size="small" block style={{ marginTop: 8 }}>
                      {poll.requiresAuth && !user ? 'Sign In to View' : 'Vote Now'}
                    </Button>
                  </Space>
                </Card>
              </Col>
            );
          })}
        </Row>
      )}
    </div>
  );
}
