import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Typography, Card, Row, Col, Spin, Empty, Progress, Grid, Pagination, theme } from 'antd';
import { FileTextOutlined, TeamOutlined } from '@ant-design/icons';
import axios from 'axios';
import type { Petition } from '@/types/api';

const { Title, Text, Paragraph } = Typography;
const API = '/api';

export default function PetitionsListPage() {
  const [petitions, setPetitions] = useState<Petition[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const { token } = theme.useToken();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  useEffect(() => {
    setLoading(true);
    axios.get(`${API}/petitions/public`, { params: { page, limit: 20 } })
      .then(({ data }) => {
        setPetitions(data.petitions);
        setTotal(data.pagination.total);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [page]);

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

  return (
    <div style={{ maxWidth: 900, margin: '0 auto', padding: isMobile ? '16px 12px' : '32px 16px' }}>
      <Title level={2} style={{ textAlign: 'center', marginBottom: 8 }}>
        <FileTextOutlined style={{ marginRight: 8 }} />Petitions
      </Title>
      <Text type="secondary" style={{ display: 'block', textAlign: 'center', marginBottom: 32 }}>
        Add your voice to causes that matter
      </Text>

      <Row gutter={[16, 16]}>
        {petitions.map(petition => {
          const signatureCount = petition._count.signatures + petition.signatureCountOffset;
          const hasGoal = petition.signatureGoal && petition.signatureGoal > 0;
          const pct = hasGoal ? Math.min(100, Math.round((signatureCount / petition.signatureGoal!) * 100)) : null;

          return (
            <Col xs={24} sm={12} key={petition.id}>
              <Link to={`/petition/${petition.slug}`} style={{ textDecoration: 'none' }}>
                <Card
                  hoverable
                  cover={petition.coverPhoto ? (
                    <img alt={petition.title} src={petition.coverPhoto} style={{ height: 160, objectFit: 'cover' }} />
                  ) : undefined}
                  style={{ height: '100%', background: token.colorBgContainer, borderColor: token.colorBorder }}
                >
                  <Title level={4} style={{ marginBottom: 8, color: token.colorText }}>{petition.title}</Title>
                  {petition.description && (
                    <Paragraph type="secondary" ellipsis={{ rows: 2 }} style={{ marginBottom: 12 }}>
                      {petition.description}
                    </Paragraph>
                  )}

                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: hasGoal ? 8 : 0 }}>
                    <TeamOutlined style={{ color: token.colorPrimary }} />
                    <Text strong style={{ color: token.colorPrimary }}>
                      {signatureCount.toLocaleString()} signature{signatureCount !== 1 ? 's' : ''}
                    </Text>
                    {hasGoal && (
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        of {petition.signatureGoal!.toLocaleString()} goal
                      </Text>
                    )}
                  </div>

                  {hasGoal && (
                    <Progress percent={pct!} size="small" showInfo={false} strokeColor={token.colorPrimary} />
                  )}
                </Card>
              </Link>
            </Col>
          );
        })}
      </Row>

      {total > 20 && (
        <div style={{ textAlign: 'center', marginTop: 32 }}>
          <Pagination
            current={page}
            total={total}
            pageSize={20}
            onChange={(p) => { setPage(p); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
            showSizeChanger={false}
          />
        </div>
      )}
    </div>
  );
}
