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,
  PlayCircleOutlined,
  CheckCircleOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { mediaApi } from '../../lib/media-api';
import { formatDuration } from './VideoPlayer';

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

export interface Video {
  id: number;
  title: string;
  filename: string;
  durationSeconds: number | null;
  fileSize: number | null;
  width: number | null;
  height: number | null;
  orientation: string | null;
  producer: string | null;
  createdAt: string;
  thumbnailPath: string | null;
}

export interface VideoPickerModalProps {
  open: boolean;
  onClose: () => void;
  onSelect: (video: Video) => void;
  mode?: 'single' | 'multiple';
  title?: string;
}

/**
 * Video Picker Modal with Library and Upload tabs
 * Allows selecting from existing videos or uploading new ones
 */
export const VideoPickerModal: React.FC<VideoPickerModalProps> = ({
  open,
  onClose,
  onSelect,
  mode = 'single',
  title = 'Select Video',
}) => {
  const [activeTab, setActiveTab] = useState('library');
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [loading, setLoading] = useState(false);
  const [videos, setVideos] = useState<Video[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(12);
  const [search, setSearch] = useState('');
  const [orientation, setOrientation] = useState<string>('');
  const [producer, setProducer] = useState<string>('');
  const [producers, setProducers] = useState<string[]>([]);
  const [selectedVideos, setSelectedVideos] = useState<Set<number>>(new Set());

  // Upload state (for future implementation)
  // const [uploading, setUploading] = useState(false);
  // const [uploadProgress, setUploadProgress] = useState(0);

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

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

      if (search) params.append('search', search);
      if (orientation) params.append('orientation', orientation);
      if (producer) params.append('producers', producer);

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

  const fetchProducers = async () => {
    try {
      const response = await mediaApi.get('/videos/producers');
      setProducers(response.data || []);
    } catch (error) {
      console.error('Failed to fetch producers:', error);
    }
  };

  const handleVideoClick = (video: Video) => {
    if (mode === 'single') {
      onSelect(video);
      onClose();
    } else {
      // Toggle selection for multiple mode
      setSelectedVideos((prev) => {
        const newSet = new Set(prev);
        if (newSet.has(video.id)) {
          newSet.delete(video.id);
        } else {
          newSet.add(video.id);
        }
        return newSet;
      });
    }
  };

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

    const selected = videos.filter((v) => selectedVideos.has(v.id));
    selected.forEach((video) => onSelect(video));
    onClose();
  };

  // const handleUploadComplete = (video: Video) => {
  //   message.success('Video uploaded successfully!');
  //   setActiveTab('library');
  //   setPage(1);
  //   fetchVideos();
  //
  //   // Auto-select the uploaded video
  //   setTimeout(() => {
  //     onSelect(video);
  //     onClose();
  //   }, 500);
  // };

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

  // Use Vite proxy path for browser-facing URLs (img src, etc.)
  // The raw VITE_MEDIA_API_URL may be a Docker hostname the browser can't resolve
  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={selectedVideos.size === 0}
            >
              Select ({selectedVideos.size})
            </Button>
          </div>
        ) : null
      }
    >
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane
          tab={
            <span>
              <PlayCircleOutlined />
              Library
            </span>
          }
          key="library"
        >
          {/* Filters */}
          <Row gutter={[12, 12]} style={{ marginBottom: 16 }}>
            <Col span={12}>
              <Input
                placeholder="Search videos..."
                prefix={<SearchOutlined />}
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setPage(1);
                }}
                allowClear
              />
            </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>
              </Select>
            </Col>
            <Col span={6}>
              <Select
                placeholder="Producer"
                value={producer || undefined}
                onChange={(value) => {
                  setProducer(value || '');
                  setPage(1);
                }}
                style={{ width: '100%' }}
                allowClear
                showSearch
              >
                {producers.map((p) => (
                  <Option key={p} value={p}>
                    {p}
                  </Option>
                ))}
              </Select>
            </Col>
          </Row>

          {/* Video Grid */}
          {loading ? (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <Spin size="large" />
            </div>
          ) : videos.length === 0 ? (
            <Empty description="No videos found" style={{ padding: 40 }}>
              <Button onClick={handleFilterReset}>Reset Filters</Button>
            </Empty>
          ) : (
            <>
              <Row gutter={[12, 12]}>
                {videos.map((video) => {
                  const isSelected = selectedVideos.has(video.id);
                  return (
                    <Col key={video.id} span={6}>
                      <Card
                        hoverable
                        cover={
                          <div
                            style={{
                              position: 'relative',
                              paddingBottom: '56.25%',
                              background: '#f0f0f0',
                              overflow: 'hidden',
                            }}
                          >
                            {video.thumbnailPath ? (
                              <img
                                src={`${mediaThumbnailBase}/videos/${video.id}/thumbnail`}
                                alt={video.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%)',
                                }}
                              >
                                <PlayCircleOutlined 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>
                            )}
                            {video.durationSeconds && (
                              <Tag
                                style={{
                                  position: 'absolute',
                                  bottom: 8,
                                  right: 8,
                                  margin: 0,
                                }}
                              >
                                {formatDuration(video.durationSeconds)}
                              </Tag>
                            )}
                          </div>
                        }
                        onClick={() => handleVideoClick(video)}
                        style={{
                          border: isSelected ? '2px solid #52c41a' : undefined,
                        }}
                      >
                        <Card.Meta
                          title={
                            <div
                              style={{
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap',
                                fontSize: 13,
                              }}
                            >
                              {video.title}
                            </div>
                          }
                          description={
                            <div style={{ fontSize: 11, color: '#999' }}>
                              {video.orientation === 'H' ? 'Horizontal' : 'Vertical'}
                              {video.producer && ` • ${video.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} videos`}
                />
              </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 videos 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 VideoPickerModal;
