"use client";

import { useEffect, useState } from "react";
import { supabase } from "@/lib/supabase";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Plus, Trash2, Edit, Loader2 } from "lucide-react";
import type { Database } from "@/lib/supabase";

type Trainer = Database["public"]["Tables"]["trainers"]["Row"];

export default function TrainersPage() {
  const [trainers, setTrainers] = useState<Trainer[]>([]);
  const [loading, setLoading] = useState(true);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  useEffect(() => {
    fetchTrainers();
  }, []);

  const fetchTrainers = async () => {
    try {
      const { data, error } = await supabase.from("trainers").select("*");
      if (error) throw error;
      setTrainers(data || []);
    } catch (error) {
      console.error("Failed to fetch trainers:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Are you sure you want to delete this trainer?")) return;

    setDeletingId(id);
    try {
      const { error } = await supabase.from("trainers").delete().eq("id", id);
      if (error) throw error;
      setTrainers(trainers.filter((t) => t.id !== id));
    } catch (error) {
      console.error("Failed to delete trainer:", error);
      alert("Failed to delete trainer");
    } finally {
      setDeletingId(null);
    }
  };

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-8">
        <div>
          <h1 className="text-3xl font-bold text-white mb-2">Trainers</h1>
          <p className="text-neutral-400">Manage your fitness trainers</p>
        </div>
        <Button className="bg-orange-500 hover:bg-orange-600">
          <Plus className="w-4 h-4 mr-2" />
          Add Trainer
        </Button>
      </div>

      {loading ? (
        <div className="flex justify-center p-8">
          <Loader2 className="w-8 h-8 animate-spin text-orange-500" />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {trainers.map((trainer) => (
            <Card key={trainer.id} className="bg-neutral-900 border-neutral-800">
              <CardContent className="p-6">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-4">
                    <div
                      className="w-12 h-12 rounded-full flex items-center justify-center text-white font-bold"
                      style={{ backgroundColor: trainer.color }}
                    >
                      {trainer.name[0]}
                    </div>
                    <div>
                      <h3 className="text-lg font-semibold text-white">{trainer.name}</h3>
                      <p className="text-neutral-400">{trainer.specialty}</p>
                      <p className="text-sm text-neutral-500">
                        {trainer.workout_count} workouts
                      </p>
                    </div>
                  </div>
                  
                  <div className="flex gap-2">
                    <Button variant="ghost" size="icon" className="text-neutral-400 hover:text-white">
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="text-neutral-400 hover:text-red-500"
                      onClick={() => handleDelete(trainer.id)}
                      disabled={deletingId === trainer.id}
                    >
                      {deletingId === trainer.id ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Trash2 className="w-4 h-4" />
                      )}
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
