import React from 'react';
import { Dialog } from '@/components/elements/dialog';
import { Button } from '@/components/elements/button/index';
import GreyRowBox from '@/components/elements/GreyRowBox';
import type { OpenFile } from '../../EditorTabs';
import type { FileHistoryEntry } from '../hooks/useFileHistory';

interface Props {
    open: boolean;
    openFiles: OpenFile[];
    history: FileHistoryEntry[];
    onClose: () => void;
    onOpenFile: (path: string) => void;
    onClearHistory: () => void;
    onRemoveHistory: (path: string) => void;
}

const cx = (...parts: Array<string | false | null | undefined>) => parts.filter(Boolean).join(' ');

const formatTimestamp = (timestamp: number) => new Date(timestamp).toLocaleString(undefined, {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
});

const fileNameFromPath = (path: string) => path.split('/').pop() || path;

const Section: React.FC<{ title: string; empty: string; children?: React.ReactNode }> = ({ title, empty, children }) => (
    <div className='space-y-2'>
        <div className='text-sm font-semibold text-neutral-200'>{title}</div>
        <GreyRowBox className='!flex-col !items-stretch !p-0 overflow-hidden' $hoverable={false}>
            {children || <div className='px-4 py-4 text-sm text-neutral-400'>{empty}</div>}
        </GreyRowBox>
    </div>
);

const RecentModifiedDialog: React.FC<Props> = ({
    open,
    openFiles,
    history,
    onClose,
    onOpenFile,
    onClearHistory,
    onRemoveHistory,
}) => {
    const modifiedFiles = openFiles.filter((file) => file.hasUnsavedChanges);

    const openPath = (path: string) => {
        onOpenFile(path);
        onClose();
    };

    return (
        <Dialog open={open} onClose={onClose} title='Recent and Modified Files'>
            <div className='max-h-[65vh] space-y-4 overflow-y-auto pr-1'>
                <Section title='Modified' empty='No modified files.'>
                    {modifiedFiles.length > 0 && modifiedFiles.map((file) => (
                        <button
                            key={file.path}
                            type='button'
                            className='w-full border-b border-neutral-700 px-4 py-3 text-left transition-colors last:border-b-0 hover:bg-neutral-700 focus:bg-neutral-700 focus:outline-none'
                            onClick={() => openPath(file.path)}
                        >
                            <div className='truncate text-sm font-semibold text-neutral-100'>{file.name || fileNameFromPath(file.path)}</div>
                            <div className='mt-1 truncate text-xs text-neutral-400'>{file.path}</div>
                        </button>
                    ))}
                </Section>

                <Section title='Open Tabs' empty='No open tabs.'>
                    {openFiles.length > 0 && openFiles.map((file) => (
                        <button
                            key={file.path}
                            type='button'
                            className={cx(
                                'w-full border-b border-neutral-700 px-4 py-3 text-left transition-colors last:border-b-0',
                                'hover:bg-neutral-700 focus:bg-neutral-700 focus:outline-none'
                            )}
                            onClick={() => openPath(file.path)}
                        >
                            <div className='flex items-center gap-3'>
                                <span className='min-w-0 flex-1 truncate text-sm font-semibold text-neutral-100'>{file.name || fileNameFromPath(file.path)}</span>
                                {file.hasUnsavedChanges && <span className='shrink-0 text-xs font-semibold text-yellow-400'>Modified</span>}
                            </div>
                            <div className='mt-1 truncate text-xs text-neutral-400'>{file.path}</div>
                        </button>
                    ))}
                </Section>

                <div className='space-y-2'>
                    <div className='flex items-center justify-between gap-3'>
                        <div className='text-sm font-semibold text-neutral-200'>Recently Edited</div>
                        <Button.Text
                            type='button'
                            size={Button.Sizes.Small}
                            onClick={onClearHistory}
                            disabled={history.length === 0}
                        >
                            Clear
                        </Button.Text>
                    </div>
                    <GreyRowBox className='!flex-col !items-stretch !p-0 overflow-hidden' $hoverable={false}>
                        {history.length === 0 ? (
                            <div className='px-4 py-4 text-sm text-neutral-400'>No recently edited files.</div>
                        ) : history.map((entry) => (
                            <div
                                key={entry.path}
                                className='flex items-center gap-3 border-b border-neutral-700 px-4 py-3 last:border-b-0'
                            >
                                <button
                                    type='button'
                                    className='min-w-0 flex-1 text-left focus:outline-none'
                                    onClick={() => openPath(entry.path)}
                                >
                                    <div className='truncate text-sm font-semibold text-neutral-100'>{entry.filename}</div>
                                    <div className='mt-1 truncate text-xs text-neutral-400'>{entry.path}</div>
                                </button>
                                <div className='hidden shrink-0 text-xs text-neutral-500 sm:block'>{formatTimestamp(entry.timestamp)}</div>
                                <Button.Text
                                    type='button'
                                    size={Button.Sizes.Small}
                                    shape={Button.Shapes.IconSquare}
                                    onClick={() => onRemoveHistory(entry.path)}
                                    title='Remove from history'
                                >
                                    <svg className='h-4 w-4' fill='none' stroke='currentColor' viewBox='0 0 24 24'>
                                        <path strokeLinecap='round' strokeLinejoin='round' strokeWidth={2} d='M6 18L18 6M6 6l12 12' />
                                    </svg>
                                </Button.Text>
                            </div>
                        ))}
                    </GreyRowBox>
                </div>
            </div>
            <Dialog.Footer>
                <Button.Text onClick={onClose}>Close</Button.Text>
            </Dialog.Footer>
        </Dialog>
    );
};

export default RecentModifiedDialog;
