import React, { useEffect } from 'react';
import { Row, Col, Image, Card, Typography, Tag, Empty, Badge } from 'antd';
import { FormattedMessage } from 'react-intl';
import { useDispatch, useSelector } from 'react-redux';
import store, { AppDispatch, RootState } from '@/states/store';
import { dview } from '@/domain/dview';
import { clearThumbnails, updateThumbnailsFromHistorySelection } from '@/states/patient/worklist/slices/thumbnailListSlice';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';

const { Text, Title } = Typography;

interface ThumbnailListProps {
  className?: string;
}

const ThumbnailList: React.FC<ThumbnailListProps> = ({ className }) => {
  const dispatch = useDispatch<AppDispatch>();
  const thumbnails = useSelector(
    (state: RootState) => state.thumbnailList.thumbnails
  );
  const currentKey = useSelector(
    (state: RootState) => state.BusinessFlow.currentKey
  );
  const loading = useSelector(
    (state: RootState) => state.thumbnailList.loading
  );
  const error = useSelector((state: RootState) => state.thumbnailList.error);
  const workSelectedIds = useSelector((state: RootState) => state.workSelection.selectedIds);
  const workHistorySelectedIds = useSelector((state: RootState) => state.historySelection.selectedIds);
  useEffect(() => {
    // 组件挂载时清空
    // 基于currentKey，查找history或者worklist中的选中项，
    if (currentKey === 'worklist') {
      const selectedId = store.getState().workSelection.selectedIds;
      if (selectedId.length > 0) { dispatch(updateThumbnailsFromHistorySelection(selectedId)); }
    }
    if (currentKey === 'historylist') {
      const selectedId = store.getState().historySelection.selectedIds;
      if (selectedId.length > 0) { dispatch(updateThumbnailsFromHistorySelection(selectedId)); }
    }
    // 组件卸载时清空
    return () => {
      dispatch(clearThumbnails());
    };
  }, [dispatch,workHistorySelectedIds,workSelectedIds]);
  if (error) {
    return (
      <div className={`p-4 ${className}`}>
        <Text type="danger">{error}</Text>
      </div>
    );
  }

  if (loading) {
    return (
      <div className={`p-4 ${className}`}>
        <Text>
          <FormattedMessage id="loading" defaultMessage="Loading..." />
        </Text>
      </div>
    );
  }

  if (thumbnails.length === 0) {
    return (
      <div className={`p-4 ${className}`}>
        <Empty
          description={
            <FormattedMessage
              id="thumbnailList.noImages"
              defaultMessage="No images to display"
            />
          }
        />
      </div>
    );
  }

  return (
    <div className={`p-1 overflow-auto ${className}`}>
      {/* <Title level={5} className="mb-3">
        <FormattedMessage
          id="thumbnailList.title"
          defaultMessage="Image Thumbnails"
        />
      </Title> */}
      <Row >
        {thumbnails.map((thumbnail: dview) => (
          <Col xs={24} sm={12} md={8} lg={3} xl={2} key={thumbnail.view_id}>
            <Card
              size="small"
              hoverable
              cover={
                <div className="relative">
                  <Image
                    src={thumbnail.thumbnail_file}
                    alt={thumbnail.view_description || thumbnail.view_id}
                    style={{
                      width: '100%',
                      height: '60px',
                      objectFit: 'cover',
                    }}
                    fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3Ik1RUG8M+Q4cMRcNHuS2BAYiBD/PIOCSFfYQ6QHBI7XhAGLpA5v4RFmEQGBFCCMxkYHJw9DQpIKjNZ/lN6JHV9937d8/o2+32uj9/t6j7n3F8nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    preview={{
                      mask: (
                        <div className="text-white text-center">
                          <FormattedMessage
                            id="preview"
                            defaultMessage="Preview"
                          />
                        </div>
                      ),
                    }}
                  />
                  {/* 左上角：判断状态badge */}
                  {/* {thumbnail.expose_status === 'Exposed' && thumbnail.judged_status && (
                    <div className="absolute top-1 left-1">
                      <Badge
                        count={
                          thumbnail.judged_status === 'Accept' ? (
                            <CheckOutlined style={{ color: '#fff' }} />
                          ) : thumbnail.judged_status === 'Reject' ? (
                            <CloseOutlined style={{ color: '#fff' }} />
                          ) : 'Un'
                        }
                        style={{
                          backgroundColor: thumbnail.judged_status === 'Accept' ? '#52c41a' : '#ff4d4f',
                        }}
                      />
                    </div>
                  )} */}
                  {/* 右上角：曝光状态tag */}
                  {/* <div className="absolute top-1 right-1">
                    <Tag
                      color={
                        thumbnail.expose_status === 'Exposed'
                          ? 'green'
                          : 'orange'
                      }
                    >
                      {thumbnail.expose_status}
                    </Tag>
                  </div> */}
                </div>
              }
            >
              <Card.Meta
                title={
                  <Text
                    ellipsis={{ tooltip: true }}
                    style={{ fontSize: '12px' }}
                  >
                    {thumbnail.view_description || thumbnail.view_type}
                  </Text>
                }
                // description={
                //   <Text type="secondary" style={{ fontSize: '10px' }}>
                //     ID: {thumbnail.view_id}
                //   </Text>
                // }
              />
            </Card>
          </Col>
        ))}
      </Row>
    </div>
  );
};

export default ThumbnailList;
