import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Typography, Card, Row, Col, Spin, Result, Button, Progress, Grid, theme } from 'antd';
import { HeartOutlined, StarFilled, TeamOutlined, DollarOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useSettingsStore } from '@/stores/settings.store';
import type { DonationPage } from '@/types/api';

const { Title, Text, Paragraph } = Typography;

export default function DonationPagesListPage() {
  const [pages, setPages] = useState<DonationPage[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const { token } = theme.useToken();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { settings: siteSettings } = useSettingsStore();

  const colorBgContainer = token.colorBgContainer;

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

  useEffect(() => {
    axios.get<DonationPage[]>('/api/donation-pages')
      .then(({ data }) => setPages(data))
      .catch(() => setError(true))
      .finally(() => setLoading(false));
  }, []);

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

  if (error) {
    return (
      <Result
        status="500"
        title="Failed to Load"
        subTitle="There was an error loading donation pages."
        extra={<Button type="primary" onClick={() => window.location.reload()}>Retry</Button>}
      />
    );
  }

  if (pages.length === 0) {
    return (
      <div style={{ textAlign: 'center', padding: 60 }}>
        <HeartOutlined style={{ fontSize: 48, color: '#eb2f96', marginBottom: 16 }} />
        <Title level={3} style={{ color: '#fff' }}>No Donation Pages Available</Title>
        <Text style={{ color: 'rgba(255,255,255,0.55)' }}>Check back later for ways to support our work.</Text>
      </div>
    );
  }

  const featured = pages.filter(p => p.highlightPage);
  const nonFeatured = pages.filter(p => !p.highlightPage);

  return (
    <div>
      {/* Hero */}
      <div style={{ textAlign: 'center', marginBottom: 32, padding: isMobile ? '24px 0' : '32px 0' }}>
        <HeartOutlined style={{ fontSize: 48, color: '#eb2f96', marginBottom: 16 }} />
        <Title level={2} style={{ color: '#fff', margin: 0 }}>
          Support Our Work
        </Title>
        <Paragraph style={{ color: 'rgba(255,255,255,0.65)', fontSize: 16, margin: '12px 0 0' }}>
          Choose a campaign to support
        </Paragraph>
      </div>

      {/* Featured */}
      {featured.map((page) => (
        <Link to={`/donate/${page.slug}`} key={page.id} style={{ display: 'block', marginBottom: 24 }}>
          <Card
            hoverable
            style={{
              background: `linear-gradient(135deg, ${colorBgContainer} 0%, ${token.colorPrimaryBg} 100%)`,
              border: '1px solid rgba(255,215,0,0.3)',
              borderRadius: 12,
              overflow: 'hidden',
            }}
          >
            {page.coverPhoto && (
              <div style={{
                height: 180,
                margin: '-24px -24px 16px -24px',
                backgroundImage: `url(${page.coverPhoto})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
              }} />
            )}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <StarFilled style={{ color: '#ffd700', fontSize: 16 }} />
              <Text style={{ color: '#ffd700', fontWeight: 600, fontSize: 12 }}>FEATURED</Text>
            </div>
            <Title level={3} style={{ color: '#fff', margin: '4px 0 8px' }}>{page.title}</Title>
            {page.description && (
              <Paragraph style={{ color: 'rgba(255,255,255,0.7)', margin: '0 0 12px', fontSize: isMobile ? 15 : 14 }} ellipsis={{ rows: 2 }}>
                {page.description}
              </Paragraph>
            )}
            <PageStats page={page} token={token} />
          </Card>
        </Link>
      ))}

      {/* Grid */}
      {nonFeatured.length > 0 && (
        <Row gutter={[20, 20]}>
          {nonFeatured.map((page) => (
            <Col xs={24} sm={12} lg={8} key={page.id}>
              <Link to={`/donate/${page.slug}`} style={{ display: 'block', height: '100%' }}>
                <Card
                  hoverable
                  style={{
                    height: '100%',
                    background: colorBgContainer,
                    border: '1px solid rgba(255,255,255,0.08)',
                    borderRadius: 10,
                    overflow: 'hidden',
                  }}
                  styles={{ body: { padding: 0, display: 'flex', flexDirection: 'column', height: '100%' } }}
                >
                  {page.coverPhoto ? (
                    <div style={{
                      height: 140,
                      backgroundImage: `url(${page.coverPhoto})`,
                      backgroundSize: 'cover',
                      backgroundPosition: 'center',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}>
                      <Title level={4} style={{ color: '#fff', margin: 0, textShadow: '0 2px 8px rgba(0,0,0,0.6)', textAlign: 'center', padding: '0 16px' }} ellipsis={{ rows: 2 }}>
                        {page.title}
                      </Title>
                    </div>
                  ) : (
                    <div style={{
                      height: 140,
                      background: `linear-gradient(135deg, ${token.colorPrimaryBg} 0%, ${colorBgContainer} 100%)`,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}>
                      <HeartOutlined style={{ fontSize: 32, color: '#eb2f96', marginRight: 12 }} />
                      <Title level={4} style={{ color: '#fff', margin: 0, textAlign: 'center' }} ellipsis={{ rows: 2 }}>
                        {page.title}
                      </Title>
                    </div>
                  )}
                  <div style={{ padding: 20, flex: 1 }}>
                    {page.description && (
                      <Paragraph
                        style={{ color: 'rgba(255,255,255,0.55)', fontSize: isMobile ? 14 : 13, margin: '0 0 12px', lineHeight: 1.5 }}
                        ellipsis={{ rows: 2 }}
                      >
                        {page.description}
                      </Paragraph>
                    )}
                    <PageStats page={page} token={token} />
                  </div>
                  <div style={{ borderTop: '1px solid rgba(255,255,255,0.06)', padding: '12px 20px', textAlign: 'center' }}>
                    <Button type="primary" icon={<HeartOutlined />} block>
                      Donate
                    </Button>
                  </div>
                </Card>
              </Link>
            </Col>
          ))}
        </Row>
      )}
    </div>
  );
}

function PageStats({ page, token }: { page: DonationPage; token: ReturnType<typeof theme.useToken>['token'] }) {
  return (
    <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'center' }}>
      {page.showDonorCount && page.donorCount != null && page.donorCount > 0 && (
        <span style={{ color: token.colorPrimary, fontSize: 13 }}>
          <TeamOutlined style={{ marginRight: 4 }} />
          {page.donorCount} {page.donorCount === 1 ? 'donor' : 'donors'}
        </span>
      )}
      {page.showTotalRaised && page.totalRaised != null && page.totalRaised > 0 && (
        <span style={{ color: token.colorSuccess, fontSize: 13 }}>
          <DollarOutlined style={{ marginRight: 4 }} />
          ${(page.totalRaised / 100).toLocaleString()} raised
        </span>
      )}
      {page.goalAmount && page.totalRaised != null && (
        <div style={{ flex: 1, minWidth: 120 }}>
          <Progress
            percent={Math.min(100, Math.round((page.totalRaised / page.goalAmount) * 100))}
            size="small"
            strokeColor={token.colorPrimary}
          />
          <Text style={{ color: 'rgba(255,255,255,0.45)', fontSize: 11 }}>
            ${(page.totalRaised / 100).toLocaleString()} of ${(page.goalAmount / 100).toLocaleString()} goal
          </Text>
        </div>
      )}
    </div>
  );
}
