import React, { useState } from 'react';
import { colors } from '../colors';
import GreyRowBox from '@/components/elements/GreyRowBox';

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

type DivProps = React.HTMLAttributes<HTMLDivElement>;

export const PageContainer = React.forwardRef<HTMLDivElement, DivProps>(({ className, style, ...props }, ref) => (
    <div ref={ref} className={cx('mb-0 md:mb-4 bfm-page-container w-full max-w-full min-w-0 overflow-x-hidden', className)} style={style} {...props} />
));


export const Container = React.forwardRef<HTMLDivElement, DivProps & { isResizing?: boolean }>(
    ({ className, style, isResizing, ...props }, ref) => (
        <div
            ref={ref}
            className={cx(
                'bfm-main-layout flex overflow-hidden gap-2 mx-auto w-full max-w-full min-w-0',
                'flex-col md:flex-row',
                'h-[calc(100dvh-4rem)] md:h-[calc(100vh-10rem)]',
                'min-h-0 md:min-h-[600px]',
                className
            )}
            style={{
                transition: isResizing ? 'none' : 'grid-template-columns 160ms ease',
                ...style,
            }}
            {...props}
        />
    )
);
Container.displayName = 'Container';

export const LeftPanel = React.forwardRef<HTMLDivElement, DivProps & { width: number; isResizing?: boolean }>(
    ({ width, isResizing, className, style, ...props }, ref) => (
        <GreyRowBox
            ref={ref}
            className={cx(
                'flex-col items-stretch items-start flex-none overflow-hidden',
                'w-full h-full min-w-0 max-w-full',
                'md:w-full md:basis-auto md:shrink md:min-w-0 md:max-w-full',
                className
            )}
            style={{
                ['--bfm-left-width' as any]: `${width}px`,
                transition: isResizing ? 'none' : 'max-width 160ms ease',
                contain: 'layout paint size',
                willChange: isResizing ? 'max-width' : 'auto',
                ...style,
            }}
            {...props}
        />
    )
);
LeftPanel.displayName = 'LeftPanel';

export const ResizeHandle: React.FC<DivProps> = ({ className, style, onMouseDown, onMouseUp, ...props }) => {
    const [hovered, setHovered] = useState(false);
    const [active, setActive] = useState(false);
    return (
        <div
            className={cx(
                'w-1 transition-colors duration-150 bg-gray-500 hidden md:block cursor-col-resize',
                className
            )}
            onMouseEnter={() => setHovered(true)}
            onMouseLeave={() => {
                setHovered(false);
                setActive(false);
            }}
            onMouseDown={(e) => {
                setActive(true);
                onMouseDown?.(e);
            }}
            onMouseUp={(e) => {
                setActive(false);
                onMouseUp?.(e);
            }}
            style={{
                backgroundColor: active ? colors.primary.dark : hovered ? colors.primary.default : undefined,
                ...style,
            }}
            {...props}
        />
    );
};

export { GreyRowBox };

type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement>;
type SpanProps = React.HTMLAttributes<HTMLSpanElement>;

export const EditorHeader: React.FC<DivProps> = ({ className, ...props }) => (
    <div
        className={cx(
            'px-0 py-0 flex flex-col gap-0',
            'md:flex-row md:items-center md:justify-between md:px-0 md:py-0',
            className
        )}
        {...props}
    />
);

export const FilePath: React.FC<DivProps> = ({ className, ...props }) => (
    <div
        className={cx(
            'font-mono text-sm flex flex-col items-start gap-1 text-neutral-300 w-full min-w-0',
            'md:flex-row md:items-center md:gap-2 md:flex-wrap',
            className
        )}
        {...props}
    />
);

export const EditorActions: React.FC<DivProps> = ({ className, ...props }) => (
    <div className={cx('flex items-center gap-2 flex-wrap ml-auto flex-shrink-0', className)} {...props} />
);

export const EmptyState: React.FC<DivProps> = ({ className, ...props }) => (
    <div
        className={cx('flex-1 flex items-center justify-center flex-col p-4 text-neutral-300', className)}
        {...props}
    />
);

export const SplitViewContainer = React.forwardRef<HTMLDivElement, DivProps>(({ className, ...props }, ref) => (
    <div ref={ref} className={cx('flex flex-1 w-full max-w-full min-w-0 overflow-y-auto overflow-x-hidden md:overflow-hidden min-h-0', className)} {...props} />
));
SplitViewContainer.displayName = 'SplitViewContainer';

export const SplitEditorPane = React.forwardRef<HTMLDivElement, DivProps & { isDragOver?: boolean; active?: boolean; framed?: boolean }>(
    ({ isDragOver, active, framed, className, style, ...props }, ref) => (
        <div
            ref={ref}
            className={cx(
                'flex-1 flex flex-col relative min-w-0 min-h-0 max-w-full overflow-x-hidden',
                framed
                    ? cx(
                          'overflow-hidden border bg-gray-800 shadow-sm',
                          active ? 'border-gray-600' : 'border-gray-700'
                      )
                    : 'overflow-y-auto md:overflow-hidden',
                className
            )}
            style={{
                ...(isDragOver ? {} : {}),
                borderRadius: framed ? 3 : undefined,
                transition: 'flex-basis 240ms ease, max-width 240ms ease, opacity 180ms ease, transform 240ms ease, border-color 180ms ease',
                ...style,
            }}
            {...props}
        />
    )
);
SplitEditorPane.displayName = 'SplitEditorPane';

