"use client";

import { useState, useEffect, useMemo } from "react";
import { Search, Plus, Loader2, Dumbbell, X } from "lucide-react";
import ExerciseCard from "@/components/exercises/ExerciseCard";
import AddExerciseForm from "@/components/exercises/AddExerciseForm";
import { Exercise } from "@prisma/client";
import { scoreExercise } from "@/lib/exerciseSearch";

export default function ExercisesClient() {
  const [exercises, setExercises] = useState<Exercise[]>([]);
  const [filteredExercises, setFilteredExercises] = useState<Exercise[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedMuscleGroup, setSelectedMuscleGroup] = useState<string | null>(
    null
  );
  const [selectedType, setSelectedType] = useState<string | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);

  // Build filter tags dynamically from all exercises
  const muscleGroups = useMemo(() => {
    const set = new Set<string>();
    for (const ex of exercises) {
      try {
        const groups = JSON.parse(ex.muscleGroups || "[]") as string[];
        groups.forEach((g) => set.add(g.toLowerCase()));
      } catch {}
    }
    return Array.from(set).sort();
  }, [exercises]);

  const equipmentTypes = useMemo(() => {
    const set = new Set<string>();
    for (const ex of exercises) {
      if (ex.type) set.add(ex.type.toLowerCase());
    }
    return Array.from(set).sort();
  }, [exercises]);

  useEffect(() => {
    const fetchExercises = async () => {
      try {
        const response = await fetch("/api/exercises");
        const data = await response.json();
        setExercises(data);
        setFilteredExercises(data);
      } catch (error) {
        console.error("Failed to fetch exercises:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchExercises();
  }, []);

  useEffect(() => {
    let filtered = exercises;

    // Apply muscle group filter
    if (selectedMuscleGroup) {
      filtered = filtered.filter((ex) => {
        try {
          const muscleGroups = JSON.parse(ex.muscleGroups || "[]");
          return muscleGroups.includes(selectedMuscleGroup);
        } catch {
          return false;
        }
      });
    }

    // Apply equipment type filter
    if (selectedType) {
      filtered = filtered.filter(
        (ex) => ex.type?.toLowerCase() === selectedType
      );
    }

    // Apply fuzzy search with abbreviation expansion
    if (searchQuery.trim()) {
      filtered = filtered
        .map((ex) => ({ exercise: ex, score: scoreExercise(searchQuery, ex.name) }))
        .filter((item) => item.score >= 0)
        .sort((a, b) => a.score - b.score)
        .map((item) => item.exercise);
    } else {
      filtered = filtered.sort((a, b) => a.name.localeCompare(b.name));
    }

    setFilteredExercises(filtered);
  }, [searchQuery, selectedMuscleGroup, selectedType, exercises]);

  const handleExerciseAdded = (newExercise: Exercise) => {
    setExercises([...exercises, newExercise]);
    setShowAddForm(false);
  };

  return (
    <div className="max-w-7xl mx-auto px-4 py-6 sm:px-6">
      {/* Controls */}
      <div className="flex flex-col sm:flex-row gap-4 mb-6">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-3 w-5 h-5 text-zinc-500" />
          <input
            type="text"
            placeholder="Search exercises..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-10 pr-10 py-2.5 bg-zinc-900 border border-zinc-800 rounded-lg text-white placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-white/20"
          />
          {searchQuery && (
            <button
              type="button"
              onClick={() => setSearchQuery("")}
              className="absolute right-3 top-3 p-0.5 rounded text-zinc-500 hover:text-white transition-colors"
              aria-label="Clear search"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>
        <button
          onClick={() => setShowAddForm(!showAddForm)}
          className="bg-white hover:bg-zinc-200 text-black font-medium py-2.5 px-4 rounded-lg flex items-center justify-center gap-2 transition"
        >
          <Plus className="w-5 h-5" />
          Add Exercise
        </button>
      </div>

      {/* Add Exercise Form */}
      {showAddForm && (
        <div className="bg-zinc-900 border border-zinc-800 rounded-lg p-6 mb-6">
          <h2 className="text-lg font-bold text-white mb-4">
            Add Custom Exercise
          </h2>
          <AddExerciseForm onExerciseAdded={handleExerciseAdded} />
        </div>
      )}

      {/* Equipment Type Filter */}
      <div className="mb-3 flex flex-wrap gap-2">
        <span className="text-xs text-zinc-600 uppercase tracking-wider self-center mr-1">Equipment</span>
        {equipmentTypes.map((type) => (
          <button
            key={type}
            onClick={() =>
              setSelectedType(selectedType === type ? null : type)
            }
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
              selectedType === type
                ? "bg-white text-black"
                : "bg-zinc-900 text-zinc-400 hover:text-white"
            }`}
          >
            {type.charAt(0).toUpperCase() + type.slice(1)}
          </button>
        ))}
      </div>

      {/* Muscle Group Filter */}
      <div className="mb-6 flex flex-wrap gap-2">
        <span className="text-xs text-zinc-600 uppercase tracking-wider self-center mr-1">Muscle</span>
        {muscleGroups.map((group) => (
          <button
            key={group}
            onClick={() =>
              setSelectedMuscleGroup(
                selectedMuscleGroup === group ? null : group
              )
            }
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
              selectedMuscleGroup === group
                ? "bg-white text-black"
                : "bg-zinc-900 text-zinc-400 hover:text-white"
            }`}
          >
            {group.charAt(0).toUpperCase() + group.slice(1)}
          </button>
        ))}
      </div>

      {/* Grid */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-6 h-6 text-zinc-500 animate-spin" />
        </div>
      ) : filteredExercises.length === 0 ? (
        <div className="bg-zinc-900 border border-zinc-800 rounded-lg p-12 text-center">
          <Dumbbell className="w-12 h-12 text-zinc-700 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-white mb-2">
            No exercises found
          </h3>
          <p className="text-zinc-500">
            {searchQuery || selectedMuscleGroup || selectedType
              ? "Try adjusting your filters"
              : "Add your first exercise to get started"}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredExercises.map((exercise) => (
            <ExerciseCard key={exercise.id} exercise={exercise} />
          ))}
        </div>
      )}
    </div>
  );
}
