import React from 'react';
import { Dialog } from '@/components/elements/dialog';
import { Button } from '@/components/elements/button/index';
import Code from '@/components/elements/Code';
import FileTypeBadge from '../FileTypeBadge';
import { FileObject } from '../api/server/files';
import GreyRowBox from '@/components/elements/GreyRowBox';

interface Props {
    visible: boolean;
    onDismiss: () => void;
    entries: Array<{
        path: string;
        file?: FileObject;
    }>;
}

const formatSize = (bytes?: number, isFile?: boolean): string => {
    if (!isFile || bytes === undefined || bytes === null) return '-';
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return `${Math.round((bytes / Math.pow(k, i)) * 100) / 100} ${sizes[i]}`;
};

const formatDate = (value?: Date | string | null): string => {
    if (!value) return '-';
    const date = value instanceof Date ? value : new Date(value);
    if (Number.isNaN(date.getTime())) return '-';
    const pad = (part: number) => String(part).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
};

const formatPermissions = (file?: FileObject): string => {
    if (!file) return '-';
    if (file.mode && file.modeBits) return `${file.mode} (${file.modeBits})`;
    if (file.mode) return file.mode;
    if (file.modeBits) return file.modeBits;
    return '-';
};

const DetailRow: React.FC<{ label: string; value: React.ReactNode }> = ({ label, value }) => (
    <div className="grid grid-cols-1 gap-1 border-t border-neutral-700 py-2.5 first:border-t-0 sm:grid-cols-[120px_minmax(0,1fr)] sm:gap-4">
        <span className="text-xs text-neutral-500">{label}</span>
        <span className="min-w-0 break-words text-sm text-neutral-300">{value}</span>
    </div>
);

const PropertiesModal: React.FC<Props> = ({ visible, onDismiss, entries }) => {
    const safeEntries = entries.filter((entry) => entry.path);
    const titleSuffix = safeEntries.length > 1 ? ` (${safeEntries.length})` : '';

    return (
        <Dialog open={visible} onClose={onDismiss} title={`Properties${titleSuffix}`}>
            <div className="betterfiles-scope max-h-[68vh] overflow-y-auto">
                {safeEntries.length === 0 ? (
                    <p className="text-sm text-neutral-300">No items selected.</p>
                ) : (
                    <div className="space-y-3">
                        {safeEntries.map((entry) => {
                            const file = entry.file;
                            const displayName = (file?.name ?? entry.path.split('/').pop()) || entry.path;
                            const isFile = file?.isFile ?? false;
                            const typeLabel = file ? (file.isFile ? 'File' : 'Folder') : 'Item';

                            return (
                                <GreyRowBox key={entry.path} className="flex-col !items-stretch !p-4" $hoverable={false}>
                                    <div className="flex items-center gap-3">
                                        <div className="flex min-w-0 items-center gap-3">
                                            <FileTypeBadge filename={displayName} isFolder={!isFile} />
                                            <div className="min-w-0">
                                                <p className="truncate text-sm font-semibold text-neutral-100">{displayName}</p>
                                                <p className="truncate text-xs text-neutral-500">{typeLabel}{file?.mimetype ? ` / ${file.mimetype}` : ''}</p>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="mt-4 border border-neutral-700 bg-neutral-800/40 px-3">
                                        <DetailRow label="Path" value={entry.path ? <Code>{entry.path}</Code> : '-'} />
                                        <DetailRow label="Size" value={formatSize(file?.size, file?.isFile)} />
                                        <DetailRow label="Permissions" value={formatPermissions(file)} />
                                        <DetailRow label="MIME Type" value={file?.mimetype || '-'} />
                                        <DetailRow label="Symlink" value={file?.isSymlink ? 'Yes' : 'No'} />
                                        <DetailRow label="Created" value={formatDate(file?.createdAt)} />
                                        <DetailRow label="Modified" value={formatDate(file?.modifiedAt)} />
                                    </div>
                                </GreyRowBox>
                            );
                        })}
                    </div>
                )}
            </div>

            <Dialog.Footer>
                <Button.Text onClick={onDismiss}>Close</Button.Text>
            </Dialog.Footer>
        </Dialog>
    );
};

export default PropertiesModal;
