"use client";

import { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, 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";

// Mock project data (same as in the groups page)
const getProjectData = (id: string) => {
  return {
    id: parseInt(id),
    name: "Projet Formation Dev Web",
    description: "Création de groupes pour la formation développement web",
    date: "2025-05-15",
    persons: [
      { id: 1, name: "Jean Dupont", tags: ["Frontend", "React", "Junior"] },
      { id: 2, name: "Marie Martin", tags: ["Backend", "Node.js", "Senior"] },
      { id: 3, name: "Pierre Durand", tags: ["Fullstack", "JavaScript", "Medior"] },
      { id: 4, name: "Sophie Lefebvre", tags: ["UX/UI", "Design", "Senior"] },
      { id: 5, name: "Thomas Bernard", tags: ["Backend", "Java", "Senior"] },
      { id: 6, name: "Julie Petit", tags: ["Frontend", "Vue", "Junior"] },
      { id: 7, name: "Nicolas Moreau", tags: ["DevOps", "Docker", "Medior"] },
      { id: 8, name: "Emma Dubois", tags: ["Frontend", "Angular", "Junior"] },
      { id: 9, name: "Lucas Leroy", tags: ["Backend", "Python", "Medior"] },
      { id: 10, name: "Camille Roux", tags: ["Fullstack", "TypeScript", "Senior"] },
      { id: 11, name: "Hugo Fournier", tags: ["Frontend", "React", "Medior"] },
      { id: 12, name: "Léa Girard", tags: ["UX/UI", "Figma", "Junior"] },
      { id: 13, name: "Mathis Bonnet", tags: ["Backend", "PHP", "Junior"] },
      { id: 14, name: "Chloé Lambert", tags: ["Frontend", "CSS", "Senior"] },
      { id: 15, name: "Nathan Mercier", tags: ["DevOps", "Kubernetes", "Senior"] },
      { id: 16, name: "Zoé Faure", tags: ["Fullstack", "MERN", "Medior"] },
    ]
  };
};

// Type definitions
interface Person {
  id: number;
  name: string;
  tags: string[];
}

interface Group {
  id: number;
  name: string;
  persons: Person[];
}

export default function CreateGroupsPage() {
  const params = useParams();
  const router = useRouter();
  const projectId = params.id as string;
  
  const [project, setProject] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  
  // State for groups and available persons
  const [groups, setGroups] = useState<Group[]>([]);
  const [availablePersons, setAvailablePersons] = useState<Person[]>([]);
  const [newGroupName, setNewGroupName] = useState("");
  
  // State for drag and drop
  const [draggedPerson, setDraggedPerson] = useState<Person | null>(null);
  const [draggedFromGroup, setDraggedFromGroup] = useState<number | null>(null);
  const [dragOverGroup, setDragOverGroup] = useState<number | null>(null);

  useEffect(() => {
    // Simulate API call to fetch project data
    const fetchProject = async () => {
      setLoading(true);
      try {
        // In a real app, this would be an API call
        await new Promise(resolve => setTimeout(resolve, 1000));
        const data = getProjectData(projectId);
        setProject(data);
        setAvailablePersons(data.persons);
      } catch (error) {
        console.error("Error fetching project:", error);
        toast.error("Erreur lors du chargement du projet");
      } finally {
        setLoading(false);
      }
    };

    fetchProject();
  }, [projectId]);

  const handleAddGroup = () => {
    if (!newGroupName.trim()) {
      toast.error("Veuillez entrer un nom de groupe");
      return;
    }

    const newGroup: Group = {
      id: Date.now(), // Use timestamp as temporary ID
      name: newGroupName,
      persons: []
    };

    setGroups([...groups, newGroup]);
    setNewGroupName("");
  };

  const handleRemoveGroup = (groupId: number) => {
    const group = groups.find(g => g.id === groupId);
    if (group) {
      // Return persons from this group to available persons
      setAvailablePersons([...availablePersons, ...group.persons]);
    }
    setGroups(groups.filter(g => g.id !== groupId));
  };

  const handleDragStart = (person: Person, fromGroup: number | null) => {
    setDraggedPerson(person);
    setDraggedFromGroup(fromGroup);
  };

  const handleDragOver = (e: React.DragEvent, toGroup: number | null) => {
    e.preventDefault();
    setDragOverGroup(toGroup);
  };

  const handleDrop = (e: React.DragEvent, toGroup: number | null) => {
    e.preventDefault();
    
    if (!draggedPerson) return;
    
    // Remove person from source
    if (draggedFromGroup === null) {
      // From available persons
      setAvailablePersons(availablePersons.filter(p => p.id !== draggedPerson.id));
    } else {
      // From another group
      const sourceGroup = groups.find(g => g.id === draggedFromGroup);
      if (sourceGroup) {
        const updatedGroups = groups.map(g => {
          if (g.id === draggedFromGroup) {
            return {
              ...g,
              persons: g.persons.filter(p => p.id !== draggedPerson.id)
            };
          }
          return g;
        });
        setGroups(updatedGroups);
      }
    }
    
    // Add person to destination
    if (toGroup === null) {
      // To available persons
      setAvailablePersons([...availablePersons, draggedPerson]);
    } else {
      // To a group
      const updatedGroups = groups.map(g => {
        if (g.id === toGroup) {
          return {
            ...g,
            persons: [...g.persons, draggedPerson]
          };
        }
        return g;
      });
      setGroups(updatedGroups);
    }
    
    // Reset drag state
    setDraggedPerson(null);
    setDraggedFromGroup(null);
    setDragOverGroup(null);
  };

  const handleSaveGroups = async () => {
    setSaving(true);
    try {
      // Validate that all groups have at least one person
      const emptyGroups = groups.filter(g => g.persons.length === 0);
      if (emptyGroups.length > 0) {
        toast.error(`${emptyGroups.length} groupe(s) vide(s). Veuillez ajouter des personnes à tous les groupes.`);
        setSaving(false);
        return;
      }

      // In a real app, this would be an API call to save the groups
      await new Promise(resolve => setTimeout(resolve, 1000));
      toast.success("Groupes enregistrés avec succès");
      
      // Navigate back to the groups page
      router.push(`/projects/${projectId}/groups`);
    } catch (error) {
      console.error("Error saving groups:", error);
      toast.error("Erreur lors de l'enregistrement des groupes");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex h-[50vh] items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!project) {
    return (
      <div className="flex h-[50vh] flex-col items-center justify-center">
        <p className="text-lg font-medium">Projet non trouvé</p>
        <Button asChild className="mt-4">
          <Link href="/projects">Retour aux projets</Link>
        </Button>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Button variant="outline" size="icon" asChild>
            <Link href={`/projects/${projectId}/groups`}>
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <h1 className="text-3xl font-bold">Créer des groupes</h1>
        </div>
        <Button onClick={handleSaveGroups} disabled={saving || groups.length === 0}>
          {saving ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Enregistrement...
            </>
          ) : (
            <>
              <Save className="mr-2 h-4 w-4" />
              Enregistrer les groupes
            </>
          )}
        </Button>
      </div>

      <div className="grid gap-6 md:grid-cols-[1fr_2fr]">
        {/* Available persons */}
        <div 
          className={`border rounded-lg p-4 ${dragOverGroup === null ? 'bg-muted/50' : ''}`}
          onDragOver={(e) => handleDragOver(e, null)}
          onDrop={(e) => handleDrop(e, null)}
        >
          <h2 className="text-xl font-bold mb-4">Personnes disponibles ({availablePersons.length})</h2>
          <div className="space-y-2">
            {availablePersons.map(person => (
              <div 
                key={person.id}
                className="border rounded-md p-3 bg-card cursor-move"
                draggable
                onDragStart={() => handleDragStart(person, null)}
              >
                <p className="font-medium">{person.name}</p>
                <div className="flex flex-wrap gap-1 mt-1">
                  {person.tags.map((tag, index) => (
                    <Badge key={index} variant="outline" className="text-xs">
                      {tag}
                    </Badge>
                  ))}
                </div>
              </div>
            ))}
            {availablePersons.length === 0 && (
              <p className="text-muted-foreground text-center py-4">
                Toutes les personnes ont été assignées à des groupes
              </p>
            )}
          </div>
        </div>

        {/* Groups */}
        <div className="space-y-4">
          {/* Add new group form */}
          <Card>
            <CardHeader>
              <CardTitle>Ajouter un nouveau groupe</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex gap-2">
                <div className="flex-1">
                  <Label htmlFor="group-name" className="sr-only">Nom du groupe</Label>
                  <Input
                    id="group-name"
                    placeholder="Nom du groupe"
                    value={newGroupName}
                    onChange={(e) => setNewGroupName(e.target.value)}
                  />
                </div>
                <Button onClick={handleAddGroup}>
                  <Plus className="h-4 w-4 mr-2" />
                  Ajouter
                </Button>
              </div>
            </CardContent>
          </Card>

          {/* Groups list */}
          {groups.length === 0 ? (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-8">
                <p className="text-muted-foreground text-center mb-4">
                  Aucun groupe créé. Commencez par ajouter un groupe.
                </p>
              </CardContent>
            </Card>
          ) : (
            <div className="space-y-4">
              {groups.map(group => (
                <Card 
                  key={group.id}
                  className={dragOverGroup === group.id ? 'border-primary' : ''}
                  onDragOver={(e) => handleDragOver(e, group.id)}
                  onDrop={(e) => handleDrop(e, group.id)}
                >
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle>{group.name}</CardTitle>
                    <Button 
                      variant="ghost" 
                      size="icon" 
                      onClick={() => handleRemoveGroup(group.id)}
                      className="h-8 w-8 text-destructive"
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2">
                      {group.persons.map(person => (
                        <div 
                          key={person.id}
                          className="border rounded-md p-3 bg-card cursor-move"
                          draggable
                          onDragStart={() => handleDragStart(person, group.id)}
                        >
                          <p className="font-medium">{person.name}</p>
                          <div className="flex flex-wrap gap-1 mt-1">
                            {person.tags.map((tag, index) => (
                              <Badge key={index} variant="outline" className="text-xs">
                                {tag}
                              </Badge>
                            ))}
                          </div>
                        </div>
                      ))}
                      {group.persons.length === 0 && (
                        <div className="border border-dashed rounded-md p-4 text-center text-muted-foreground">
                          Glissez-déposez des personnes ici
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}