
import React, { useState, useEffect } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { X, Plus, Tags } from "lucide-react";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { supabase } from "@/integrations/supabase/client";

interface ProjectTagsManagerProps {
  tags: string[];
  onTagsChange: (tags: string[]) => void;
}

const ProjectTagsManager = ({ tags, onTagsChange }: ProjectTagsManagerProps) => {
  const [newTag, setNewTag] = useState("");
  const [existingTags, setExistingTags] = useState<string[]>([]);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    fetchExistingTags();
  }, []);

  const fetchExistingTags = async () => {
    try {
      const { data: projects, error } = await supabase
        .from('projects')
        .select('tags');

      if (error) {
        console.error('Error fetching existing tags:', error);
        return;
      }

      // Extract all unique tags from all projects
      const allTags = new Set<string>();
      projects?.forEach(project => {
        if (project.tags && Array.isArray(project.tags)) {
          project.tags.forEach(tag => allTags.add(tag));
        }
      });

      setExistingTags(Array.from(allTags).sort());
    } catch (error) {
      console.error('Error fetching existing tags:', error);
    }
  };

  const addTag = (tagToAdd: string = newTag) => {
    const tag = tagToAdd.trim();
    if (tag && !tags.includes(tag)) {
      onTagsChange([...tags, tag]);
      
      // Si c'est un nouveau tag (pas dans la liste existante), l'ajouter localement
      if (!existingTags.includes(tag)) {
        setExistingTags(prev => [...prev, tag].sort());
      }
      
      setNewTag("");
      setOpen(false);
    }
  };

  const removeTag = (tagToRemove: string) => {
    onTagsChange(tags.filter(tag => tag !== tagToRemove));
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      addTag();
    }
  };

  // Filter existing tags to show only those not already added
  const availableTags = existingTags.filter(tag => !tags.includes(tag));

  return (
    <div>
      <Label>Tags</Label>
      <div className="flex space-x-2 mb-2">
        <Input
          value={newTag}
          onChange={(e) => setNewTag(e.target.value)}
          placeholder="Ajouter un nouveau tag"
          onKeyPress={handleKeyPress}
          className="flex-1"
        />
        <Button type="button" onClick={() => addTag()} size="sm">
          <Plus className="h-4 w-4" />
        </Button>
        <Popover open={open} onOpenChange={setOpen}>
          <PopoverTrigger asChild>
            <Button 
              type="button" 
              variant="outline" 
              size="sm"
              disabled={availableTags.length === 0}
            >
              <Tags className="h-4 w-4" />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-[300px] p-0" align="start">
            <Command>
              <CommandInput placeholder="Rechercher un tag existant..." />
              <CommandList>
                <CommandEmpty>Aucun tag trouvé.</CommandEmpty>
                <CommandGroup heading="Tags existants">
                  {availableTags.map((tag) => (
                    <CommandItem
                      key={tag}
                      value={tag}
                      onSelect={() => addTag(tag)}
                      className="cursor-pointer"
                    >
                      {tag}
                    </CommandItem>
                  ))}
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>
      </div>
      <div className="flex flex-wrap gap-2">
        {tags.map((tag, index) => (
          <Badge key={index} variant="secondary" className="cursor-pointer">
            {tag}
            <X 
              className="h-3 w-3 ml-1" 
              onClick={() => removeTag(tag)}
            />
          </Badge>
        ))}
      </div>
      {availableTags.length === 0 && existingTags.length > 0 && (
        <p className="text-sm text-gray-500 mt-1">
          Tous les tags existants sont déjà ajoutés à ce projet.
        </p>
      )}
    </div>
  );
};

export default ProjectTagsManager;
