"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useForm, Controller } from "react-hook-form";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { 
  ArrowLeft,
  Loader2,
  Save,
  Plus,
  X
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

// Type definitions
interface PersonFormData {
  name: string;
  email: string;
  level: string;
}

// Mock data for available tags
const availableTags = [
  "Frontend", "Backend", "Fullstack", "UX/UI", "DevOps",
  "React", "Vue", "Angular", "Node.js", "Python", "Java", "PHP",
  "JavaScript", "TypeScript", "CSS", "Docker", "Kubernetes", "Design",
  "Figma", "MERN"
];

// Levels
const levels = ["Junior", "Medior", "Senior"];

export default function NewPersonPage() {
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [tagInput, setTagInput] = useState("");
  const [filteredTags, setFilteredTags] = useState<string[]>([]);
  
  const { register, handleSubmit, control, formState: { errors } } = useForm<PersonFormData>({
    defaultValues: {
      name: "",
      email: "",
      level: ""
    }
  });

  // Filter available tags based on input
  useEffect(() => {
    if (tagInput) {
      const filtered = availableTags.filter(
        tag => 
          tag.toLowerCase().includes(tagInput.toLowerCase()) && 
          !selectedTags.includes(tag)
      );
      setFilteredTags(filtered);
    } else {
      setFilteredTags([]);
    }
  }, [tagInput, selectedTags]);

  const handleAddTag = (tag: string) => {
    if (!selectedTags.includes(tag)) {
      setSelectedTags([...selectedTags, tag]);
    }
    setTagInput("");
    setFilteredTags([]);
  };

  const handleRemoveTag = (tag: string) => {
    setSelectedTags(selectedTags.filter(t => t !== tag));
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && tagInput) {
      e.preventDefault();
      if (filteredTags.length > 0) {
        handleAddTag(filteredTags[0]);
      } else if (!selectedTags.includes(tagInput)) {
        // Add as a new tag if it doesn't exist
        handleAddTag(tagInput);
      }
    }
  };

  const onSubmit = async (data: PersonFormData) => {
    if (selectedTags.length === 0) {
      toast.error("Veuillez sélectionner au moins un tag");
      return;
    }

    setIsSubmitting(true);
    try {
      // In a real app, this would be an API call to create a new person
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // Combine form data with selected tags
      const personData = {
        ...data,
        tags: [...selectedTags, data.level]
      };
      
      // Simulate a successful response with a person ID
      const personId = Date.now();
      
      toast.success("Personne créée avec succès");
      router.push("/persons");
    } catch (error) {
      console.error("Error creating person:", error);
      toast.error("Erreur lors de la création de la personne");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-2">
        <Button variant="outline" size="icon" asChild>
          <Link href="/persons">
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <h1 className="text-3xl font-bold">Nouvelle personne</h1>
      </div>

      <Card>
        <form onSubmit={handleSubmit(onSubmit)}>
          <CardHeader>
            <CardTitle>Informations de la personne</CardTitle>
            <CardDescription>
              Ajoutez une nouvelle personne à votre projet
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="name">Nom</Label>
              <Input
                id="name"
                placeholder="Ex: Jean Dupont"
                {...register("name", { 
                  required: "Le nom est requis",
                  minLength: {
                    value: 3,
                    message: "Le nom doit contenir au moins 3 caractères"
                  }
                })}
              />
              {errors.name && (
                <p className="text-sm text-destructive">{errors.name.message}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                type="email"
                placeholder="Ex: jean.dupont@example.com"
                {...register("email", { 
                  required: "L'email est requis",
                  pattern: {
                    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                    message: "Adresse email invalide"
                  }
                })}
              />
              {errors.email && (
                <p className="text-sm text-destructive">{errors.email.message}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="level">Niveau</Label>
              <Controller
                name="level"
                control={control}
                rules={{ required: "Le niveau est requis" }}
                render={({ field }) => (
                  <Select
                    onValueChange={field.onChange}
                    defaultValue={field.value}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Sélectionnez un niveau" />
                    </SelectTrigger>
                    <SelectContent>
                      {levels.map((level) => (
                        <SelectItem key={level} value={level}>
                          {level}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                )}
              />
              {errors.level && (
                <p className="text-sm text-destructive">{errors.level.message}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="tags">Tags</Label>
              <div className="flex flex-wrap gap-1 mb-2">
                {selectedTags.map((tag) => (
                  <Badge key={tag} variant="secondary" className="flex items-center gap-1">
                    {tag}
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="h-4 w-4 p-0 text-muted-foreground hover:text-foreground"
                      onClick={() => handleRemoveTag(tag)}
                    >
                      <X className="h-3 w-3" />
                      <span className="sr-only">Supprimer le tag {tag}</span>
                    </Button>
                  </Badge>
                ))}
              </div>
              <div className="relative">
                <Input
                  id="tags"
                  placeholder="Rechercher ou ajouter un tag..."
                  value={tagInput}
                  onChange={(e) => setTagInput(e.target.value)}
                  onKeyDown={handleKeyDown}
                />
                {filteredTags.length > 0 && (
                  <div className="absolute z-10 mt-1 w-full rounded-md border bg-popover p-2 shadow-md">
                    <div className="max-h-60 overflow-auto">
                      {filteredTags.map((tag) => (
                        <div
                          key={tag}
                          className="flex cursor-pointer items-center rounded-md px-2 py-1.5 hover:bg-muted"
                          onClick={() => handleAddTag(tag)}
                        >
                          <Plus className="mr-2 h-4 w-4" />
                          {tag}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
              <p className="text-xs text-muted-foreground">
                Appuyez sur Entrée pour ajouter un tag ou sélectionnez-en un dans la liste
              </p>
            </div>
          </CardContent>
          <CardFooter className="flex justify-between">
            <Button variant="outline" asChild>
              <Link href="/persons">Annuler</Link>
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Création en cours...
                </>
              ) : (
                <>
                  <Save className="mr-2 h-4 w-4" />
                  Créer la personne
                </>
              )}
            </Button>
          </CardFooter>
        </form>
      </Card>
    </div>
  );
}