"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, CardFooter } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import { 
  ArrowLeft,
  Loader2,
  Wand2,
  Save,
  RefreshCw
} 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 AutoCreateGroupsPage() {
  const params = useParams();
  const router = useRouter();
  const projectId = params.id as string;

  const [project, setProject] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [generating, setGenerating] = useState(false);
  const [saving, setSaving] = useState(false);

  // State for auto-generation parameters
  const [numberOfGroups, setNumberOfGroups] = useState(4);
  const [balanceTags, setBalanceTags] = useState(true);
  const [balanceLevels, setBalanceLevels] = useState(true);
  const [groups, setGroups] = useState<Group[]>([]);
  const [availableTags, setAvailableTags] = useState<string[]>([]);
  const [availableLevels, setAvailableLevels] = useState<string[]>([]);

  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);

        // Extract unique tags and levels
        const tags = new Set<string>();
        const levels = new Set<string>();

        data.persons.forEach(person => {
          person.tags.forEach(tag => {
            // Assuming the last tag is the level (Junior, Medior, Senior)
            if (["Junior", "Medior", "Senior"].includes(tag)) {
              levels.add(tag);
            } else {
              tags.add(tag);
            }
          });
        });

        setAvailableTags(Array.from(tags));
        setAvailableLevels(Array.from(levels));

      } catch (error) {
        console.error("Error fetching project:", error);
        toast.error("Erreur lors du chargement du projet");
      } finally {
        setLoading(false);
      }
    };

    fetchProject();
  }, [projectId]);

  const generateGroups = async () => {
    if (!project) return;

    setGenerating(true);
    try {
      // In a real app, this would be an API call to the backend
      // which would run the algorithm to create balanced groups
      await new Promise(resolve => setTimeout(resolve, 1500));

      // Simple algorithm to create balanced groups
      const persons = [...project.persons];
      const newGroups: Group[] = [];

      // Create empty groups
      for (let i = 0; i < numberOfGroups; i++) {
        newGroups.push({
          id: i + 1,
          name: `Groupe ${String.fromCharCode(65 + i)}`, // A, B, C, ...
          persons: []
        });
      }

      // Sort persons by level if balancing levels
      if (balanceLevels) {
        persons.sort((a, b) => {
          const aLevel = a.tags.find((tag: string) => ["Junior", "Medior", "Senior"].includes(tag)) || "";
          const bLevel = b.tags.find((tag: string) => ["Junior", "Medior", "Senior"].includes(tag)) || "";

          // Order: Senior, Medior, Junior
          const levelOrder: Record<string, number> = { "Senior": 0, "Medior": 1, "Junior": 2 };
          return levelOrder[aLevel] - levelOrder[bLevel];
        });
      }

      // Sort persons by tags if balancing tags
      if (balanceTags) {
        // Group persons by their primary skill tag
        const personsByTag: Record<string, Person[]> = {};

        persons.forEach(person => {
          // Get first tag that's not a level
          const primaryTag = person.tags.find((tag: string) => !["Junior", "Medior", "Senior"].includes(tag));
          if (primaryTag) {
            if (!personsByTag[primaryTag]) {
              personsByTag[primaryTag] = [];
            }
            personsByTag[primaryTag].push(person);
          }
        });

        // Distribute persons from each tag group evenly
        let currentGroupIndex = 0;

        Object.values(personsByTag).forEach(tagPersons => {
          tagPersons.forEach(person => {
            newGroups[currentGroupIndex].persons.push(person);
            currentGroupIndex = (currentGroupIndex + 1) % numberOfGroups;
          });
        });
      } else {
        // Simple distribution without balancing tags
        persons.forEach((person, index) => {
          const groupIndex = index % numberOfGroups;
          newGroups[groupIndex].persons.push(person);
        });
      }

      setGroups(newGroups);
      toast.success("Groupes générés avec succès");
    } catch (error) {
      console.error("Error generating groups:", error);
      toast.error("Erreur lors de la génération des groupes");
    } finally {
      setGenerating(false);
    }
  };

  const handleSaveGroups = async () => {
    if (groups.length === 0) {
      toast.error("Veuillez d'abord générer des groupes");
      return;
    }

    setSaving(true);
    try {
      // 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">Assistant de création de 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]">
        {/* Parameters */}
        <Card>
          <CardHeader>
            <CardTitle>Paramètres</CardTitle>
            <CardDescription>
              Configurez les paramètres pour la génération automatique de groupes
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-2">
              <Label htmlFor="number-of-groups">Nombre de groupes: {numberOfGroups}</Label>
              <Slider
                id="number-of-groups"
                min={2}
                max={Math.min(8, Math.floor(project.persons.length / 2))}
                step={1}
                value={[numberOfGroups]}
                onValueChange={(value) => setNumberOfGroups(value[0])}
              />
              <p className="text-xs text-muted-foreground">
                {Math.ceil(project.persons.length / numberOfGroups)} personnes par groupe en moyenne
              </p>
            </div>

            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label htmlFor="balance-tags">Équilibrer les compétences</Label>
                  <p className="text-xs text-muted-foreground">
                    Répartir équitablement les compétences dans chaque groupe
                  </p>
                </div>
                <Switch
                  id="balance-tags"
                  checked={balanceTags}
                  onCheckedChange={setBalanceTags}
                />
              </div>

              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label htmlFor="balance-levels">Équilibrer les niveaux</Label>
                  <p className="text-xs text-muted-foreground">
                    Répartir équitablement les niveaux (Junior, Medior, Senior) dans chaque groupe
                  </p>
                </div>
                <Switch
                  id="balance-levels"
                  checked={balanceLevels}
                  onCheckedChange={setBalanceLevels}
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label>Compétences disponibles</Label>
              <div className="flex flex-wrap gap-1">
                {availableTags.map((tag, index) => (
                  <Badge key={index} variant="outline">
                    {tag}
                  </Badge>
                ))}
              </div>
            </div>

            <div className="space-y-2">
              <Label>Niveaux disponibles</Label>
              <div className="flex flex-wrap gap-1">
                {availableLevels.map((level, index) => (
                  <Badge key={index} variant="outline">
                    {level}
                  </Badge>
                ))}
              </div>
            </div>
          </CardContent>
          <CardFooter>
            <Button 
              onClick={generateGroups} 
              disabled={generating} 
              className="w-full"
            >
              {generating ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Génération en cours...
                </>
              ) : (
                <>
                  <Wand2 className="mr-2 h-4 w-4" />
                  Générer les groupes
                </>
              )}
            </Button>
          </CardFooter>
        </Card>

        {/* Generated Groups */}
        <div className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Groupes générés</CardTitle>
              <CardDescription>
                {groups.length > 0 
                  ? `${groups.length} groupes avec ${project.persons.length} personnes au total` 
                  : "Utilisez les paramètres à gauche pour générer des groupes"}
              </CardDescription>
            </CardHeader>
            <CardContent>
              {groups.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-8">
                  <Wand2 className="h-12 w-12 text-muted-foreground mb-4" />
                  <p className="text-center text-muted-foreground">
                    Aucun groupe généré. Cliquez sur "Générer les groupes" pour commencer.
                  </p>
                </div>
              ) : (
                <div className="space-y-4">
                  {groups.map((group) => (
                    <Card key={group.id}>
                      <CardHeader className="pb-2">
                        <CardTitle>{group.name}</CardTitle>
                        <CardDescription>
                          {group.persons.length} personnes
                        </CardDescription>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-2">
                          {group.persons.map((person) => (
                            <div key={person.id} className="flex items-center justify-between border-b pb-2 last:border-0 last:pb-0">
                              <div>
                                <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>
                            </div>
                          ))}
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              )}
            </CardContent>
            {groups.length > 0 && (
              <CardFooter>
                <Button 
                  variant="outline" 
                  onClick={generateGroups} 
                  disabled={generating} 
                  className="w-full"
                >
                  <RefreshCw className="mr-2 h-4 w-4" />
                  Régénérer les groupes
                </Button>
              </CardFooter>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}
