import { useState, useEffect } from 'react';
import { Modal, Tabs, Table, Button, Segmented, Typography, Spin } from 'antd';
import { api } from '@/lib/api';
import type { GalleryAd, AdVariant } from '@/types/gallery-ads';
import { AD_TYPE_LABELS } from '@/types/gallery-ads';

const { Text } = Typography;

export interface AdInsertResult {
  type: 'specific' | 'slot';
  adId?: number;
  adTitle?: string;
  variant?: string;
}

interface AdPickerModalProps {
  open: boolean;
  onCancel: () => void;
  onInsert: (result: AdInsertResult) => void;
}

export function AdPickerModal({ open, onCancel, onInsert }: AdPickerModalProps) {
  const [ads, setAds] = useState<GalleryAd[]>([]);
  const [loading, setLoading] = useState(false);
  const [slotVariant, setSlotVariant] = useState<AdVariant>('standard');

  useEffect(() => {
    if (!open) return;
    setLoading(true);
    api.get('/gallery-ads/admin', { params: { limit: 100, isActive: 'true' } })
      .then(({ data }) => setAds(data.ads || []))
      .catch(() => setAds([]))
      .finally(() => setLoading(false));
  }, [open]);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
    },
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => AD_TYPE_LABELS[type as keyof typeof AD_TYPE_LABELS] || type,
    },
    {
      title: 'Variant',
      dataIndex: 'variant',
      key: 'variant',
      width: 100,
    },
    {
      title: '',
      key: 'action',
      width: 80,
      render: (_: unknown, record: GalleryAd) => (
        <Button
          type="primary"
          size="small"
          onClick={() => onInsert({ type: 'specific', adId: record.id, adTitle: record.title })}
        >
          Insert
        </Button>
      ),
    },
  ];

  return (
    <Modal
      open={open}
      onCancel={onCancel}
      title="Insert Ad"
      footer={null}
      width={640}
    >
      <Tabs
        items={[
          {
            key: 'specific',
            label: 'Specific Ad',
            children: loading ? (
              <div style={{ textAlign: 'center', padding: 32 }}><Spin /></div>
            ) : (
              <Table
                dataSource={ads}
                columns={columns}
                rowKey="id"
                size="small"
                pagination={false}
                scroll={{ y: 300 }}
              />
            ),
          },
          {
            key: 'slot',
            label: 'Ad Slot (Dynamic)',
            children: (
              <div style={{ padding: '16px 0' }}>
                <Text style={{ display: 'block', marginBottom: 12 }}>
                  Inserts a dynamic ad slot that rotates between active ads targeted to documentation pages.
                </Text>
                <Text strong style={{ display: 'block', marginBottom: 8 }}>Variant:</Text>
                <Segmented
                  value={slotVariant}
                  onChange={(v) => setSlotVariant(v as AdVariant)}
                  options={[
                    { label: 'Standard', value: 'standard' },
                    { label: 'Highlight', value: 'highlight' },
                    { label: 'Minimal', value: 'minimal' },
                  ]}
                  style={{ marginBottom: 16 }}
                />
                <Button
                  type="primary"
                  onClick={() => onInsert({ type: 'slot', variant: slotVariant })}
                >
                  Insert Ad Slot
                </Button>
              </div>
            ),
          },
        ]}
      />
    </Modal>
  );
}
