import { useState, useEffect } from 'react';
import { Card, Row, Col, Button, Typography, Tag, Spin, Select, Space, Pagination, App } from 'antd';
import { ShoppingCartOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import { usePageAds } from '@/hooks/usePageAds';
import AdBanner from '@/components/AdBanner';
import type { Product, ProductType } from '@/types/api';

const { Title, Text, Paragraph } = Typography;

export default function ShopPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [typeFilter, setTypeFilter] = useState<string>();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const { user, isAuthenticated } = useAuthStore();
  const { message } = App.useApp();
  const { settings: siteSettings } = useSettingsStore();
  const navigate = useNavigate();
  const shopAds = usePageAds('shop');

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

  useEffect(() => {
    setLoading(true);
    const params: Record<string, string | number> = { page, limit: 20 };
    if (typeFilter) params.type = typeFilter;
    axios.get('/api/payments/products', { params })
      .then(({ data }) => {
        setProducts(data.products);
        setTotal(data.pagination.total);
      })
      .catch(() => message.error('Failed to load products'))
      .finally(() => setLoading(false));
  }, [typeFilter, page]); // eslint-disable-line react-hooks/exhaustive-deps

  const handlePurchase = async (e: React.MouseEvent, product: Product) => {
    e.stopPropagation(); // prevent card click navigation
    const email = isAuthenticated && user ? user.email : prompt('Enter your email to purchase:');
    if (!email) return;

    try {
      const { data } = await axios.post('/api/payments/purchase', {
        productId: product.id,
        buyerEmail: email,
        buyerName: user?.name || undefined,
      });
      if (data.url) {
        window.location.href = data.url;
      }
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data?.error?.message || 'Failed to start checkout';
      message.error(msg);
    }
  };

  const typeColors: Record<ProductType, string> = {
    DIGITAL: 'blue',
    EVENT: 'green',
    DONATION: 'purple',
  };

  const getProductImage = (product: Product): string | null => {
    return product.resolvedImageUrl || product.imageUrl || null;
  };

  if (loading) return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;

  return (
    <div>
      <Title level={2} style={{ textAlign: 'center' }}>Shop</Title>
      <Paragraph style={{ textAlign: 'center', fontSize: 16, opacity: 0.8 }}>
        Reports, toolkits, event tickets, and more
      </Paragraph>

      <AdBanner ads={shopAds} placement="shop" />

      <Space style={{ marginBottom: 24 }} wrap>
        <Select
          placeholder="Filter by type"
          allowClear
          value={typeFilter}
          onChange={(v) => { setTypeFilter(v); setPage(1); }}
          style={{ width: 200 }}
          options={[
            { value: 'DIGITAL', label: 'Digital Products' },
            { value: 'EVENT', label: 'Events' },
          ]}
        />
      </Space>

      {products.length === 0 ? (
        <Card style={{ textAlign: 'center', padding: 40 }}>
          <Title level={4}>No products available yet</Title>
          <Text type="secondary">Check back soon!</Text>
        </Card>
      ) : (
        <Row gutter={[16, 16]}>
          {products.map((product) => {
            const imgSrc = getProductImage(product);
            const isSoldOut = !!(product.maxPurchases && product.purchaseCount >= product.maxPurchases);

            return (
              <Col xs={24} sm={12} md={8} key={product.id}>
                <Card
                  hoverable
                  onClick={() => navigate(`/shop/${product.slug}`)}
                  style={{ height: '100%', display: 'flex', flexDirection: 'column', cursor: 'pointer', overflow: 'hidden' }}
                  styles={{ body: { flex: 1, display: 'flex', flexDirection: 'column' } }}
                  cover={
                    <div
                      style={{
                        position: 'relative',
                        paddingBottom: '66.67%',
                        overflow: 'hidden',
                        background: imgSrc ? undefined : 'linear-gradient(135deg, #1b2838 0%, #2a3f5f 100%)',
                      }}
                    >
                      {imgSrc ? (
                        <img
                          src={imgSrc}
                          alt={product.title}
                          style={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            width: '100%',
                            height: '100%',
                            objectFit: 'cover',
                          }}
                        />
                      ) : (
                        <div
                          style={{
                            position: 'absolute',
                            top: '50%',
                            left: '50%',
                            transform: 'translate(-50%, -50%)',
                          }}
                        >
                          <ShoppingCartOutlined style={{ fontSize: 40, opacity: 0.2, color: '#fff' }} />
                        </div>
                      )}
                      {/* Type badge overlay */}
                      <Tag
                        color={typeColors[product.type]}
                        style={{ position: 'absolute', top: 8, left: 8, margin: 0 }}
                      >
                        {product.type}
                      </Tag>
                      {/* Video indicator */}
                      {product.videoId && (
                        <div
                          style={{
                            position: 'absolute',
                            bottom: 8,
                            right: 8,
                            background: 'rgba(0,0,0,0.6)',
                            borderRadius: '50%',
                            width: 32,
                            height: 32,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                          }}
                        >
                          <PlayCircleOutlined style={{ color: '#fff', fontSize: 18 }} />
                        </div>
                      )}
                    </div>
                  }
                >
                  <Title level={4} style={{ margin: 0 }}>{product.title}</Title>
                  {product.description && (
                    <Paragraph
                      type="secondary"
                      ellipsis={{ rows: 2 }}
                      style={{ marginTop: 8 }}
                    >
                      {product.description}
                    </Paragraph>
                  )}
                  <div style={{ marginTop: 'auto', paddingTop: 16 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Text strong style={{ fontSize: 20 }}>${(product.priceCAD / 100).toFixed(2)}</Text>
                      {isSoldOut ? (
                        <Tag color="red">Sold Out</Tag>
                      ) : (
                        <Button
                          type="primary"
                          icon={<ShoppingCartOutlined />}
                          onClick={(e) => handlePurchase(e, product)}
                        >
                          Buy
                        </Button>
                      )}
                    </div>
                  </div>
                </Card>
              </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>
  );
}
