"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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Plus, Trash2, Edit, Loader2, Users, AlertCircle } from "lucide-react";
import Link from "next/link";
import { toast } from "sonner";
import type { Database } from "@/lib/supabase";
import { useRouter } from "next/navigation";

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

export default function TrainersPage() {
  const [trainers, setTrainers] = useState<Trainer[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [trainerToDelete, setTrainerToDelete] = useState<Trainer | null>(null);

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

  const fetchTrainers = async () => {
    try {
      setError(null);
      console.log("Fetching trainers...");
      
      const { data, error } = await supabase.from("trainers").select("*").order("name");
      
      console.log("Supabase response:", { data, error });
      
      if (error) {
        console.error("Supabase error:", error);
        throw new Error(error.message || "Database error");
      }
      
      setTrainers(data || []);
    } catch (err) {
      console.error("Failed to fetch trainers:", err);
      const errorMessage = err instanceof Error 
        ? err.message 
        : typeof err === 'object' && err !== null
          ? JSON.stringify(err)
          : "Failed to connect to database";
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const openDeleteDialog = (trainer: Trainer) => {
    setTrainerToDelete(trainer);
    setDeleteDialogOpen(true);
  };

  const handleDelete = async () => {
    if (!trainerToDelete) return;

    setDeletingId(trainerToDelete.id);
    try {
      const { error } = await supabase.from("trainers").delete().eq("id", trainerToDelete.id);
      if (error) throw error;
      setTrainers(trainers.filter((t) => t.id !== trainerToDelete.id));
      toast.success("Trainer deleted", {
        description: "The trainer has been removed successfully."
      });
    } catch (error) {
      console.error("Failed to delete trainer:", error);
      toast.error("Failed to delete trainer");
    } finally {
      setDeletingId(null);
      setDeleteDialogOpen(false);
      setTrainerToDelete(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>
        <Link href="/trainers/new">
          <Button className="bg-orange-500 hover:bg-orange-600">
            <Plus className="w-4 h-4 mr-2" />
            Add Trainer
          </Button>
        </Link>
      </div>

      {loading ? (
        <div className="flex justify-center p-8">
          <Loader2 className="w-8 h-8 animate-spin text-orange-500" />
        </div>
      ) : error ? (
        <div className="flex flex-col items-center justify-center p-12 text-center">
          <div className="w-16 h-16 rounded-full bg-red-500/10 flex items-center justify-center mb-4">
            <AlertCircle className="w-8 h-8 text-red-500" />
          </div>
          <h3 className="text-xl font-semibold text-white mb-2">Failed to Load Trainers</h3>
          <p className="text-neutral-400 mb-2 max-w-md">{error}</p>
          <p className="text-sm text-neutral-500 mb-6">
            Make sure your Supabase database is running and the trainers table exists.
          </p>
          <Button 
            onClick={fetchTrainers}
            variant="outline"
            className="border-neutral-700 text-neutral-300 hover:bg-neutral-800"
          >
            Try Again
          </Button>
        </div>
      ) : trainers.length === 0 ? (
        <div className="flex flex-col items-center justify-center p-12 text-center">
          <div className="w-16 h-16 rounded-full bg-orange-500/10 flex items-center justify-center mb-4">
            <Users className="w-8 h-8 text-orange-500" />
          </div>
          <h3 className="text-xl font-semibold text-white mb-2">No Trainers Yet</h3>
          <p className="text-neutral-400 mb-6 max-w-md">
            Get started by adding your first trainer. Trainers lead workouts and help users achieve their fitness goals.
          </p>
          <Link href="/trainers/new">
            <Button className="bg-orange-500 hover:bg-orange-600">
              <Plus className="w-4 h-4 mr-2" />
              Add First Trainer
            </Button>
          </Link>
        </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">
                    {trainer.avatar_url ? (
                      <img
                        src={trainer.avatar_url}
                        alt={trainer.name}
                        className="w-12 h-12 rounded-full object-cover border-2"
                        style={{ borderColor: trainer.color }}
                      />
                    ) : (
                      <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">
                    <Link href={`/trainers/${trainer.id}/edit`}>
                      <Button variant="ghost" size="icon" className="text-neutral-400 hover:text-white">
                        <Edit className="w-4 h-4" />
                      </Button>
                    </Link>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="text-neutral-400 hover:text-red-500"
                      onClick={() => openDeleteDialog(trainer)}
                      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>
      )}

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent className="bg-neutral-900 border-neutral-800 text-white">
          <DialogHeader>
            <DialogTitle>Delete Trainer</DialogTitle>
            <DialogDescription className="text-neutral-400">
              Are you sure you want to delete {trainerToDelete?.name}? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2">
            <Button
              variant="outline"
              onClick={() => setDeleteDialogOpen(false)}
              className="border-neutral-700 text-neutral-300 hover:bg-neutral-800"
            >
              Cancel
            </Button>
            <Button
              onClick={handleDelete}
              disabled={!!deletingId}
              className="bg-red-500 hover:bg-red-600"
            >
              {deletingId ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Deleting...
                </>
              ) : (
                "Delete"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
