'use client';

import React, { useEffect, useState } from 'react';
import { Flex, Text } from '@radix-ui/themes';
import { isLegacyWordDocFile } from '../utils';
import type { FilePreviewRendererProps } from '../types';

// Export new specialized renderers
// NOTE: PDFRenderer is NOT exported here — it must be dynamically imported
// (via next/dynamic + ssr:false) to keep pdfjs-dist out of the server bundle.
export { ImageRenderer } from './image-renderer';
export { TextRenderer } from './text-renderer';
export { MarkdownRenderer } from './markdown-renderer';
export { MediaRenderer } from './media-renderer';
export { SpreadsheetRenderer } from './spreadsheet-renderer';
export { DocxRenderer } from './docx-renderer';

// Fallback renderer for unsupported Office documents (e.g. legacy Word .doc when not converted to PDF)
export function DocumentPreview({ fileUrl, fileName, fileBlob }: FilePreviewRendererProps) {
  const [blobUrl, setBlobUrl] = useState('');

  useEffect(() => {
    if (fileUrl?.trim()) {
      setBlobUrl('');
      return;
    }
    if (!fileBlob || fileBlob.size === 0) {
      setBlobUrl('');
      return;
    }
    const url = URL.createObjectURL(fileBlob);
    setBlobUrl(url);
    return () => {
      URL.revokeObjectURL(url);
    };
  }, [fileUrl, fileBlob]);

  const downloadHref = (fileUrl && fileUrl.trim() !== '') ? fileUrl : blobUrl;
  const isLegacyDoc = isLegacyWordDocFile(undefined, fileName);

  return (
    <Flex
      direction="column"
      align="center"
      justify="center"
      gap="4"
      style={{
        width: '100%',
        height: '100%',
        backgroundColor: 'var(--slate-2)',
        borderRadius: 'var(--radius-3)',
        padding: 'var(--space-6)',
      }}
    >
      <span className="material-icons-outlined" style={{ fontSize: '48px', color: 'var(--slate-9)' }}>
        description
      </span>
      <Text size="4" weight="medium" style={{ textAlign: 'center' }}>
        {fileName}
      </Text>
      <Text size="2" color="gray" style={{ textAlign: 'center', maxWidth: '400px' }}>
        {isLegacyDoc
          ? 'This file is in legacy Word (.doc) format. In-browser preview is not supported here; download it to open in Word, or save a copy as .docx to preview in Pipeshub.'
          : 'Preview not available for this document type. Please download to view.'}
      </Text>
      {downloadHref && downloadHref.trim() !== '' && (
        <a
          href={downloadHref}
          download={fileName}
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 'var(--space-2)',
            padding: 'var(--space-2) var(--space-4)',
            backgroundColor: 'var(--accent-9)',
            color: 'white',
            borderRadius: 'var(--radius-2)',
            textDecoration: 'none',
            fontSize: 'var(--font-size-2)',
            fontWeight: 500,
            transition: 'background-color 0.15s ease',
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.backgroundColor = 'var(--accent-10)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.backgroundColor = 'var(--accent-9)';
          }}
        >
          <span className="material-icons-outlined" style={{ fontSize: '18px' }}>
            download
          </span>
          Download File
        </a>
      )}
    </Flex>
  );
}

export function UnknownPreview({ fileName, fileUrl, fileBlob, webUrl, previewRenderable }: FilePreviewRendererProps) {
  const [blobUrl, setBlobUrl] = useState('');

  useEffect(() => {
    if (fileUrl?.trim()) {
      setBlobUrl('');
      return;
    }
    if (!fileBlob || fileBlob.size === 0) {
      setBlobUrl('');
      return;
    }
    const url = URL.createObjectURL(fileBlob);
    setBlobUrl(url);
    return () => {
      URL.revokeObjectURL(url);
    };
  }, [fileUrl, fileBlob]);

  const downloadHref = (fileUrl && fileUrl.trim() !== '') ? fileUrl : blobUrl;

  const buttonStyle: React.CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    gap: 'var(--space-2)',
    padding: 'var(--space-2) var(--space-4)',
    borderRadius: 'var(--radius-2)',
    textDecoration: 'none',
    fontSize: 'var(--font-size-2)',
    fontWeight: 500,
    transition: 'background-color 0.15s ease',
  };

  return (
    <Flex
      direction="column"
      align="center"
      justify="center"
      gap="4"
      style={{
        width: '100%',
        height: '100%',
        backgroundColor: 'var(--slate-2)',
        borderRadius: 'var(--radius-3)',
        padding: 'var(--space-6)',
      }}
    >
      <span className="material-icons-outlined" style={{ fontSize: '48px', color: 'var(--slate-9)' }}>
        insert_drive_file
      </span>
      <Text size="4" weight="medium" style={{ textAlign: 'center' }}>
        {fileName}
      </Text>
      <Text size="2" color="gray" style={{ textAlign: 'center', maxWidth: '400px' }}>
        Preview not available for this file type
      </Text>
      <Flex gap="3">
        {previewRenderable !== false && downloadHref && downloadHref.trim() !== '' && (
          <a
            href={downloadHref}
            download={fileName}
            style={{ ...buttonStyle, backgroundColor: 'var(--accent-9)', color: 'white' }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = 'var(--accent-10)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = 'var(--accent-9)';
            }}
          >
            <span className="material-icons-outlined" style={{ fontSize: '18px' }}>
              download
            </span>
            Download File
          </a>
        )}
        {webUrl && webUrl.trim() !== '' && (
          <a
            href={webUrl}
            target="_blank"
            rel="noopener noreferrer"
            style={{ ...buttonStyle, backgroundColor: 'var(--olive-4)', color: 'var(--olive-12)', border: '1px solid var(--olive-6)' }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = 'var(--olive-5)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = 'var(--olive-4)';
            }}
          >
            <span className="material-icons-outlined" style={{ fontSize: '18px' }}>
              open_in_new
            </span>
            Open in Browser
          </a>
        )}
      </Flex>
    </Flex>
  );
}
