"use client";

import { useEffect, useState } from "react";
import { AuthGuard } from "@/components/auth/AuthGuard";
import { Navbar } from "@/components/layout/Navbar";
import { BottomNav } from "@/components/layout/BottomNav";
import { Spinner } from "@/components/ui/Spinner";
import { api } from "@/lib/api";

interface Rule {
  value: unknown;
  description: string;
  category: string;
}

const CATEGORY_LABELS: Record<string, string> = {
  rep_floors: "Rep Floors",
  duration: "Duration",
  superset: "Superset Structure",
  coherence: "Workout Coherence",
};

const CATEGORY_ORDER = ["rep_floors", "duration", "superset", "coherence"];

function formatValue(value: unknown): string {
  if (typeof value === "boolean") return value ? "Yes" : "No";
  if (typeof value === "number") return String(value);
  if (typeof value === "string") return value.replace(/_/g, " ");
  return String(value);
}

export default function RulesPage() {
  const [rules, setRules] = useState<Record<string, Rule> | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    async function fetchRules() {
      try {
        const data = await api.getRules();
        setRules(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load rules");
      } finally {
        setLoading(false);
      }
    }
    fetchRules();
  }, []);

  // Group rules by category
  const grouped: Record<string, [string, Rule][]> = {};
  if (rules) {
    for (const [key, rule] of Object.entries(rules)) {
      const cat = rule.category;
      if (!grouped[cat]) grouped[cat] = [];
      grouped[cat].push([key, rule]);
    }
  }

  const sortedCategories = CATEGORY_ORDER.filter((c) => grouped[c]);

  return (
    <AuthGuard>
      <Navbar />
      <BottomNav />
      <main className="pt-20 pb-20 px-4 max-w-3xl mx-auto">
        <h1 className="text-2xl font-bold text-zinc-100 mb-6">
          Generation Rules
        </h1>
        <p className="text-zinc-400 text-sm mb-8">
          These guardrails are enforced during workout generation to ensure
          quality and coherence.
        </p>

        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Spinner size="lg" />
          </div>
        ) : error ? (
          <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-sm">
            {error}
          </div>
        ) : (
          <div className="space-y-6">
            {sortedCategories.map((category) => (
              <div
                key={category}
                className="rounded-xl border border-zinc-800 bg-zinc-900/50 overflow-hidden"
              >
                <div className="px-4 py-3 bg-zinc-800/50 border-b border-zinc-800">
                  <h2 className="text-sm font-semibold text-zinc-200 uppercase tracking-wide">
                    {CATEGORY_LABELS[category] || category}
                  </h2>
                </div>
                <div className="divide-y divide-zinc-800/50">
                  {grouped[category].map(([key, rule]) => (
                    <div
                      key={key}
                      className="px-4 py-3 flex items-center justify-between gap-4"
                    >
                      <div className="min-w-0">
                        <p className="text-sm text-zinc-200">
                          {rule.description}
                        </p>
                        <p className="text-xs text-zinc-500 mt-0.5 font-mono">
                          {key}
                        </p>
                      </div>
                      <span className="shrink-0 text-sm font-medium text-[#39FF14] bg-[#39FF14]/10 px-2.5 py-1 rounded-md">
                        {formatValue(rule.value)}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </main>
    </AuthGuard>
  );
}
