import {
    Card,
    CardHeader,
    CardBody,
    __experimentalText as Text,
    __experimentalHeading as Heading,
    Tooltip,
    Notice,
    Button,
    Modal,
    Dropdown,
    // @ts-ignore
} from '@wordpress/components';
import { help } from '@wordpress/icons';
import { useState } from 'react';

function truncateString(s: string, len = 8) {
    if (!s) return '';
    return s.length > len ? s.slice(0, len) + '…' : s;
}



function SkeletonTable() {
    // Simple skeleton with 3 columns and 5 rows
    return (
        <Card style={{ marginBottom: 32 }}>
            <CardHeader>
                <Heading level={4} style={{ opacity: 0.5, background: "#f3f3f3", borderRadius: 4, width: 120, height: 18 }} />
            </CardHeader>
            <CardBody>
                <div style={{ overflowX: 'auto' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                        <thead>
                            <tr>
                                {[1,2,3].map(i => (
                                    <th key={i} style={{ textAlign: 'left', padding: '4px 8px', borderBottom: '1px solid #eee', fontWeight: 600 }}>
                                        <div style={{ background: "#eee", height: 14, width: 60, borderRadius: 3 }} />
                                    </th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {[...Array(5)].map((_, row) => (
                                <tr key={row} style={{ borderBottom: '1px solid #f3f3f3' }}>
                                    {[1,2,3].map(col => (
                                        <td key={col} style={{ padding: '4px 8px', verticalAlign: 'top', fontSize: 13 }}>
                                            <div style={{ background: "#f3f3f3", height: 12, width: "80%", borderRadius: 3 }} />
                                        </td>
                                    ))}
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </CardBody>
        </Card>
    );
}

function isImageUrl(url: string) {
    return /\.(jpe?g|png|gif|webp|bmp|svg)$/i.test(url);
}
function isVideoUrl(url: string) {
    return /\.mp4$/i.test(url);
}

export default function JobTables({ jobsData, loading }: { jobsData: any, loading?: boolean }) {
    const [modalContent, setModalContent] = useState<{ type: 'image' | 'video', url: string } | null>(null);
    // Track failed images by URL
    const [failedImages, setFailedImages] = useState<{ [url: string]: boolean }>({});

    // Handler for image error
    const handleImgError = (url: string) => {
        setFailedImages(prev => ({ ...prev, [url]: true }));
    };

    if (loading) {
        // Show 2 skeleton tables as a placeholder
        return (
            <div>
                <SkeletonTable />
                <SkeletonTable />
            </div>
        );
    }

    /*
    // Check if all array properties in jobsData are empty arrays
    // Example of NO jobs structure. This is considered a "no jobs found state"
        {
        "img2img": [],
        "img2vid": [],
        "img2img001vision": [],
        "foo": "bar",
    }
    */
    const arrayKeys = Object.keys(jobsData).filter(
        key => Array.isArray(jobsData[key])
    );
    const allArraysEmpty = arrayKeys.length > 0 && arrayKeys.every(
        key => Array.isArray(jobsData[key]) && jobsData[key].length === 0
    );
    if (allArraysEmpty) {
        return <Text>No jobs found.</Text>;
    }




    return (
        <div>
            <Notice status="info" isDismissible={false} style={{ marginBottom: 24 }}>
                <strong>Note:</strong> The media will be deleted after 30 days and will no longer be accessible. Please download any important media before this time.
            </Notice>
            <br/><br/>
            {Object.entries(jobsData).map(([jobType, jobs]) => (
                Array.isArray(jobs) && jobs.length > 0 ? (
                    <Card key={jobType} style={{ marginBottom: 32 }}>
                        <CardHeader>
                            <Heading level={4}>{jobType}</Heading>
                        </CardHeader>
                        <CardBody>
                            <div style={{ overflowX: 'auto' }}>
                                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                    <thead>
                                        <tr>
                                            {Object.keys(jobs[0]).map((key) => (
                                                <th key={key} style={{ textAlign: 'left', padding: '4px 8px', borderBottom: '1px solid #eee', fontWeight: 600 }}>
                                                    {key}
                                                </th>
                                            ))}
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {jobs.map((job: any, i: number) => (
                                            <tr key={job.id || i} style={{ borderBottom: '1px solid #f3f3f3' }}>
                                                {Object.entries(job).map(([key, value]) => (
                                                    <td key={key} style={{ padding: '4px 8px', verticalAlign: 'top', fontSize: 13 }}>
                                                        {(key === 'id') && typeof value === 'string' ? (
                                                            <Tooltip text={value}>
                                                                <span style={{ cursor: 'pointer', borderBottom: '1px dotted #888' }}>
                                                                    {truncateString(value, 8)}
                                                                </span>
                                                            </Tooltip>

                                                        ) : (key === 'input_object') && typeof value === 'object' ? (
                                                            <>
                                                                <Dropdown
                                                                    popoverProps={ { placement: 'bottom-start' } }
                                                                    renderToggle={ ( { isOpen, onToggle }:any ) => (
                                                                        <Button
                                                                            variant="tertiary"
                                                                            icon={ help }
                                                                            onClick={ onToggle }
                                                                            aria-expanded={ isOpen }
                                                                        >
                                                                        </Button>
                                                                    ) }
                                                                    renderContent={ () => <div><pre>{JSON.stringify(value, null, 2)}</pre></div> }
                                                                />                                                            
                                                            </>

                                                        ) : key === 'output_urls' && Array.isArray(value) ? (
                                                            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                                                                {value.map((url: string, idx: number) => (
                                                                    <span key={idx} style={{ display: 'inline-block' }}>
                                                                        {isImageUrl(url) && !failedImages[url] ? (
                                                                            <Tooltip text={url}>
                                                                                <img
                                                                                    src={url}
                                                                                    alt="output"
                                                                                    style={{ maxWidth: 80, maxHeight: 60, borderRadius: 4, cursor: 'pointer', border: '1px solid #eee', boxShadow: '0 1px 4px #0001' }}
                                                                                    onClick={() => setModalContent({ type: 'image', url })}
                                                                                    onError={() => handleImgError(url)}
                                                                                />
                                                                            </Tooltip>
                                                                        ) : isImageUrl(url) && failedImages[url] ? (
                                                                            <Tooltip text={url}>
                                                                                <a href={url} target="_blank" rel="noopener noreferrer" style={{ fontSize: 12, color: '#b00', wordBreak: 'break-all' }}>
                                                                                    {url}
                                                                                </a>
                                                                            </Tooltip>
                                                                        ) : isVideoUrl(url) ? (
                                                                            <Tooltip text={url}>
                                                                                <Button
                                                                                    //icon="format-video"
                                                                                    label="Preview video"
                                                                                    style={{ padding: 0, minWidth: 32, minHeight: 32, borderRadius: 4, background: '#eee', margin: 0 }}
                                                                                    onClick={() => setModalContent({ type: 'video', url })}
                                                                                >
                                                                                    {/* <span style={{ fontSize: 22, lineHeight: '32px', verticalAlign: 'middle' }}>▶</span> */}
                                                                                    <video src={ url } style={{ width: 60, height: 60, borderRadius: 4 }} autoPlay muted loop />
                                                                                </Button>
                                                                            </Tooltip>
                                                                        ) : (
                                                                            <Tooltip text={url}>
                                                                                <a href={url} target="_blank" rel="noopener noreferrer" style={{ fontSize: 12, wordBreak: 'break-all' }}>
                                                                                    {url}
                                                                                </a>
                                                                            </Tooltip>
                                                                        )}
                                                                    </span>
                                                                ))}
                                                            </div>
                                                        ) : value && typeof value === 'object' ? (
                                                            <pre style={{ margin: 0, maxWidth: 320, whiteSpace: 'pre-wrap', fontSize: 12, background: '#f8f8f8', borderRadius: 4, padding: 4 }}>
                                                                {JSON.stringify(value, null, 2)}
                                                            </pre>
                                                        ) : value === null ? (
                                                            <span style={{ color: '#aaa' }}>null</span>
                                                        ) : (
                                                            String(value)
                                                        )}
                                                    </td>
                                                ))}
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </CardBody>
                    </Card>
                ) : null
            ))}
            {modalContent && (
                <Modal
                    title={modalContent.type === 'image' ? 'Image Preview' : 'Video Preview'}
                    onRequestClose={() => setModalContent(null)}
                    shouldCloseOnClickOutside={true}
                >
                    {modalContent.type === 'image' ? (
                        <img src={modalContent.url} alt="output" style={{ maxWidth: '100%', maxHeight: '70vh', borderRadius: 8 }} />
                    ) : (
                        <video src={modalContent.url} controls autoPlay style={{ maxWidth: '100%', maxHeight: '70vh', borderRadius: 8, background: '#000' }} />
                    )}
                </Modal>
            )}
        </div>
    );
}