import React, { useState } from 'react'
import { Card, Image, Row, Col, Spin, Empty, Modal, Button, Tag, Space, Typography } from 'antd'
import { EyeOutlined, DownloadOutlined,  FileImageOutlined } from '@ant-design/icons'
import { useSelector } from 'react-redux'
import type { RootState } from '../../store/store'
import type { GalleryImage } from '../../store/slices/uiSlice'

const { Text } = Typography

interface GalleryViewProps {
  deviceId: string
}

/**
 * 相册展示组件
 */
const GalleryView: React.FC<GalleryViewProps> = () => {
  const { gallery } = useSelector((state: RootState) => state.ui)
  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewImage, setPreviewImage] = useState<GalleryImage | null>(null)

  const handlePreview = (image: GalleryImage) => {
    setPreviewImage(image)
    setPreviewVisible(true)
  }

  const handleDownload = (image: GalleryImage) => {
    // 创建下载链接
    const link = document.createElement('a')
    link.href = image.url
    link.download = image.displayName || `image_${image.id}.jpg`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  const formatDate = (timestamp: number) => {
    return new Date(timestamp).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }

  if (gallery.loading) {
    return (
      <Card title="Gallery" size="small" style={{ marginTop: '8px' }}>
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" />
          <div style={{ marginTop: '16px', color: '#666' }}>正在加载相册...</div>
        </div>
      </Card>
    )
  }

  if (gallery.images.length === 0) {
    return (
      <Card title="Gallery" size="small" style={{ marginTop: '8px' }}>
        <Empty
          image={<FileImageOutlined style={{ fontSize: '48px', color: 'var(--md-outline)' }} />}
          description="暂无相册图片"
          style={{ padding: '20px 0' }}
        />
      </Card>
    )
  }

  return (
    <>
      <Card 
        title={
          <Space>
            <FileImageOutlined />
            相册 ({gallery.images.length} 张)
          </Space>
        } 
        size="small" 
        style={{ marginTop: '8px' }}
        extra={
          <Tag color="blue">
            {gallery.images.length > 0 && formatDate(gallery.images[0].timestamp)}
          </Tag>
        }
      >
        <Row gutter={[8, 8]}>
          {gallery.images.map((image) => (
            <Col key={image.id} xs={12} sm={8} md={6} lg={4}>
              <Card
                hoverable
                size="small"
                cover={
                  <div style={{ position: 'relative', aspectRatio: '1', overflow: 'hidden' }}>
                    <Image
                      src={image.url}
                      alt={image.displayName}
                      style={{ 
                        width: '100%', 
                        height: '100%', 
                        objectFit: 'cover' 
                      }}
                      preview={false}
                      onClick={() => handlePreview(image)}
                    />
                    <div style={{
                      position: 'absolute',
                      top: '4px',
                      right: '4px',
                      background: 'rgba(0,0,0,0.6)',
                      color: 'white',
                      padding: '2px 6px',
                      borderRadius: '4px',
                      fontSize: '10px'
                    }}>
                      {image.width}×{image.height}
                    </div>
                  </div>
                }
                actions={[
                  <Button
                    key="preview"
                    type="text"
                    icon={<EyeOutlined />}
                    size="small"
                    onClick={() => handlePreview(image)}
                  />,
                  <Button
                    key="download"
                    type="text"
                    icon={<DownloadOutlined />}
                    size="small"
                    onClick={() => handleDownload(image)}
                  />
                ]}
              >
                <Card.Meta
                  title={
                    <Text ellipsis style={{ fontSize: '12px' }}>
                      {image.displayName || `图片_${image.index}`}
                    </Text>
                  }
                  description={
                    <Space direction="vertical" size={0} style={{ fontSize: '10px' }}>
                      <Text type="secondary">
                        {formatFileSize(image.size)}
                      </Text>
                      <Text type="secondary">
                        {formatDate(image.timestamp)}
                      </Text>
                    </Space>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      </Card>

      {/* 图片预览模态框 */}
      <Modal
        title={
          previewImage ? (
            <Space>
              <FileImageOutlined />
              {previewImage.displayName || `图片_${previewImage.index}`}
            </Space>
          ) : ''
        }
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={[
          <Button key="download" icon={<DownloadOutlined />} onClick={() => previewImage && handleDownload(previewImage)}>
            下载
          </Button>,
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>
        ]}
        width="80%"
        style={{ top: 20 }}
      >
        {previewImage && (
          <div>
            <Image
              src={previewImage.url}
              alt={previewImage.displayName}
              style={{ width: '100%', maxHeight: '70vh', objectFit: 'contain' }}
            />
            <div style={{ marginTop: '16px', padding: '12px', background: '#f5f5f5', borderRadius: '6px' }}>
              <Row gutter={[16, 8]}>
                <Col span={12}>
                  <Text strong>尺寸：</Text>
                  <Text>{previewImage.width} × {previewImage.height}</Text>
                </Col>
                <Col span={12}>
                  <Text strong>大小：</Text>
                  <Text>{formatFileSize(previewImage.size)}</Text>
                </Col>
                <Col span={12}>
                  <Text strong>类型：</Text>
                  <Text>{previewImage.mimeType}</Text>
                </Col>
                <Col span={12}>
                  <Text strong>时间：</Text>
                  <Text>{formatDate(previewImage.timestamp)}</Text>
                </Col>
                <Col span={24}>
                  <Text strong>路径：</Text>
                  <Text code style={{ fontSize: '11px' }}>{previewImage.contentUri}</Text>
                </Col>
              </Row>
            </div>
          </div>
        )}
      </Modal>
    </>
  )
}

export default GalleryView
