"use client"

import * as React from "react"
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"
import { X, CheckCircle, AlertCircle, AlertTriangle, Info } from "lucide-react"
import { cn } from "@/lib/utils"

const toastVariants = cva(
  "group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-lg border p-6 pe-8 shadow-lg transition-all data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=cancel]:translate-x-0 data-[swipe=end]:animate-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:animate-out",
  {
    variants: {
      variant: {
        default: "border-border bg-card text-foreground",
        destructive: "border-destructive bg-destructive text-destructive-foreground",
        success: "border-success bg-success text-success-foreground",
        warning: "border-warning bg-warning text-warning-foreground",
        info: "border-primary bg-primary text-primary-foreground",
        glass: "glass text-foreground border-border/20",
      },
      size: {
        default: "max-w-md",
        sm: "max-w-sm",
        lg: "max-w-lg",
        xl: "max-w-xl",
        full: "max-w-full",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)

const ToastProvider = ToastPrimitives.Provider

const ToastViewport = React.forwardRef<
  React.ElementRef<typeof ToastPrimitives.Viewport>,
  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
  <ToastPrimitives.Viewport
    ref={ref}
    className={cn(
      "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
      className
    )}
    {...props}
  />
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName

const Toast = React.forwardRef<
  React.ElementRef<typeof ToastPrimitives.Root>,
  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
    VariantProps<typeof toastVariants> & {
      icon?: React.ReactNode
      title?: string
      description?: string
      action?: React.ReactNode
      duration?: number
    }
>(({ className, variant, size, icon, title, description, action, duration = 5000, ...props }, ref) => {
  const [open, setOpen] = React.useState(true)

  const defaultIcons = {
    default: <Info className="h-5 w-5" />,
    destructive: <AlertCircle className="h-5 w-5" />,
    success: <CheckCircle className="h-5 w-5" />,
    warning: <AlertTriangle className="h-5 w-5" />,
    info: <Info className="h-5 w-5" />,
    glass: <Info className="h-5 w-5" />,
  }

  const displayIcon = icon || defaultIcons[variant as keyof typeof defaultIcons] || defaultIcons.default

  return (
    <ToastPrimitives.Root
      ref={ref}
      className={cn(toastVariants({ variant, size }), className)}
      duration={duration}
      open={open}
      onOpenChange={setOpen}
      {...props}
    >
      <div className="grid gap-1">
        <div className="flex items-center gap-3">
          {displayIcon && (
            <div className={cn(
              "flex-shrink-0 w-10 h-10 rounded-lg flex items-center justify-center",
              variant === "success" && "bg-success/20 text-success",
              variant === "destructive" && "bg-destructive/20 text-destructive",
              variant === "warning" && "bg-warning/20 text-warning",
              variant === "info" && "bg-primary/20 text-primary",
              variant === "default" && "bg-muted text-muted-foreground",
              variant === "glass" && "bg-surface/50 text-foreground"
            )}>
              {displayIcon}
            </div>
          )}
          
          <div className="grid gap-1 flex-1">
            {title && (
              <ToastPrimitives.Title className="text-sm font-semibold leading-none">
                {title}
              </ToastPrimitives.Title>
            )}
            {description && (
              <ToastPrimitives.Description className="text-sm opacity-90 leading-relaxed">
                {description}
              </ToastPrimitives.Description>
            )}
          </div>
        </div>
        
        {action && (
          <ToastPrimitives.Action
            className={cn(
              "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive"
            )}
            altText={typeof action === 'string' ? action : 'Action'}
          >
            {action}
          </ToastPrimitives.Action>
        )}
      </div>
      
      <ToastPrimitives.Close className="absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600">
        <X className="h-4 w-4" />
      </ToastPrimitives.Close>
    </ToastPrimitives.Root>
  )
})
Toast.displayName = ToastPrimitives.Root.displayName

const ToastAction = React.forwardRef<
  React.ElementRef<typeof ToastPrimitives.Action>,
  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
  <ToastPrimitives.Action
    ref={ref}
    className={cn(
      "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
      className
    )}
    {...props}
  />
))
ToastAction.displayName = ToastPrimitives.Action.displayName

const ToastClose = React.forwardRef<
  React.ElementRef<typeof ToastPrimitives.Close>,
  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
  <ToastPrimitives.Close
    ref={ref}
    className={cn(
      "absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
      className
    )}
    {...props}
  />
))
ToastClose.displayName = ToastPrimitives.Close.displayName

