'use client';

import * as DialogPrimitive from '@radix-ui/react-dialog';
import { cva, type VariantProps } from 'class-variance-authority';
import { X } from 'lucide-react';
import * as React from 'react';

import { cn } from '@/lib/utils';

/*
 * Panel lateral/inferior genérico sobre `@radix-ui/react-dialog` (mismo
 * primitivo que ya usa `dialog.tsx`, no una librería nueva). Pensado para
 * reemplazar el drawer del sidebar hardcodeado en `dashboard-shell.tsx` y
 * para paneles de filtros en mobile — ese reemplazo lo hace otro agente,
 * este componente sólo queda listo para consumirse.
 */
const Sheet = DialogPrimitive.Root;
const SheetTrigger = DialogPrimitive.Trigger;
const SheetPortal = DialogPrimitive.Portal;
const SheetClose = DialogPrimitive.Close;

const SheetOverlay = React.forwardRef<
    React.ElementRef<typeof DialogPrimitive.Overlay>,
    React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
    <DialogPrimitive.Overlay
        ref={ref}
        className={cn(
            'fixed inset-0 z-50 bg-foreground/25 backdrop-blur-[2px] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0',
            className
        )}
        {...props}
    />
));
SheetOverlay.displayName = DialogPrimitive.Overlay.displayName;

/*
 * `sheet-up` (tailwind.config.ts) ya cubre la entrada desde abajo. Los otros
 * tres lados no tienen keyframe propio en el config y esta tarea no debe
 * tocarlo — así que usan las utilidades `animate-in`/slide-in de
 * `tailwindcss-animate` (ya instalado, mismo plugin que anima `dialog.tsx` y
 * `select.tsx`) en vez de un keyframe nuevo.
 */
const sheetVariants = cva(
    'fixed z-50 flex flex-col overflow-hidden bg-surface text-foreground shadow-2xl data-[state=closed]:animate-out data-[state=closed]:duration-200',
    {
        variants: {
            side: {
                bottom:
                    'inset-x-0 bottom-0 max-h-[92dvh] rounded-t-3xl border-t border-border data-[state=open]:animate-sheet-up data-[state=closed]:slide-out-to-bottom',
                top: 'inset-x-0 top-0 max-h-[92dvh] rounded-b-3xl border-b border-border data-[state=open]:animate-in data-[state=open]:slide-in-from-top data-[state=closed]:slide-out-to-top',
                left: 'inset-y-0 left-0 h-full w-[86vw] max-w-sm border-r border-border data-[state=open]:animate-in data-[state=open]:slide-in-from-left data-[state=closed]:slide-out-to-left',
                right: 'inset-y-0 right-0 h-full w-[86vw] max-w-sm border-l border-border data-[state=open]:animate-in data-[state=open]:slide-in-from-right data-[state=closed]:slide-out-to-right',
            },
        },
        defaultVariants: {
            side: 'right',
        },
    }
);

export interface SheetContentProps
    extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>,
    VariantProps<typeof sheetVariants> {}

const SheetContent = React.forwardRef<
    React.ElementRef<typeof DialogPrimitive.Content>,
    SheetContentProps
>(({ side = 'right', className, children, ...props }, ref) => (
    <SheetPortal>
        <SheetOverlay />
        <DialogPrimitive.Content
            ref={ref}
            className={cn(sheetVariants({ side }), className)}
            {...props}
        >
            {/* Agarradera visible sólo en la hoja anclada abajo, como en dialog.tsx */}
            {side === 'bottom' ? (
                <div
                    aria-hidden
                    className="mx-auto mt-2 h-1 w-10 shrink-0 rounded-full bg-border-strong"
                />
            ) : null}
            {children}
            <DialogPrimitive.Close className="absolute right-3 top-3 z-10 flex h-9 w-9 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none">
                <X className="h-5 w-5" />
                <span className="sr-only">Cerrar</span>
            </DialogPrimitive.Close>
        </DialogPrimitive.Content>
    </SheetPortal>
));
SheetContent.displayName = DialogPrimitive.Content.displayName;

const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
    <div
        className={cn(
            'shrink-0 space-y-1 border-b border-border px-5 py-4 pr-14 text-left sm:px-6',
            className
        )}
        {...props}
    />
);
SheetHeader.displayName = 'SheetHeader';

const SheetBody = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
    <div
        className={cn('min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 py-5 sm:px-6', className)}
        {...props}
    />
);
SheetBody.displayName = 'SheetBody';

const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
    <div
        className={cn(
            'safe-bottom flex shrink-0 flex-col gap-2 border-t border-border bg-surface px-5 py-4 sm:flex-row sm:justify-end sm:px-6 [&>*]:w-full sm:[&>*]:w-auto',
            className
        )}
        {...props}
    />
);
SheetFooter.displayName = 'SheetFooter';

const SheetTitle = React.forwardRef<
    React.ElementRef<typeof DialogPrimitive.Title>,
    React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
    <DialogPrimitive.Title
        ref={ref}
        className={cn('text-lg font-semibold tracking-tight text-foreground', className)}
        {...props}
    />
));
SheetTitle.displayName = DialogPrimitive.Title.displayName;

const SheetDescription = React.forwardRef<
    React.ElementRef<typeof DialogPrimitive.Description>,
    React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
    <DialogPrimitive.Description
        ref={ref}
        className={cn('text-sm leading-relaxed text-muted-foreground', className)}
        {...props}
    />
));
SheetDescription.displayName = DialogPrimitive.Description.displayName;

export {
    Sheet,
    SheetPortal,
    SheetOverlay,
    SheetClose,
    SheetTrigger,
    SheetContent,
    SheetHeader,
    SheetBody,
    SheetFooter,
    SheetTitle,
    SheetDescription,
    sheetVariants,
};
