import { useState, useEffect } from 'react';
import { Drawer, Card, Row, Col, Typography, Tag, Spin, Empty, Input, Button, Grid } from 'antd';
import { ShoppingCartOutlined, SearchOutlined, CheckCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import type { Product, ProductType } from '@/types/api';

const { Text, Paragraph } = Typography;

export interface ProductInsertResult {
  product: Product;
}

interface ProductInsertModalProps {
  open: boolean;
  onClose: () => void;
  onInsert: (result: ProductInsertResult) => void;
}

const typeColors: Record<ProductType, string> = {
  DIGITAL: '#1890ff',
  EVENT: '#52c41a',
  DONATION: '#722ed1',
};

export function ProductInsertModal({ open, onClose, onInsert }: ProductInsertModalProps) {
  const [products, setProducts] = useState<Product[]>([]);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [search, setSearch] = useState('');

  useEffect(() => {
    if (open && products.length === 0) {
      setLoading(true);
      setError(null);
      axios.get('/api/payments/products', { params: { limit: 50 } })
        .then(({ data }) => setProducts(data.products))
        .catch(() => setError('Failed to load products'))
        .finally(() => setLoading(false));
    }
    if (open) {
      setSelectedId(null);
      setSearch('');
    }
  }, [open]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleOk = () => {
    const product = products.find(p => p.id === selectedId);
    if (!product) return;
    onInsert({ product });
    onClose();
  };

  const filtered = products.filter(p => {
    if (!search) return true;
    const q = search.toLowerCase();
    return p.title.toLowerCase().includes(q) || p.slug.toLowerCase().includes(q) || p.type.toLowerCase().includes(q);
  });

  return (
    <Drawer
      title="Insert Product Card"
      open={open}
      onClose={onClose}
      width={isMobile ? '95vw' : 640}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      extra={
        <Button type="primary" onClick={handleOk} disabled={!selectedId}>
          Insert
        </Button>
      }
    >
      <Paragraph type="secondary" style={{ marginBottom: 12 }}>
        Select a product to embed as an inline purchase card.
      </Paragraph>

      <Input
        prefix={<SearchOutlined />}
        placeholder="Search products..."
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        style={{ marginBottom: 16 }}
        allowClear
      />

      {loading && <Spin style={{ display: 'block', margin: '40px auto' }} />}
      {error && <Text type="danger">{error}</Text>}

      {!loading && !error && filtered.length === 0 && (
        <Empty
          description={products.length === 0 ? 'No products found. Create products in the Payments section first.' : 'No products match your search.'}
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      )}

      <div style={{ maxHeight: 400, overflowY: 'auto' }}>
        <Row gutter={[12, 12]}>
          {filtered.map((product) => {
            const isSelected = selectedId === product.id;
            const isSoldOut = product.maxPurchases !== null && product.purchaseCount >= (product.maxPurchases ?? 0);
            return (
              <Col xs={24} sm={12} key={product.id}>
                <Card
                  size="small"
                  hoverable
                  onClick={() => setSelectedId(product.id)}
                  style={{
                    border: isSelected ? '2px solid #722ed1' : '1px solid #303030',
                    background: isSelected ? 'rgba(114,46,209,0.08)' : undefined,
                    cursor: 'pointer',
                    position: 'relative',
                  }}
                >
                  {isSelected && (
                    <CheckCircleOutlined style={{ position: 'absolute', top: 8, right: 8, color: '#722ed1', fontSize: 18 }} />
                  )}
                  <div style={{ display: 'flex', gap: 12 }}>
                    <div style={{
                      width: 56,
                      height: 56,
                      borderRadius: 8,
                      background: product.imageUrl
                        ? `url(${product.imageUrl}) center/cover no-repeat`
                        : 'linear-gradient(135deg, #9d4edd, #722ed1)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      flexShrink: 0,
                    }}>
                      {!product.imageUrl && <ShoppingCartOutlined style={{ color: '#fff', fontSize: 22 }} />}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 2 }}>
                        <Tag color={typeColors[product.type]} style={{ margin: 0, fontSize: 10 }}>{product.type}</Tag>
                        {isSoldOut && <Tag color="red" style={{ margin: 0, fontSize: 10 }}>Sold Out</Tag>}
                      </div>
                      <Text strong ellipsis style={{ display: 'block' }}>{product.title}</Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>${(product.priceCAD / 100).toFixed(2)}</Text>
                      {product.description && (
                        <Paragraph type="secondary" ellipsis={{ rows: 1 }} style={{ fontSize: 11, margin: '2px 0 0' }}>
                          {product.description}
                        </Paragraph>
                      )}
                    </div>
                  </div>
                </Card>
              </Col>
            );
          })}
        </Row>
      </div>
    </Drawer>
  );
}
