import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Typography, Card, Row, Col, Spin, Empty, Grid, Pagination, theme } from 'antd';
import { FileTextOutlined } from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';
import { useSettingsStore } from '@/stores/settings.store';

const { Title, Text, Paragraph } = Typography;

interface ListedPage {
  slug: string;
  title: string;
  description: string | null;
  seoImage: string | null;
  updatedAt: string;
}

export default function PagesIndexPage() {
  const [pages, setPages] = useState<ListedPage[]>([]);
  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;
  const { settings } = useSettingsStore();

  useEffect(() => {
    document.title = `Pages | ${settings?.organizationName || 'Changemaker'}`;
  }, [settings?.organizationName]);

  useEffect(() => {
    setLoading(true);
    axios.get('/api/pages/listed', { params: { page, limit: 20 } })
      .then(({ data }) => {
        setPages(data.pages);
        setTotal(data.pagination.total);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [page]);

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

  return (
    <div>
      <div
        style={{
          textAlign: 'center',
          padding: isMobile ? '32px 16px' : '48px 24px',
          marginBottom: 32,
          background: `linear-gradient(135deg, ${token.colorPrimaryBg} 0%, ${token.colorBgContainer} 100%)`,
          borderRadius: 12,
        }}
      >
        <Title level={2} style={{ color: '#fff', margin: 0 }}>
          Pages
        </Title>
        <Text style={{ color: 'rgba(255,255,255,0.7)', fontSize: 16 }}>
          Resources, information, and more
        </Text>
      </div>

      {pages.length === 0 ? (
        <Empty description={<Text style={{ color: 'rgba(255,255,255,0.45)' }}>No pages available</Text>} />
      ) : (
        <Row gutter={[20, 20]}>
          {pages.map((page) => (
            <Col xs={24} sm={12} lg={8} key={page.slug}>
              <Link to={`/p/${page.slug}`} style={{ display: 'block', height: '100%' }}>
                <Card
                  hoverable
                  style={{
                    height: '100%',
                    background: token.colorBgContainer,
                    border: '1px solid rgba(255,255,255,0.08)',
                    borderRadius: 10,
                    overflow: 'hidden',
                  }}
                  styles={{ body: { padding: 0 } }}
                >
                  {page.seoImage ? (
                    <div
                      style={{
                        height: 160,
                        backgroundImage: `url(${page.seoImage})`,
                        backgroundSize: 'cover',
                        backgroundPosition: 'center',
                      }}
                    />
                  ) : (
                    <div
                      style={{
                        height: 160,
                        background: `linear-gradient(135deg, ${token.colorPrimaryBg} 0%, ${token.colorBgContainer} 100%)`,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}
                    >
                      <FileTextOutlined style={{ fontSize: 48, color: 'rgba(255,255,255,0.2)' }} />
                    </div>
                  )}
                  <div style={{ padding: 20 }}>
                    <Title level={5} style={{ margin: '0 0 8px 0' }}>{page.title}</Title>
                    {page.description && (
                      <Paragraph
                        style={{ color: 'rgba(255,255,255,0.55)', fontSize: 13, margin: '0 0 8px' }}
                        ellipsis={{ rows: 2 }}
                      >
                        {page.description}
                      </Paragraph>
                    )}
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      Updated {dayjs(page.updatedAt).fromNow()}
                    </Text>
                  </div>
                </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>
  );
}
