"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Plus, Search } from "lucide-react";
import { SkillCategory, CategoryEvaluation } from "@/lib/types";
import { TechIcon } from "./icons/tech-icon";

interface SkillSelectorProps {
  categories: SkillCategory[];
  evaluations: CategoryEvaluation[];
  selectedCategory: string;
  onAddSkill: (category: string, skillId: string) => void;
  onRemoveSkill: (category: string, skillId: string) => void;
}

export function SkillSelector({
  categories,
  evaluations,
  selectedCategory,
  onAddSkill,
  onRemoveSkill,
}: SkillSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");

  const currentCategory = categories.find(
    (cat) => cat.category === selectedCategory
  );
  const currentEvaluation = evaluations.find(
    (evaluation) => evaluation.category === selectedCategory
  );

  if (!currentCategory) return null;

  const selectedSkillIds = currentEvaluation?.selectedSkillIds || [];

  const filteredSkills = currentCategory.skills.filter(
    (skill) =>
      skill.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      skill.description.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const availableSkills = filteredSkills.filter(
    (skill) => !selectedSkillIds.includes(skill.id)
  );

  const selectedSkills = currentCategory.skills.filter((skill) =>
    selectedSkillIds.includes(skill.id)
  );

  return (
    <div className="space-y-4">
      {/* Selected Skills */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <h4 className="text-lg font-medium">Mes compétences sélectionnées</h4>
          <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogTrigger asChild>
              <Button
                size="sm"
                className="gap-2 bg-blue-500 hover:bg-blue-600 text-white shadow-lg"
              >
                <Plus className="h-4 w-4" />
                Ajouter une compétence
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-2xl">
              <DialogHeader>
                <DialogTitle>
                  Ajouter des compétences - {selectedCategory}
                </DialogTitle>
                <DialogDescription>
                  Choisissez les compétences que vous souhaitez évaluer dans
                  cette catégorie.
                </DialogDescription>
              </DialogHeader>

              <div className="space-y-4">
                {/* Search */}
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="Rechercher une compétence..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>

                {/* Available Skills Grid */}
                <div className="max-h-96 overflow-y-auto">
                  <div className="grid gap-2">
                    {availableSkills.length > 0 ? (
                      availableSkills.map((skill) => (
                        <div
                          key={skill.id}
                          className="flex items-center justify-between p-3 border rounded-lg hover:bg-muted/30 transition-colors"
                        >
                          <div className="flex items-center gap-3">
                            <div className="w-8 h-8 rounded bg-muted flex items-center justify-center">
                              <TechIcon
                                iconName={skill.icon}
                                className="w-5 h-5 text-foreground"
                                fallbackText={skill.name}
                              />
                            </div>
                            <div>
                              <h5 className="font-medium">{skill.name}</h5>
                              <p className="text-sm text-muted-foreground line-clamp-1">
                                {skill.description}
                              </p>
                            </div>
                          </div>
                          <Button
                            size="sm"
                            onClick={() => {
                              onAddSkill(selectedCategory, skill.id);
                            }}
                            className="gap-2"
                          >
                            <Plus className="h-3 w-3" />
                            Ajouter
                          </Button>
                        </div>
                      ))
                    ) : (
                      <div className="text-center py-8 text-muted-foreground">
                        {searchTerm
                          ? "Aucune compétence trouvée"
                          : "Toutes les compétences ont été ajoutées"}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>

        {selectedSkills.length > 0 ? (
          <div className="bg-muted/30 rounded-lg p-4">
            <div className="flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                {selectedSkills.length} compétence
                {selectedSkills.length > 1 ? "s" : ""} sélectionnée
                {selectedSkills.length > 1 ? "s" : ""}
              </p>
              <div className="text-xs text-muted-foreground">
                Supprimez directement depuis les lignes ci-dessous
              </div>
            </div>
          </div>
        ) : (
          <div className="text-center py-8 text-muted-foreground border-2 border-dashed border-muted rounded-lg">
            <p className="mb-2">Aucune compétence sélectionnée</p>
            <p className="text-sm">
              Cliquez sur "Ajouter une compétence" pour commencer
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
