"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { supabase } from "@/lib/supabase";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Plus, Trash2, Edit, Loader2, Eye } from "lucide-react";
import { toast } from "sonner";
import type { Database } from "@/lib/supabase";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

type Workout = Database["public"]["Tables"]["workouts"]["Row"];

export default function WorkoutsPage() {
  const router = useRouter();
  const [workouts, setWorkouts] = useState<Workout[]>([]);
  const [loading, setLoading] = useState(true);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [workoutToDelete, setWorkoutToDelete] = useState<Workout | null>(null);

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

  const fetchWorkouts = async () => {
    try {
      const { data, error } = await supabase
        .from("workouts")
        .select("*")
        .order("created_at", { ascending: false });

      if (error) throw error;
      setWorkouts(data || []);
    } catch (error) {
      console.error("Failed to fetch workouts:", error);
    } finally {
      setLoading(false);
    }
  };

  const openDeleteDialog = (workout: Workout) => {
    setWorkoutToDelete(workout);
    setDeleteDialogOpen(true);
  };

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

    setDeletingId(workoutToDelete.id);
    try {
      const { error } = await supabase.from("workouts").delete().eq("id", workoutToDelete.id);
      if (error) throw error;
      setWorkouts(workouts.filter((w) => w.id !== workoutToDelete.id));
      toast.success("Workout deleted", {
        description: "The workout has been removed successfully."
      });
    } catch (error) {
      console.error("Failed to delete workout:", error);
      toast.error("Failed to delete workout");
    } finally {
      setDeletingId(null);
      setDeleteDialogOpen(false);
      setWorkoutToDelete(null);
    }
  };

  const getCategoryColor = (category: string) => {
    const colors: Record<string, string> = {
      "full-body": "bg-orange-500/20 text-orange-500",
      core: "bg-blue-500/20 text-blue-500",
      "upper-body": "bg-green-500/20 text-green-500",
      "lower-body": "bg-purple-500/20 text-purple-500",
      cardio: "bg-red-500/20 text-red-500",
    };
    return colors[category] || "bg-neutral-500/20 text-neutral-500";
  };

  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">Workouts</h1>
          <p className="text-neutral-400">Manage your workout library</p>
        </div>
        <Button className="bg-orange-500 hover:bg-orange-600" asChild>
          <Link href="/workouts/new">
            <Plus className="w-4 h-4 mr-2" />
            Add Workout
          </Link>
        </Button>
      </div>

      <Card className="bg-neutral-900 border-neutral-800">
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 flex justify-center">
              <Loader2 className="w-8 h-8 animate-spin text-orange-500" />
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow className="border-neutral-800">
                  <TableHead className="text-neutral-400">Title</TableHead>
                  <TableHead className="text-neutral-400">Category</TableHead>
                  <TableHead className="text-neutral-400">Level</TableHead>
                  <TableHead className="text-neutral-400">Duration</TableHead>
                  <TableHead className="text-neutral-400">Rounds</TableHead>
                  <TableHead className="text-neutral-400 text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {workouts.map((workout) => (
                  <TableRow
                    key={workout.id}
                    className="border-neutral-800 cursor-pointer hover:bg-neutral-800/50 transition-colors"
                    onClick={() => router.push(`/workouts/${workout.id}`)}
                  >
                    <TableCell className="text-white font-medium">
                      {workout.title}
                      {workout.is_featured && (
                        <Badge className="ml-2 bg-orange-500/20 text-orange-500">
                          Featured
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge className={getCategoryColor(workout.category)}>
                        {workout.category}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-neutral-300">{workout.level}</TableCell>
                    <TableCell className="text-neutral-300">{workout.duration} min</TableCell>
                    <TableCell className="text-neutral-300">{workout.rounds}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2" onClick={(e) => e.stopPropagation()}>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="text-neutral-400 hover:text-white"
                          asChild
                        >
                          <Link href={`/workouts/${workout.id}`}>
                            <Eye className="w-4 h-4" />
                          </Link>
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="text-neutral-400 hover:text-white"
                          asChild
                        >
                          <Link href={`/workouts/${workout.id}/edit`}>
                            <Edit className="w-4 h-4" />
                          </Link>
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="text-neutral-400 hover:text-red-500"
                          onClick={() => openDeleteDialog(workout)}
                          disabled={deletingId === workout.id}
                        >
                          {deletingId === workout.id ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Trash2 className="w-4 h-4" />
                          )}
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent className="bg-neutral-900 border-neutral-800 text-white">
          <DialogHeader>
            <DialogTitle>Delete Workout</DialogTitle>
            <DialogDescription className="text-neutral-400">
              Are you sure you want to delete "{workoutToDelete?.title}"? 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>
  );
}