export const SplitDropZone: React.FC<DivProps & { isDragOver?: boolean }> = ({ isDragOver, className, style, children, ...props }) => (
    <div
        className={cx('absolute inset-0 flex items-center justify-center z-10 transition-opacity', className)}
        style={{
            padding: 12,
            background: isDragOver ? colors.primary.opacity(0.08) : 'transparent',
            opacity: isDragOver ? 1 : 0,
            pointerEvents: isDragOver ? 'auto' : 'none',
            ...style,
        }}
        {...props}
    >
        <div
            className='w-full h-full flex items-center justify-center'
            style={{
                border: `2px dashed ${colors.primary.default}`,
                borderSpacing: 10,
                borderCollapse: 'separate',
                boxShadow: `0 0 0 1px ${colors.primary.opacity(0.35)}`,
                background: colors.primary.opacity(0.06),
            }}
        >
            {children}
        </div>
    </div>
);

export const SplitDivider: React.FC<DivProps> = ({ className, style, ...props }) => {
    const [hovered, setHovered] = useState(false);
    const [active, setActive] = useState(false);
    return (
        <div
            className={cx('flex-shrink-0 flex items-center justify-center transition-colors bg-gray-800', className)}
            onMouseEnter={() => setHovered(true)}
            onMouseLeave={() => {
                setHovered(false);
                setActive(false);
            }}
            onMouseDown={() => setActive(true)}
            onMouseUp={() => setActive(false)}
            style={{
                width: 4,
                cursor: 'col-resize',
                background: active ? colors.primary.opacity(0.25) : hovered ? colors.primary.opacity(0.15) : undefined,
                ...style,
            }}
            {...props}
        >
            <span
                className='transition-all bg-gray-500'
                style={{
                    width: 1,
                    height: hovered ? 56 : 36,
                    background: hovered ? colors.primary.default : undefined,
                    borderRadius: 1,
                }}
            />
        </div>
    );
};

export const SplitPaneHeader: React.FC<DivProps & { active: boolean }> = ({ active, className, style, ...props }) => (
    <div
        className={cx(
            'h-8 px-2 flex items-center justify-between gap-2 cursor-pointer select-none border-b text-neutral-300',
            active ? 'bg-gray-800 border-gray-600' : 'bg-gray-800 border-gray-700',
            className
        )}
        style={style}
        {...props}
    />
);

export const SplitPaneHeaderLeft: React.FC<DivProps> = ({ className, ...props }) => (
    <div className={cx('flex items-center gap-2 min-w-0 flex-1', className)} {...props} />
);

export const SplitPaneTitle: React.FC<SpanProps & { active: boolean }> = ({ active: _active, className, style, ...props }) => (
    <span
        className={cx('text-xs font-medium truncate text-neutral-300', className)}
        style={style}
        {...props}
    />
);

export const PaneBadge: React.FC<SpanProps & { active: boolean }> = ({ active, className, style, ...props }) => (
    <span
        className={cx(
            'text-[10px] px-1.5 py-0.5 border text-neutral-300 leading-none flex-shrink-0',
            active ? '' : 'border-gray-600 bg-gray-700 text-neutral-400',
            className
        )}
        style={{
            ...(active
                ? {
                      borderColor: colors.primary.opacity(0.5),
                      background: colors.primary.opacity(0.25),
                  }
                : {}),
            ...style,
        }}
        {...props}
    />
);

export const SplitCloseButton: React.FC<ButtonProps> = ({ className, style, ...props }) => (
    <button
        className={cx(
            'inline-flex h-6 w-6 flex-shrink-0 items-center justify-center text-neutral-400 transition-colors hover:bg-gray-600 hover:text-red-300',
            className
        )}
        style={{
            borderRadius: 3,
            ...style,
        }}
        {...props}
    />
);

export const MobileTabBar: React.FC<DivProps> = ({ className, style, ...props }) => (
    <div className='md:hidden'>
        <GreyRowBox
            className={cx('flex flex-col gap-1 !p-1 !rounded-md overflow-hidden', className)}
            $hoverable={false}
            style={style}
            {...props}
        />
    </div>
);

export const MobileTab: React.FC<ButtonProps & { active: boolean }> = ({ active, className, children, ...props }) => (
    <button
        className={cx(
            'min-w-0 flex-1 rounded px-2 py-2 text-sm font-medium transition-colors relative',
            active ? 'text-neutral-100 bg-gray-700' : 'text-gray-400 hover:bg-gray-700/60 hover:text-neutral-200',
            className
        )}
        {...props}
    >
        {children}
        <span
            className='absolute bottom-0 left-0 w-full h-0.5 transition-colors'
            style={{ backgroundColor: active ? colors.primary.default : 'transparent' }}
        />
    </button>
);
