import { Card, Row, Col, Button, Typography, Empty } from 'antd';
import {
  FileTextOutlined,
  VideoCameraOutlined,
  PictureOutlined,
  DownloadOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { mediaApi } from '@/lib/media-api';
import type { DashboardResource } from './types';

interface ResourcesGridProps {
  resources: DashboardResource[];
}

const KIND_ICONS = {
  document: <FileTextOutlined style={{ fontSize: 40, color: 'rgba(255,255,255,0.3)' }} />,
  video: <VideoCameraOutlined style={{ fontSize: 40, color: 'rgba(255,255,255,0.3)' }} />,
  photo: <PictureOutlined style={{ fontSize: 40, color: 'rgba(255,255,255,0.3)' }} />,
};

function resolveDownloadUrl(downloadPath: string): string {
  if (/^https?:\/\//i.test(downloadPath)) return downloadPath;
  const base = (mediaApi.defaults.baseURL || '/media').replace(/\/$/, '');
  return `${base}${downloadPath.startsWith('/') ? '' : '/'}${downloadPath}`;
}

export default function ResourcesGrid({ resources }: ResourcesGridProps) {
  const navigate = useNavigate();

  const handleAction = (resource: DashboardResource) => {
    if (resource.kind === 'document' && resource.downloadPath) {
      const url = resolveDownloadUrl(resource.downloadPath);
      const link = document.createElement('a');
      link.href = url;
      link.download = resource.title;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      return;
    }
    if (resource.viewPath) {
      if (/^https?:\/\//i.test(resource.viewPath)) {
        window.open(resource.viewPath, '_blank', 'noopener,noreferrer');
      } else {
        navigate(resource.viewPath);
      }
    }
  };

  return (
    <Card
      styles={{
        header: { borderBottom: '1px solid rgba(255,255,255,0.06)', padding: '12px 20px', minHeight: 'auto' },
        body: { padding: 20 },
      }}
      title={
        <span style={{ fontSize: 14, fontWeight: 600 }}>Tools & Resources</span>
      }
    >
      {resources.length === 0 ? (
        <Empty description="No resources available yet" image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <Row gutter={[16, 16]}>
          {resources.map((resource) => (
            <Col key={resource.id} xs={12} sm={8} md={6}>
              <Card
                hoverable
                size="small"
                styles={{
                  body: { padding: 0 },
                }}
                style={{ height: '100%', overflow: 'hidden' }}
              >
                <div
                  style={{
                    height: 120,
                    background: 'rgba(255,255,255,0.03)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    overflow: 'hidden',
                  }}
                >
                  {resource.thumbnailUrl ? (
                    <img
                      src={resource.thumbnailUrl}
                      alt={resource.title}
                      style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                    />
                  ) : (
                    KIND_ICONS[resource.kind]
                  )}
                </div>
                <div style={{ padding: '10px 12px 12px' }}>
                  <Typography.Text
                    strong
                    style={{
                      display: 'block',
                      fontSize: 13,
                      marginBottom: 8,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {resource.title}
                  </Typography.Text>
                  <Button
                    size="small"
                    block
                    icon={resource.kind === 'document' ? <DownloadOutlined /> : <EyeOutlined />}
                    onClick={() => handleAction(resource)}
                    disabled={
                      resource.kind === 'document'
                        ? !resource.downloadPath
                        : !resource.viewPath
                    }
                  >
                    {resource.kind === 'document' ? 'Download' : 'View'}
                  </Button>
                </div>
              </Card>
            </Col>
          ))}
        </Row>
      )}
    </Card>
  );
}
