"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Plus, X, Link as LinkIcon, Loader2 } from "lucide-react";
import { skillsClient } from "@/clients";

interface CreateSkillFormProps {
  categoryName: string;
  onSuccess: (skillId: string) => void;
  onCancel: () => void;
}

export function CreateSkillForm({
  categoryName,
  onSuccess,
  onCancel,
}: CreateSkillFormProps) {
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    icon: "",
    links: [""],
  });
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");

  const addLink = () => {
    setFormData((prev) => ({
      ...prev,
      links: [...prev.links, ""],
    }));
  };

  const removeLink = (index: number) => {
    setFormData((prev) => ({
      ...prev,
      links: prev.links.filter((_, i) => i !== index),
    }));
  };

  const updateLink = (index: number, value: string) => {
    setFormData((prev) => ({
      ...prev,
      links: prev.links.map((link, i) => (i === index ? value : link)),
    }));
  };

  const generateSkillId = (name: string) => {
    return name
      .toLowerCase()
      .replace(/[^a-z0-9\s]/g, "")
      .replace(/\s+/g, "-")
      .trim();
  };

  const getCategoryId = (categoryName: string) => {
    // Convertir le nom de catégorie en ID (ex: "Cloud" -> "cloud")
    return categoryName.toLowerCase();
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setIsLoading(true);

    try {
      // Validation
      if (!formData.name.trim()) {
        throw new Error("Le nom de la compétence est requis");
      }
      if (!formData.description.trim()) {
        throw new Error("La description est requise");
      }

      const skillId = generateSkillId(formData.name);
      const categoryId = getCategoryId(categoryName);

      // Filtrer les liens vides
      const validLinks = formData.links.filter((link) => link.trim());

      const skillData = {
        id: skillId,
        name: formData.name.trim(),
        description: formData.description.trim(),
        icon: formData.icon.trim() || "fas-cog",
        links: validLinks,
      };

      const success = await skillsClient.createSkill(categoryId, skillData);

      if (success) {
        onSuccess(skillId);
      } else {
        throw new Error("Erreur lors de la création de la compétence");
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Une erreur est survenue");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && (
        <div className="p-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded-md">
          {error}
        </div>
      )}

      <div className="space-y-2">
        <Label htmlFor="skill-name">Nom de la compétence *</Label>
        <Input
          id="skill-name"
          placeholder="ex: Next.js, Docker, Figma..."
          value={formData.name}
          onChange={(e) =>
            setFormData((prev) => ({ ...prev, name: e.target.value }))
          }
          disabled={isLoading}
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="skill-description">Description *</Label>
        <Textarea
          id="skill-description"
          placeholder="Décrivez brièvement cette compétence..."
          value={formData.description}
          onChange={(e) =>
            setFormData((prev) => ({ ...prev, description: e.target.value }))
          }
          disabled={isLoading}
          rows={3}
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="skill-icon">Icône (optionnel)</Label>
        <Input
          id="skill-icon"
          placeholder="ex: fab-react, fas-database..."
          value={formData.icon}
          onChange={(e) =>
            setFormData((prev) => ({ ...prev, icon: e.target.value }))
          }
          disabled={isLoading}
        />
        <p className="text-xs text-muted-foreground">
          Utilisez les classes FontAwesome (fab-, fas-, far-) ou laissez vide
          pour l'icône par défaut
        </p>
      </div>

      <div className="space-y-2">
        <Label>Liens de référence (optionnel)</Label>
        {formData.links.map((link, index) => (
          <div key={index} className="flex gap-2">
            <div className="relative flex-1">
              <LinkIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="https://..."
                value={link}
                onChange={(e) => updateLink(index, e.target.value)}
                disabled={isLoading}
                className="pl-10"
              />
            </div>
            {formData.links.length > 1 && (
              <Button
                type="button"
                variant="outline"
                size="icon"
                onClick={() => removeLink(index)}
                disabled={isLoading}
              >
                <X className="h-4 w-4" />
              </Button>
            )}
          </div>
        ))}
        {formData.links.length < 5 && (
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={addLink}
            disabled={isLoading}
            className="gap-2"
          >
            <Plus className="h-3 w-3" />
            Ajouter un lien
          </Button>
        )}
      </div>

      <div className="flex gap-3 pt-4">
        <Button type="submit" disabled={isLoading} className="flex-1">
          {isLoading ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Création...
            </>
          ) : (
            <>
              <Plus className="mr-2 h-4 w-4" />
              Créer la compétence
            </>
          )}
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={onCancel}
          disabled={isLoading}
        >
          Annuler
        </Button>
      </div>
    </form>
  );
}
