'use client';

import { useState, useMemo } from 'react';
import { Tag } from '@/lib/types';
import { Card, CardContent, CardHeader } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { ConfirmModal } from '@/components/ui/ConfirmModal';
import { TagForm } from '@/components/forms/TagForm';
import { TagsStats } from './TagsStats';
import { TagsFilters } from './TagsFilters';
import { TagsGrid } from './TagsGrid';
import { Plus } from 'lucide-react';

interface TagsManagementProps {
  tags: (Tag & { usage: number })[];
  onRefreshTags: () => Promise<void>;
  onDeleteTag: (tagId: string) => Promise<void>;
}

export function TagsManagement({
  tags,
  onRefreshTags,
  onDeleteTag,
}: TagsManagementProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [showOnlyUnused, setShowOnlyUnused] = useState(false);
  const [showOnlyWithoutIcons, setShowOnlyWithoutIcons] = useState(false);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [editingTag, setEditingTag] = useState<Tag | null>(null);
  const [deletingTagId, setDeletingTagId] = useState<string | null>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [tagToDelete, setTagToDelete] = useState<Tag | null>(null);

  // Filtrer et trier les tags
  const filteredTags = useMemo(() => {
    let filtered = tags;

    // Filtrer par recherche
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter((tag) =>
        tag.name.toLowerCase().includes(query)
      );
    }

    // Filtrer pour afficher seulement les non utilisés
    if (showOnlyUnused) {
      filtered = filtered.filter((tag) => {
        const usage = tag.usage || 0;
        return usage === 0;
      });
    }

    // Filtrer pour afficher seulement les tags sans icônes
    if (showOnlyWithoutIcons) {
      filtered = filtered.filter(
        (tag) => !tag.name.match(/^[\p{Emoji}\p{Symbol}]/u)
      );
    }

    const sorted = filtered.sort((a, b) => {
      const usageA = a.usage || 0;
      const usageB = b.usage || 0;
      if (usageB !== usageA) return usageB - usageA;
      return a.name.localeCompare(b.name);
    });

    // Limiter à 12 tags si pas de recherche ni filtre, sinon afficher tous les résultats
    const hasFilters =
      searchQuery.trim() || showOnlyUnused || showOnlyWithoutIcons;
    return hasFilters ? sorted : sorted.slice(0, 12);
  }, [tags, searchQuery, showOnlyUnused, showOnlyWithoutIcons]);

  const handleEditTag = (tag: Tag) => {
    setEditingTag(tag);
  };

  const handleDeleteTag = async (tag: Tag) => {
    setTagToDelete(tag);
    setShowDeleteConfirm(true);
  };

  const confirmDeleteTag = async () => {
    if (!tagToDelete) return;

    setDeletingTagId(tagToDelete.id);
    try {
      await onDeleteTag(tagToDelete.id);
      await onRefreshTags();
    } catch (error) {
      console.error('Erreur lors de la suppression:', error);
    } finally {
      setDeletingTagId(null);
      setTagToDelete(null);
    }
  };

  const handleReset = () => {
    setSearchQuery('');
    setShowOnlyUnused(false);
    setShowOnlyWithoutIcons(false);
  };

  return (
    <>
      <Card variant="glass">
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-lg font-semibold flex items-center gap-2">
                🏷️ Gestion des tags
              </h2>
              <p className="text-sm text-[var(--muted-foreground)] mt-1">
                Créer et organiser les étiquettes pour vos tâches
              </p>
            </div>
            <Button
              variant="primary"
              size="sm"
              onClick={() => setIsCreateModalOpen(true)}
              className="flex items-center gap-2"
            >
              <Plus className="w-4 h-4" />
              Nouveau tag
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {/* Stats des tags */}
          <TagsStats tags={tags} />

          {/* Recherche et filtres */}
          <TagsFilters
            searchQuery={searchQuery}
            onSearchChange={setSearchQuery}
            showOnlyUnused={showOnlyUnused}
            onToggleUnused={() => setShowOnlyUnused(!showOnlyUnused)}
            showOnlyWithoutIcons={showOnlyWithoutIcons}
            onToggleWithoutIcons={() =>
              setShowOnlyWithoutIcons(!showOnlyWithoutIcons)
            }
            tags={tags}
            onReset={handleReset}
          />

          {/* Liste des tags en grid */}
          <TagsGrid
            tags={filteredTags}
            onEditTag={handleEditTag}
            onDeleteTag={handleDeleteTag}
            deletingTagId={deletingTagId}
            searchQuery={searchQuery}
            showOnlyUnused={showOnlyUnused}
            totalTags={tags.length}
          />
        </CardContent>
      </Card>

      {/* Modals pour les tags */}
      {isCreateModalOpen && (
        <TagForm
          isOpen={isCreateModalOpen}
          onClose={() => setIsCreateModalOpen(false)}
          onSuccess={async () => {
            setIsCreateModalOpen(false);
            await onRefreshTags();
          }}
        />
      )}

      {editingTag && (
        <TagForm
          isOpen={!!editingTag}
          tag={editingTag}
          onClose={() => setEditingTag(null)}
          onSuccess={async () => {
            setEditingTag(null);
            await onRefreshTags();
          }}
        />
      )}

      <ConfirmModal
        isOpen={showDeleteConfirm}
        onClose={() => {
          setShowDeleteConfirm(false);
          setTagToDelete(null);
        }}
        onConfirm={confirmDeleteTag}
        title="Supprimer le tag"
        message={`Êtes-vous sûr de vouloir supprimer le tag "${tagToDelete?.name}" ?`}
        confirmText="Supprimer"
        cancelText="Annuler"
        variant="destructive"
        isLoading={!!deletingTagId}
      />
    </>
  );
}
