"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 { Select } from "@/components/ui/select";
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 WorkoutProgram = Database["public"]["Tables"]["workout_programs"]["Row"];

const BODY_ZONE_OPTIONS = [
  { value: "all", label: "All Zones" },
  { value: "upper-body", label: "Upper Body" },
  { value: "lower-body", label: "Lower Body" },
  { value: "full-body", label: "Full Body" },
]

const LEVEL_OPTIONS = [
  { value: "all", label: "All Levels" },
  { value: "Beginner", label: "Beginner" },
  { value: "Intermediate", label: "Intermediate" },
  { value: "Advanced", label: "Advanced" },
]

export default function ProgramsPage() {
  const router = useRouter();
  const [programs, setPrograms] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [programToDelete, setProgramToDelete] = useState<WorkoutProgram | null>(null);
  const [filterZone, setFilterZone] = useState("all");
  const [filterLevel, setFilterLevel] = useState("all");

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

  const fetchPrograms = async () => {
    try {
      const { data, error } = await (supabase.from("workout_programs") as any)
        .select(`
          *,
          program_tabatas (id)
        `)
        .order("sort_order", { ascending: true });

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

  const openDeleteDialog = (program: WorkoutProgram) => {
    setProgramToDelete(program);
    setDeleteDialogOpen(true);
  };

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

    setDeletingId(programToDelete.id);
    try {
      // Delete tabatas first (foreign key constraint)
      const { error: tabataError } = await (supabase.from("program_tabatas") as any)
        .delete()
        .eq("program_id", programToDelete.id);
      if (tabataError) throw tabataError;

      const { error } = await (supabase.from("workout_programs") as any)
        .delete()
        .eq("id", programToDelete.id);
      if (error) throw error;

      setPrograms(programs.filter((p) => p.id !== programToDelete.id));
      toast.success("Program deleted", {
        description: "The program has been removed successfully."
      });
    } catch (error) {
      console.error("Failed to delete program:", error);
      toast.error("Failed to delete program");
    } finally {
      setDeletingId(null);
      setDeleteDialogOpen(false);
      setProgramToDelete(null);
    }
  };

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

  const getLevelColor = (level: string) => {
    const colors: Record<string, string> = {
      "Beginner": "bg-emerald-500/20 text-emerald-500",
      "Intermediate": "bg-yellow-500/20 text-yellow-500",
      "Advanced": "bg-red-500/20 text-red-500",
    };
    return colors[level] || "bg-neutral-500/20 text-neutral-500";
  };

  const filteredPrograms = programs.filter((p) => {
    if (filterZone !== "all" && p.body_zone !== filterZone) return false;
    if (filterLevel !== "all" && p.level !== filterLevel) return false;
    return true;
  });

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

      {/* Filters */}
      <div className="flex gap-4 mb-6">
        <div className="w-48">
          <Select
            value={filterZone}
            onValueChange={setFilterZone}
            options={BODY_ZONE_OPTIONS}
            placeholder="Filter by zone"
          />
        </div>
        <div className="w-48">
          <Select
            value={filterLevel}
            onValueChange={setFilterLevel}
            options={LEVEL_OPTIONS}
            placeholder="Filter by level"
          />
        </div>
      </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>
          ) : filteredPrograms.length === 0 ? (
            <div className="p-8 text-center text-neutral-500">
              {programs.length === 0
                ? "No programs yet. Create your first program to get started."
                : "No programs match your filters."}
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow className="border-neutral-800">
                  <TableHead className="text-neutral-400">Title</TableHead>
                  <TableHead className="text-neutral-400">Body Zone</TableHead>
                  <TableHead className="text-neutral-400">Level</TableHead>
                  <TableHead className="text-neutral-400">Access</TableHead>
                  <TableHead className="text-neutral-400">Duration</TableHead>
                  <TableHead className="text-neutral-400">Calories</TableHead>
                  <TableHead className="text-neutral-400">Tabatas</TableHead>
                  <TableHead className="text-neutral-400 text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredPrograms.map((program) => (
                  <TableRow
                    key={program.id}
                    className="border-neutral-800 cursor-pointer hover:bg-neutral-800/50 transition-colors"
                    onClick={() => router.push(`/programs/${program.id}`)}
                  >
                    <TableCell className="text-white font-medium">
                      <div className="flex items-center gap-2">
                        {program.accent_color && (
                          <div
                            className="h-3 w-3 rounded-full flex-shrink-0"
                            style={{ backgroundColor: program.accent_color }}
                          />
                        )}
                        {program.title}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={getBodyZoneColor(program.body_zone)}>
                        {program.body_zone}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={getLevelColor(program.level)}>
                        {program.level}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={program.is_free ? "bg-emerald-500/20 text-emerald-500" : "bg-amber-500/20 text-amber-500"}>
                        {program.is_free ? "Free" : "Premium"}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-neutral-300">{program.estimated_duration} min</TableCell>
                    <TableCell className="text-neutral-300">{program.estimated_calories}</TableCell>
                    <TableCell className="text-neutral-300">
                      {program.program_tabatas?.length || 0}
                    </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={`/programs/${program.id}`}>
                            <Eye className="w-4 h-4" />
                          </Link>
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="text-neutral-400 hover:text-white"
                          asChild
                        >
                          <Link href={`/programs/${program.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(program)}
                          disabled={deletingId === program.id}
                        >
                          {deletingId === program.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 Program</DialogTitle>
            <DialogDescription className="text-neutral-400">
              Are you sure you want to delete &quot;{programToDelete?.title}&quot;? This will also delete all associated tabatas. 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>
  );
}
