import { createFileRoute, Navigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useRole } from "@/lib/use-role";
import { useT } from "@/lib/i18n";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Shield, UserCog } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/users")({
  component: UsersPage,
});

type Row = { user_id: string; role: "super_admin" | "salesman"; email?: string | null };

function UsersPage() {
  const { t } = useT();
  const { isAdmin, loading } = useRole();
  const [rows, setRows] = useState<Row[]>([]);
  const [busy, setBusy] = useState(false);

  const load = async () => {
    const { data, error } = await supabase
      .from("user_roles" as any)
      .select("user_id, role")
      .order("role", { ascending: true });
    if (error) { toast.error(error.message); return; }
    setRows((data as any) || []);
  };

  useEffect(() => { if (isAdmin) load(); }, [isAdmin]);

  if (loading) return <div className="p-8 text-muted-foreground">…</div>;
  if (!isAdmin) return <Navigate to="/" />;

  const setRole = async (user_id: string, role: "super_admin" | "salesman") => {
    setBusy(true);
    // delete existing then insert new (keeps single-role semantics)
    await supabase.from("user_roles" as any).delete().eq("user_id", user_id);
    const { error } = await supabase.from("user_roles" as any).insert({ user_id, role });
    setBusy(false);
    if (error) { toast.error(error.message); return; }
    toast.success(t("saved"));
    load();
  };

  return (
    <div className="space-y-6 max-w-4xl">
      <div className="flex items-center gap-3">
        <div className="size-10 rounded-xl gradient-primary grid place-items-center shadow-glow">
          <UserCog className="size-5 text-white" />
        </div>
        <div>
          <h1 className="text-2xl font-extrabold">{t("users")}</h1>
          <p className="text-sm text-muted-foreground">Manage user roles and permissions</p>
        </div>
      </div>

      <Card className="p-0 overflow-hidden">
        <div className="grid grid-cols-[1fr_auto_auto] gap-4 px-4 py-3 border-b bg-muted/40 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
          <div>User ID</div>
          <div>{t("role")}</div>
          <div>{t("actions")}</div>
        </div>
        {rows.length === 0 && <div className="p-8 text-center text-muted-foreground">{t("no_data")}</div>}
        {rows.map((r) => (
          <div key={r.user_id} className="grid grid-cols-[1fr_auto_auto] gap-4 px-4 py-3 border-b items-center">
            <div className="font-mono text-xs truncate flex items-center gap-2">
              {r.role === "super_admin" && <Shield className="size-3.5 text-primary" />}
              {r.user_id}
            </div>
            <div>
              <span className={`px-2 py-1 rounded-md text-xs font-semibold ${r.role === "super_admin" ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"}`}>
                {t(r.role as any)}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <Select value={r.role} onValueChange={(v) => setRole(r.user_id, v as any)}>
                <SelectTrigger className="w-40 h-8"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="super_admin">{t("super_admin")}</SelectItem>
                  <SelectItem value="salesman">{t("salesman")}</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        ))}
      </Card>

      <Card className="p-4 bg-muted/30">
        <div className="text-sm font-semibold mb-2">Permissions Overview</div>
        <div className="grid md:grid-cols-2 gap-4 text-xs">
          <div>
            <div className="font-semibold text-primary mb-1">{t("super_admin")}</div>
            <ul className="list-disc pl-4 text-muted-foreground space-y-0.5">
              <li>Full access to all modules</li>
              <li>Manage users & roles</li>
              <li>Purchases, Suppliers, Expenses, Reports</li>
              <li>Categories & Brands</li>
            </ul>
          </div>
          <div>
            <div className="font-semibold mb-1">{t("salesman")}</div>
            <ul className="list-disc pl-4 text-muted-foreground space-y-0.5">
              <li>Dashboard</li>
              <li>POS / New Sale</li>
              <li>Sales list</li>
              <li>Customers & Products (view)</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  );
}
