'use client';

import React, { useState } from 'react';
import { Modal, Button, Space, Image } from 'antd';
import { message } from '@/lib/feedback/message';
import { Download, FileText, Image as ImageIcon } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import { downloadFileFromAPI } from '@/lib/utils/export';

interface DocumentPreviewProps {
    url: string;
    type?: 'image' | 'pdf' | 'auto';
    filename?: string;
    title?: string;
    trigger?: React.ReactNode;
}

export function DocumentPreview({
    url,
    type = 'auto',
    filename,
    title,
    trigger,
}: DocumentPreviewProps) {
    const [visible, setVisible] = useState(false);
    const [loading, setLoading] = useState(false);

    const detectType = (url: string): 'image' | 'pdf' => {
        if (type !== 'auto') return type;
        const extension = url.split('.').pop()?.toLowerCase();
        if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'].includes(extension || '')) {
            return 'image';
        }
        if (extension === 'pdf') {
            return 'pdf';
        }
        return 'image'; // default
    };

    const handleDownload = async () => {
        try {
            setLoading(true);
            await downloadFileFromAPI(url, filename || 'documento');
            message.success('Download iniciado!');
        } catch (error) {
            message.error('Erro ao fazer download');
        } finally {
            setLoading(false);
        }
    };

    const fileType = detectType(url);

    const defaultTrigger = (
        <Button
            type="link"
            icon={
                fileType === 'image' ? (
                    <ImageIcon size={ICON_SIZE_MD} aria-hidden />
                ) : (
                    <FileText size={ICON_SIZE_MD} aria-hidden />
                )
            }
            onClick={() => setVisible(true)}
        >
            Visualizar
        </Button>
    );

    return (
        <>
            <div onClick={() => setVisible(true)} style={{ cursor: 'pointer' }}>
                {trigger || defaultTrigger}
            </div>

            <Modal
                title={title || filename || 'Visualizar Documento'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={
                    <Space>
                        <Button
                            icon={<Download size={ICON_SIZE_MD} aria-hidden />}
                            onClick={handleDownload}
                            loading={loading}
                        >
                            Baixar
                        </Button>
                        <Button onClick={() => setVisible(false)}>Fechar</Button>
                    </Space>
                }
                width={fileType === 'image' ? 800 : '90%'}
                style={{ top: 20 }}
            >
                {fileType === 'image' ? (
                    <div style={{ textAlign: 'center' }}>
                        <Image
                            src={url}
                            alt={filename || 'Preview'}
                            style={{ maxWidth: '100%', maxHeight: '70vh' }}
                            preview={false}
                        />
                    </div>
                ) : (
                    <iframe
                        src={url}
                        style={{
                            width: '100%',
                            height: '70vh',
                            border: 'none',
                        }}
                        title={filename || 'PDF Preview'}
                    />
                )}
            </Modal>
        </>
    );
}
