'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { motion } from 'framer-motion';
import { Plus, Search } from 'lucide-react';

import { cn } from '@/lib/utils';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  WIDGET_REGISTRY,
  WIDGET_CATEGORIES,
  getWidgetsByCategory,
  type WidgetMeta,
  type WidgetCategory,
} from './widget-registry';

interface AddWidgetDialogProps {
  onAddWidget: (widgetType: string) => void;
  existingWidgets?: string[];
  userRoles?: string[];
  trigger?: React.ReactNode;
}

/**
 * Add Widget Dialog - Allows users to add new widgets to their dashboard
 */
export function AddWidgetDialog({
  onAddWidget,
  existingWidgets = [],
  userRoles = [],
  trigger,
}: AddWidgetDialogProps) {
  const t = useTranslations('widgets');
  const [open, setOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<WidgetCategory | 'all'>('all');

  // Filter widgets based on search and category
  const getFilteredWidgets = (): WidgetMeta[] => {
    let widgets = Object.values(WIDGET_REGISTRY);

    // Filter by category
    if (selectedCategory !== 'all') {
      widgets = getWidgetsByCategory(selectedCategory);
    }

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      widgets = widgets.filter(
        (widget) =>
          t(widget.nameKey).toLowerCase().includes(query) ||
          t(widget.descriptionKey).toLowerCase().includes(query)
      );
    }

    // Filter by user roles (if widget has required roles)
    widgets = widgets.filter(
      (widget) =>
        widget.requiredRoles.length === 0 ||
        widget.requiredRoles.some((role) => userRoles.includes(role))
    );

    return widgets;
  };

  const filteredWidgets = getFilteredWidgets();

  const handleAddWidget = (widgetType: string) => {
    onAddWidget(widgetType);
    setOpen(false);
    setSearchQuery('');
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {trigger || (
          <Button variant="outline" size="sm" className="gap-2">
            <Plus className="h-4 w-4" />
            {t('addWidget')}
          </Button>
        )}
      </DialogTrigger>

      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>{t('addWidgetTitle')}</DialogTitle>
          <DialogDescription>{t('addWidgetDescription')}</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* Search Input */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder={t('searchWidgets')}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9"
            />
          </div>

          {/* Category Tabs */}
          <Tabs
            value={selectedCategory}
            onValueChange={(value) => setSelectedCategory(value as WidgetCategory | 'all')}
          >
            <TabsList className="w-full justify-start">
              <TabsTrigger value="all">{t('categories.all')}</TabsTrigger>
              {WIDGET_CATEGORIES.map((category) => (
                <TabsTrigger key={category.key} value={category.key}>
                  {t(category.labelKey)}
                </TabsTrigger>
              ))}
            </TabsList>

            {/* Widget Grid */}
            <TabsContent value={selectedCategory} className="mt-4">
              <ScrollArea className="h-[400px] pr-4">
                {filteredWidgets.length === 0 ? (
                  <div className="flex h-32 items-center justify-center text-sm text-muted-foreground">
                    {t('noWidgetsFound')}
                  </div>
                ) : (
                  <div className="grid grid-cols-2 gap-3">
                    {filteredWidgets.map((widget, index) => {
                      const Icon = widget.icon;
                      const isAlreadyAdded = existingWidgets.includes(widget.type);

                      return (
                        <motion.button
                          key={widget.type}
                          initial={{ opacity: 0, y: 10 }}
                          animate={{ opacity: 1, y: 0 }}
                          transition={{ duration: 0.2, delay: index * 0.03 }}
                          onClick={() => handleAddWidget(widget.type)}
                          disabled={isAlreadyAdded}
                          className={cn(
                            'flex items-start gap-3 rounded-lg border p-4 text-left transition-colors',
                            'hover:bg-accent hover:border-accent-foreground/20',
                            'focus:outline-none focus:ring-2 focus:ring-ring',
                            isAlreadyAdded && 'cursor-not-allowed opacity-50'
                          )}
                        >
                          <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10">
                            <Icon className="h-5 w-5 text-primary" />
                          </div>

                          <div className="flex-1 space-y-1">
                            <p className="font-medium leading-none">{t(widget.nameKey)}</p>
                            <p className="text-sm text-muted-foreground line-clamp-2">
                              {t(widget.descriptionKey)}
                            </p>
                            {isAlreadyAdded && (
                              <p className="text-xs text-primary">{t('alreadyAdded')}</p>
                            )}
                          </div>
                        </motion.button>
                      );
                    })}
                  </div>
                )}
              </ScrollArea>
            </TabsContent>
          </Tabs>
        </div>
      </DialogContent>
    </Dialog>
  );
}