const ToastTitle = React.forwardRef<
  React.ElementRef<typeof ToastPrimitives.Title>,
  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
  <ToastPrimitives.Title
    ref={ref}
    className={cn("text-sm font-semibold", className)}
    {...props}
  />
))
ToastTitle.displayName = ToastPrimitives.Title.displayName

const ToastDescription = React.forwardRef<
  React.ElementRef<typeof ToastPrimitives.Description>,
  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
  <ToastPrimitives.Description
    ref={ref}
    className={cn("text-sm opacity-90", className)}
    {...props}
  />
))
ToastDescription.displayName = ToastPrimitives.Description.displayName

type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>

type ToastActionElement = React.ReactElement<{
  altText: string
  onClick: () => void
}>

// Enhanced Toast Hook
export function useToast() {
  const [toasts, setToasts] = React.useState<Array<{
    id: string
    title?: string
    description?: string
    variant?: VariantProps<typeof toastVariants>["variant"]
    duration?: number
    action?: React.ReactNode
    icon?: React.ReactNode
  }>>([])

  const toast = React.useCallback(
    ({ title, description, variant = "default", duration = 5000, action, icon }: Omit<ToastProps, "id">) => {
      const id = Math.random().toString(36).substr(2, 9)
      
      setToasts(prev => [...prev, {
        id,
        title,
        description,
        variant,
        duration,
        action,
        icon,
      }])

      // Auto remove after duration
      setTimeout(() => {
        setToasts(prev => prev.filter(toast => toast.id !== id))
      }, duration)
    },
    []
  )

  const success = React.useCallback(
    (props: Omit<ToastProps, "variant">) =>
      toast({ ...props, variant: "success" }),
    [toast]
  )

  const error = React.useCallback(
    (props: Omit<ToastProps, "variant">) =>
      toast({ ...props, variant: "destructive" }),
    [toast]
  )

  const warning = React.useCallback(
    (props: Omit<ToastProps, "variant">) =>
      toast({ ...props, variant: "warning" }),
    [toast]
  )

  const info = React.useCallback(
    (props: Omit<ToastProps, "variant">) =>
      toast({ ...props, variant: "info" }),
    [toast]
  )

  const dismiss = React.useCallback((id: string) => {
    setToasts(prev => prev.filter(toast => toast.id !== id))
  }, [])

  const dismissAll = React.useCallback(() => {
    setToasts([])
  }, [])

  return {
    toast,
    success,
    error,
    warning,
    info,
    dismiss,
    dismissAll,
    toasts,
  }
}

// Toast Container Component
export const ToastContainer = ({ children }: { children: React.ReactNode }) => {
  return (
    <ToastProvider>
      {children}
      <ToastViewport />
    </ToastProvider>
  )
}

// Individual Toast Component for use in ToastContainer
export const ToastItem = React.forwardRef<
  HTMLLIElement,
  {
    toast: {
      id: string
      title?: string
      description?: string
      variant?: VariantProps<typeof toastVariants>["variant"]
      duration?: number
      action?: React.ReactNode
      icon?: React.ReactNode
    }
    onDismiss: (id: string) => void
  }
>(({ toast, onDismiss, ...props }, ref) => {
  return (
    <li ref={ref}>
    <Toast
      variant={toast.variant}
      title={toast.title}
      description={toast.description}
      duration={toast.duration}
      icon={toast.icon}
      action={toast.action}
      onOpenChange={(open) => {
        if (!open) {
          onDismiss(toast.id)
        }
      }}
      {...props}
    />
    </li>
  )
})
ToastItem.displayName = "ToastItem"

export {
  type ToastProps,
  ToastProvider,
  ToastViewport,
  Toast,
  ToastTitle,
  ToastDescription,
  ToastClose,
  ToastAction,
}