'use client';

import { ReactNode, forwardRef } from 'react';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { motion } from 'framer-motion';
import { GripVertical, X, Settings } from 'lucide-react';
import { useTranslations } from 'next-intl';

import { cn } from '@/lib/utils';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';

export interface WidgetContainerProps {
  /** Unique widget ID */
  id: string;
  /** Widget title */
  title: string;
  /** Optional icon */
  icon?: ReactNode;
  /** Widget content */
  children: ReactNode;
  /** Whether the widget is being edited (showing controls) */
  isEditing?: boolean;
  /** Callback when remove button is clicked */
  onRemove?: () => void;
  /** Callback when settings button is clicked */
  onSettings?: () => void;
  /** Additional CSS classes */
  className?: string;
  /** Whether to show the header */
  showHeader?: boolean;
  /** Grid column span */
  colSpan?: number;
  /** Grid row span */
  rowSpan?: number;
}

/**
 * Widget Container - Wrapper component for dashboard widgets
 * Provides drag handle, remove/settings buttons, and consistent styling
 */
export const WidgetContainer = forwardRef<HTMLDivElement, WidgetContainerProps>(
  function WidgetContainer(
    {
      id,
      title,
      icon,
      children,
      isEditing = false,
      onRemove,
      onSettings,
      className,
      showHeader = true,
      colSpan = 1,
      rowSpan = 1,
    },
    ref
  ) {
    const t = useTranslations('widgets');

    const {
      attributes,
      listeners,
      setNodeRef,
      transform,
      transition,
      isDragging,
    } = useSortable({ id, disabled: !isEditing });

    const style = {
      transform: CSS.Transform.toString(transform),
      transition,
      gridColumn: `span ${colSpan}`,
      gridRow: `span ${rowSpan}`,
    };

    return (
      <motion.div
        ref={setNodeRef}
        style={style}
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        exit={{ opacity: 0, scale: 0.95 }}
        transition={{ duration: 0.2 }}
        className={cn(isDragging && 'z-50')}
      >
        <Card
          ref={ref}
          className={cn(
            'relative h-full transition-shadow duration-200',
            isDragging && 'shadow-lg ring-2 ring-primary/20',
            isEditing && 'ring-1 ring-dashed ring-muted-foreground/30',
            className
          )}
        >
          {showHeader && (
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <div className="flex items-center gap-2">
                {/* Drag Handle - only visible in edit mode */}
                {isEditing && (
                  <button
                    {...attributes}
                    {...listeners}
                    className="cursor-grab touch-none rounded p-1 hover:bg-muted active:cursor-grabbing"
                    aria-label="Drag to reorder"
                  >
                    <GripVertical className="h-4 w-4 text-muted-foreground" />
                  </button>
                )}

                {/* Title with optional icon */}
                <CardTitle className="flex items-center gap-2 text-sm font-medium">
                  {icon}
                  {title}
                </CardTitle>
              </div>

              {/* Action buttons - only visible in edit mode */}
              {isEditing && (
                <div className="flex items-center gap-1">
                  {onSettings && (
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-7 w-7"
                          onClick={onSettings}
                        >
                          <Settings className="h-3.5 w-3.5" />
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>{t('settings')}</TooltipContent>
                    </Tooltip>
                  )}

                  {onRemove && (
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-7 w-7 text-destructive hover:text-destructive"
                          onClick={onRemove}
                        >
                          <X className="h-3.5 w-3.5" />
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>{t('remove')}</TooltipContent>
                    </Tooltip>
                  )}
                </div>
              )}
            </CardHeader>
          )}

          <CardContent className={cn(!showHeader && 'pt-6')}>{children}</CardContent>
        </Card>
      </motion.div>
    );
  }
);
