import React, { useState, useEffect } from 'react';
import {
  Modal,
  Tabs,
  Input,
  Select,
  Row,
  Col,
  Card,
  Pagination,
  Empty,
  Spin,
  Button,
  Tag,
  message,
  Grid,
} from 'antd';
import {
  SearchOutlined,
  PictureOutlined,
  CheckCircleOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { mediaApi } from '../../lib/media-api';

const { TabPane } = Tabs;
const { Option } = Select;

export interface Photo {
  id: number;
  title: string | null;
  originalFilename: string | null;
  format: string | null;
  width: number | null;
  height: number | null;
  orientation: string | null;
  producer: string | null;
  description: string | null;
  thumbnailPath: string | null;
  thumbnailUrl: string | null;
  isPublished: boolean;
  viewCount: number;
  createdAt: string;
}

export interface PhotoPickerModalProps {
  open: boolean;
  onClose: () => void;
  onSelect: (photo: Photo) => void;
  mode?: 'single' | 'multiple';
  title?: string;
}

function formatDimensions(w: number | null, h: number | null): string {
  if (!w || !h) return '';
  return `${w}\u00D7${h}`;
}

/**
 * Photo Picker Modal with Library and Upload tabs.
 * Mirrors VideoPickerModal with photo-specific fields and filters.
 */
export const PhotoPickerModal: React.FC<PhotoPickerModalProps> = ({
  open,
  onClose,
  onSelect,
  mode = 'single',
  title = 'Select Photo',
}) => {
  const [activeTab, setActiveTab] = useState('library');
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [loading, setLoading] = useState(false);
  const [photos, setPhotos] = useState<Photo[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(12);
  const [search, setSearch] = useState('');
  const [format, setFormat] = useState<string>('');
  const [orientation, setOrientation] = useState<string>('');
  const [selectedPhotos, setSelectedPhotos] = useState<Set<number>>(new Set());

  useEffect(() => {
    if (open && activeTab === 'library') {
      fetchPhotos();
    }
  }, [open, activeTab, page, search, format, orientation]);

  const fetchPhotos = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        limit: pageSize.toString(),
        offset: ((page - 1) * pageSize).toString(),
      });

      if (search) params.append('search', search);
      if (format) params.append('format', format);
      if (orientation) params.append('orientation', orientation);

      const response = await mediaApi.get(`/photos?${params.toString()}`);
      setPhotos(response.data.photos || []);
      setTotal(response.data.total || 0);
    } catch (error) {
      console.error('Failed to fetch photos:', error);
      message.error('Failed to load photos');
    } finally {
      setLoading(false);
    }
  };

  const handlePhotoClick = (photo: Photo) => {
    if (mode === 'single') {
      onSelect(photo);
      onClose();
    } else {
      setSelectedPhotos((prev) => {
        const newSet = new Set(prev);
        if (newSet.has(photo.id)) {
          newSet.delete(photo.id);
        } else {
          newSet.add(photo.id);
        }
        return newSet;
      });
    }
  };

  const handleSelectMultiple = () => {
    if (selectedPhotos.size === 0) {
      message.warning('Please select at least one photo');
      return;
    }

    const selected = photos.filter((p) => selectedPhotos.has(p.id));
    selected.forEach((photo) => onSelect(photo));
    onClose();
  };

  const handleFilterReset = () => {
    setSearch('');
    setFormat('');
    setOrientation('');
    setPage(1);
  };

  // Use Vite proxy path for browser-facing URLs (img src, etc.)
  const mediaThumbnailBase = '/media';

  return (
    <Modal
      open={open}
      onCancel={onClose}
      title={title}
      width={isMobile ? '95vw' : 900}
      footer={
        mode === 'multiple' && activeTab === 'library' ? (
          <div>
            <Button onClick={onClose}>Cancel</Button>
            <Button
              type="primary"
              onClick={handleSelectMultiple}
              disabled={selectedPhotos.size === 0}
            >
              Select ({selectedPhotos.size})
            </Button>
          </div>
        ) : null
      }
    >
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane
          tab={
            <span>
              <PictureOutlined />
              Library
            </span>
          }
          key="library"
        >
          {/* Filters */}
          <Row gutter={[12, 12]} style={{ marginBottom: 16 }}>
            <Col span={12}>
              <Input
                placeholder="Search photos..."
                prefix={<SearchOutlined />}
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setPage(1);
                }}
                allowClear
              />
            </Col>
            <Col span={6}>
              <Select
                placeholder="Format"
                value={format || undefined}
                onChange={(value) => {
                  setFormat(value || '');
                  setPage(1);
                }}
                style={{ width: '100%' }}
                allowClear
              >
                <Option value="jpeg">JPEG</Option>
                <Option value="png">PNG</Option>
                <Option value="webp">WebP</Option>
                <Option value="gif">GIF</Option>
              </Select>
            </Col>
            <Col span={6}>
              <Select
                placeholder="Orientation"
                value={orientation || undefined}
                onChange={(value) => {
                  setOrientation(value || '');
                  setPage(1);
                }}
                style={{ width: '100%' }}
                allowClear
              >
                <Option value="H">Horizontal</Option>
                <Option value="V">Vertical</Option>
                <Option value="S">Square</Option>
              </Select>
            </Col>
          </Row>

          {/* Photo Grid */}
          {loading ? (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <Spin size="large" />
            </div>
          ) : photos.length === 0 ? (
            <Empty description="No photos found" style={{ padding: 40 }}>
              <Button onClick={handleFilterReset}>Reset Filters</Button>
            </Empty>
          ) : (
            <>
              <Row gutter={[12, 12]}>
                {photos.map((photo) => {
                  const isSelected = selectedPhotos.has(photo.id);
                  const dims = formatDimensions(photo.width, photo.height);
                  return (
                    <Col key={photo.id} span={6}>
                      <Card
                        hoverable
                        cover={
                          <div
                            style={{
                              position: 'relative',
                              paddingBottom: '66.67%',
                              background: '#f0f0f0',
                              overflow: 'hidden',
                            }}
                          >
                            {photo.thumbnailPath ? (
                              <img
                                src={`${mediaThumbnailBase}/photos/${photo.id}/thumbnail`}
                                alt={photo.title || photo.originalFilename || 'Photo'}
                                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%)',
                                }}
                              >
                                <PictureOutlined style={{ fontSize: 32, color: '#999' }} />
                              </div>
                            )}
                            {isSelected && (
                              <div
                                style={{
                                  position: 'absolute',
                                  top: 8,
                                  right: 8,
                                  background: '#52c41a',
                                  borderRadius: '50%',
                                  padding: 4,
                                }}
                              >
                                <CheckCircleOutlined style={{ color: '#fff', fontSize: 16 }} />
                              </div>
                            )}
                            {photo.format && (
                              <Tag
                                style={{
                                  position: 'absolute',
                                  top: 8,
                                  left: 8,
                                  margin: 0,
                                }}
                              >
                                {photo.format.toUpperCase()}
                              </Tag>
                            )}
                            {dims && (
                              <Tag
                                style={{
                                  position: 'absolute',
                                  bottom: 8,
                                  right: 8,
                                  margin: 0,
                                }}
                              >
                                {dims}
                              </Tag>
                            )}
                          </div>
                        }
                        onClick={() => handlePhotoClick(photo)}
                        style={{
                          border: isSelected ? '2px solid #52c41a' : undefined,
                        }}
                      >
                        <Card.Meta
                          title={
                            <div
                              style={{
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap',
                                fontSize: 13,
                              }}
                            >
                              {photo.title || photo.originalFilename || 'Untitled'}
                            </div>
                          }
                          description={
                            <div style={{ fontSize: 11, color: '#999' }}>
                              {photo.orientation === 'H' ? 'Horizontal' : photo.orientation === 'V' ? 'Vertical' : photo.orientation === 'S' ? 'Square' : ''}
                              {photo.producer && ` \u2022 ${photo.producer}`}
                            </div>
                          }
                        />
                      </Card>
                    </Col>
                  );
                })}
              </Row>

              {/* Pagination */}
              <div style={{ marginTop: 16, textAlign: 'center' }}>
                <Pagination
                  current={page}
                  pageSize={pageSize}
                  total={total}
                  onChange={(newPage) => setPage(newPage)}
                  showSizeChanger={false}
                  showTotal={(total) => `Total ${total} photos`}
                />
              </div>
            </>
          )}
        </TabPane>

        <TabPane
          tab={
            <span>
              <UploadOutlined />
              Upload
            </span>
          }
          key="upload"
        >
          <div style={{ padding: '20px 0' }}>
            <Empty
              description="Upload feature integration coming soon"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            >
              <p style={{ color: '#999', marginTop: 16 }}>
                For now, please upload photos through the Media Library page,
                <br />
                then return here to select them.
              </p>
              <Button type="primary" onClick={() => setActiveTab('library')}>
                Go to Library
              </Button>
            </Empty>
          </div>
        </TabPane>
      </Tabs>
    </Modal>
  );
};

export default PhotoPickerModal;
