import { useState, useEffect, useCallback } from 'react';
import {
  Modal,
  Radio,
  InputNumber,
  Switch,
  Select,
  Typography,
  Space,
  Input,
  Spin,
  Empty,
  Row,
  Col,
  Card,
  theme,
  Grid,
} from 'antd';
import {
  PictureOutlined,
  AppstoreOutlined,
  BlockOutlined,
  SlidersOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { mediaApi } from '../../lib/media-api';

const { Text, Paragraph } = Typography;

export type PhotoInsertVariant = 'single-photo' | 'photo-card' | 'album-grid' | 'album-carousel';

export interface PhotoInsertResult {
  variant: PhotoInsertVariant;
  album?: { id: number; title: string; photoCount: number };
  options: {
    size?: string;
    alignment?: string;
    linkToGallery?: boolean;
    columns?: number;
    maxPhotos?: number;
    showTitle?: boolean;
    autoPlay?: boolean;
  };
}

interface Album {
  id: number;
  title: string;
  photoCount: number;
  coverThumbnailUrl: string | null;
}

interface PhotoInsertModalProps {
  open: boolean;
  onClose: () => void;
  onInsert: (result: PhotoInsertResult) => void;
}

export function PhotoInsertModal({ open, onClose, onInsert }: PhotoInsertModalProps) {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { token } = theme.useToken();

  // Step: 'variant' = pick variant + options, 'album' = pick album
  const [step, setStep] = useState<'variant' | 'album'>('variant');
  const [variant, setVariant] = useState<PhotoInsertVariant>('single-photo');

  // Options for single-photo
  const [size, setSize] = useState<string>('large');
  const [alignment, setAlignment] = useState<string>('center');
  const [linkToGallery, setLinkToGallery] = useState(true);

  // Options for album-grid
  const [columns, setColumns] = useState<number>(3);
  const [maxPhotos, setMaxPhotos] = useState<number>(12);
  const [showTitle, setShowTitle] = useState(true);

  // Options for album-carousel
  const [carouselMaxPhotos, setCarouselMaxPhotos] = useState<number>(20);
  const [carouselShowTitle, setCarouselShowTitle] = useState(true);
  const [autoPlay, setAutoPlay] = useState(false);

  // Album picker state
  const [albums, setAlbums] = useState<Album[]>([]);
  const [albumsTotal, setAlbumsTotal] = useState(0);
  const [albumsLoading, setAlbumsLoading] = useState(false);
  const [albumSearch, setAlbumSearch] = useState('');
  const [selectedAlbum, setSelectedAlbum] = useState<Album | null>(null);

  // Reset when modal opens
  useEffect(() => {
    if (open) {
      setStep('variant');
      setVariant('single-photo');
      setSize('large');
      setAlignment('center');
      setLinkToGallery(true);
      setColumns(3);
      setMaxPhotos(12);
      setShowTitle(true);
      setCarouselMaxPhotos(20);
      setCarouselShowTitle(true);
      setAutoPlay(false);
      setAlbumSearch('');
      setSelectedAlbum(null);
    }
  }, [open]);

  // Fetch albums when album step is shown
  const fetchAlbums = useCallback(async (search?: string) => {
    setAlbumsLoading(true);
    try {
      const params = new URLSearchParams({ limit: '48' });
      if (search) params.append('search', search);
      const res = await mediaApi.get(`/albums?${params.toString()}`);
      setAlbums(res.data.albums || []);
      setAlbumsTotal(res.data.total || 0);
    } catch {
      console.error('Failed to fetch albums');
      setAlbums([]);
    } finally {
      setAlbumsLoading(false);
    }
  }, []);

  useEffect(() => {
    if (step === 'album') {
      fetchAlbums(albumSearch || undefined);
    }
  }, [step, albumSearch, fetchAlbums]);

  const isAlbumVariant = variant === 'album-grid' || variant === 'album-carousel';

  const handleOk = () => {
    if (step === 'variant') {
      if (isAlbumVariant) {
        // Go to album picker step
        setStep('album');
        return;
      }
      // Photo variants — return result, DocsPage will open PhotoPickerModal
      const result: PhotoInsertResult = {
        variant,
        options: variant === 'single-photo'
          ? { size, alignment, linkToGallery }
          : {},
      };
      onInsert(result);
      onClose();
    } else {
      // Album step — submit with selected album
      if (!selectedAlbum) return;
      const options = variant === 'album-grid'
        ? { columns, maxPhotos, showTitle }
        : { maxPhotos: carouselMaxPhotos, showTitle: carouselShowTitle, autoPlay };
      const result: PhotoInsertResult = {
        variant,
        album: {
          id: selectedAlbum.id,
          title: selectedAlbum.title,
          photoCount: selectedAlbum.photoCount,
        },
        options,
      };
      onInsert(result);
      onClose();
    }
  };

  const handleBack = () => {
    setStep('variant');
    setSelectedAlbum(null);
  };

  const cardStyle = (selected: boolean) => ({
    padding: '16px',
    borderRadius: 8,
    border: `2px solid ${selected ? token.colorPrimary : token.colorBorderSecondary}`,
    background: selected ? token.colorPrimaryBg : token.colorBgContainer,
    cursor: 'pointer',
    transition: 'all 0.2s',
  });

  const mediaThumbnailBase = '/media';

  const okDisabled = step === 'album' && !selectedAlbum;

  return (
    <Modal
      title={step === 'variant' ? 'Insert Photo Block' : 'Select Album'}
      open={open}
      onCancel={step === 'album' ? handleBack : onClose}
      onOk={handleOk}
      okText={step === 'variant' && isAlbumVariant ? 'Next' : 'Insert'}
      okButtonProps={{ disabled: okDisabled }}
      cancelText={step === 'album' ? 'Back' : 'Cancel'}
      width={isMobile ? '95vw' : step === 'album' ? 700 : 560}
      afterClose={() => setStep('variant')}
    >
      {step === 'variant' ? (
        <>
          <Paragraph type="secondary" style={{ marginBottom: 16 }}>
            Choose a photo block style to insert into your document.
          </Paragraph>

          <Radio.Group
            value={variant}
            onChange={(e) => setVariant(e.target.value)}
            style={{ width: '100%' }}
          >
            <Space direction="vertical" style={{ width: '100%' }} size={12}>
              {/* Single Photo */}
              <div style={cardStyle(variant === 'single-photo')} onClick={() => setVariant('single-photo')}>
                <Radio value="single-photo">
                  <Space>
                    <PictureOutlined style={{ fontSize: 18, color: '#43cea2' }} />
                    <div>
                      <Text strong>Single Photo</Text>
                      <br />
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        A standalone image with optional caption and gallery link
                      </Text>
                    </div>
                  </Space>
                </Radio>
                {variant === 'single-photo' && (
                  <div style={{ marginTop: 12, marginLeft: 32, display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
                    <div>
                      <Text style={{ fontSize: 12, marginRight: 6 }}>Size:</Text>
                      <Select size="small" value={size} onChange={setSize} style={{ width: 100 }}>
                        <Select.Option value="small">Small</Select.Option>
                        <Select.Option value="medium">Medium</Select.Option>
                        <Select.Option value="large">Large</Select.Option>
                      </Select>
                    </div>
                    <div>
                      <Text style={{ fontSize: 12, marginRight: 6 }}>Align:</Text>
                      <Select size="small" value={alignment} onChange={setAlignment} style={{ width: 90 }}>
                        <Select.Option value="left">Left</Select.Option>
                        <Select.Option value="center">Center</Select.Option>
                        <Select.Option value="right">Right</Select.Option>
                      </Select>
                    </div>
                    <div>
                      <Text style={{ fontSize: 12, marginRight: 6 }}>Gallery link:</Text>
                      <Switch size="small" checked={linkToGallery} onChange={setLinkToGallery} />
                    </div>
                  </div>
                )}
              </div>

              {/* Photo Card */}
              <div style={cardStyle(variant === 'photo-card')} onClick={() => setVariant('photo-card')}>
                <Radio value="photo-card">
                  <Space>
                    <BlockOutlined style={{ fontSize: 18, color: '#185a9d' }} />
                    <div>
                      <Text strong>Photo Card</Text>
                      <br />
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        A styled card with title, metadata, and gallery link
                      </Text>
                    </div>
                  </Space>
                </Radio>
              </div>

              {/* Album Grid */}
              <div style={cardStyle(variant === 'album-grid')} onClick={() => setVariant('album-grid')}>
                <Radio value="album-grid">
                  <Space>
                    <AppstoreOutlined style={{ fontSize: 18, color: '#722ed1' }} />
                    <div>
                      <Text strong>Album Grid</Text>
                      <br />
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        A responsive grid of album thumbnails
                      </Text>
                    </div>
                  </Space>
                </Radio>
                {variant === 'album-grid' && (
                  <div style={{ marginTop: 12, marginLeft: 32, display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
                    <div>
                      <Text style={{ fontSize: 12, marginRight: 6 }}>Columns:</Text>
                      <Select size="small" value={columns} onChange={setColumns} style={{ width: 70 }}>
                        <Select.Option value={2}>2</Select.Option>
                        <Select.Option value={3}>3</Select.Option>
                        <Select.Option value={4}>4</Select.Option>
                      </Select>
                    </div>
                    <div>
                      <Text style={{ fontSize: 12, marginRight: 6 }}>Max photos:</Text>
                      <InputNumber size="small" min={1} max={50} value={maxPhotos} onChange={(v) => setMaxPhotos(v || 12)} style={{ width: 70 }} />
                    </div>
                    <div>
                      <Text style={{ fontSize: 12, marginRight: 6 }}>Show title:</Text>
                      <Switch size="small" checked={showTitle} onChange={setShowTitle} />
                    </div>
                  </div>
                )}
              </div>

              {/* Album Carousel */}
              <div style={cardStyle(variant === 'album-carousel')} onClick={() => setVariant('album-carousel')}>
                <Radio value="album-carousel">
                  <Space>
                    <SlidersOutlined style={{ fontSize: 18, color: '#eb2f96' }} />
                    <div>
                      <Text strong>Album Carousel</Text>
                      <br />
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        A slideshow with navigation arrows, dots, and swipe support
                      </Text>
                    </div>
                  </Space>
                </Radio>
                {variant === 'album-carousel' && (
                  <div style={{ marginTop: 12, marginLeft: 32, display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
                    <div>
                      <Text style={{ fontSize: 12, marginRight: 6 }}>Max photos:</Text>
                      <InputNumber size="small" min={1} max={50} value={carouselMaxPhotos} onChange={(v) => setCarouselMaxPhotos(v || 20)} style={{ width: 70 }} />
                    </div>
                    <div>
                      <Text style={{ fontSize: 12, marginRight: 6 }}>Show title:</Text>
                      <Switch size="small" checked={carouselShowTitle} onChange={setCarouselShowTitle} />
                    </div>
                    <div>
                      <Text style={{ fontSize: 12, marginRight: 6 }}>Auto-play:</Text>
                      <Switch size="small" checked={autoPlay} onChange={setAutoPlay} />
                    </div>
                  </div>
                )}
              </div>
            </Space>
          </Radio.Group>
        </>
      ) : (
        /* Album picker step */
        <>
          <Input
            placeholder="Search albums..."
            prefix={<SearchOutlined />}
            value={albumSearch}
            onChange={(e) => setAlbumSearch(e.target.value)}
            allowClear
            style={{ marginBottom: 16 }}
          />

          {albumsLoading ? (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <Spin size="large" />
            </div>
          ) : albums.length === 0 ? (
            <Empty
              description={albumSearch ? 'No albums match your search' : 'No albums found'}
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              style={{ padding: 40 }}
            >
              <Text type="secondary" style={{ fontSize: 12 }}>
                Create albums in the Media Library first.
              </Text>
            </Empty>
          ) : (
            <>
              <Row gutter={[12, 12]}>
                {albums.map((album) => {
                  const isSelected = selectedAlbum?.id === album.id;
                  return (
                    <Col key={album.id} xs={12} sm={8} md={8}>
                      <Card
                        hoverable
                        cover={
                          <div
                            style={{
                              position: 'relative',
                              paddingBottom: '66.67%',
                              background: '#f0f0f0',
                              overflow: 'hidden',
                            }}
                          >
                            {album.coverThumbnailUrl ? (
                              <img
                                src={`${mediaThumbnailBase}${album.coverThumbnailUrl}`}
                                alt={album.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%)',
                                }}
                              >
                                <AppstoreOutlined style={{ fontSize: 32, color: '#999' }} />
                              </div>
                            )}
                          </div>
                        }
                        onClick={() => setSelectedAlbum(album)}
                        style={{
                          border: isSelected ? '2px solid #52c41a' : undefined,
                        }}
                      >
                        <Card.Meta
                          title={
                            <div
                              style={{
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap',
                                fontSize: 13,
                              }}
                            >
                              {album.title}
                            </div>
                          }
                          description={
                            <Text type="secondary" style={{ fontSize: 11 }}>
                              {album.photoCount} photo{album.photoCount !== 1 ? 's' : ''}
                            </Text>
                          }
                        />
                      </Card>
                    </Col>
                  );
                })}
              </Row>
              {albumsTotal > albums.length && (
                <Text type="secondary" style={{ display: 'block', textAlign: 'center', marginTop: 12, fontSize: 12 }}>
                  Showing {albums.length} of {albumsTotal} albums. Use search to find more.
                </Text>
              )}
            </>
          )}
        </>
      )}
    </Modal>
  );
}
