import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { supabase } from "@/integrations/supabase/client";
import { adminDeleteUser } from "@/lib/admin.functions";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Trash2, Search } from "lucide-react";
import { toast } from "sonner";

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

type Profile = {
  id: string;
  full_name: string | null;
  username: string | null;
  email: string | null;
  phone: string | null;
  is_active: boolean;
  created_at: string;
};

function UsersPage() {
  const [rows, setRows] = useState<Profile[]>([]);
  const [q, setQ] = useState("");
  const del = useServerFn(adminDeleteUser);

  const load = async () => {
    const { data, error } = await supabase
      .from("profiles")
      .select("id, full_name, username, email, phone, is_active, created_at")
      .order("created_at", { ascending: false });
    if (error) toast.error(error.message);
    else setRows((data ?? []) as Profile[]);
  };
  useEffect(() => { load(); }, []);

  const filtered = rows.filter((r) => {
    const s = q.toLowerCase();
    if (!s) return true;
    return (
      (r.full_name ?? "").toLowerCase().includes(s) ||
      (r.email ?? "").toLowerCase().includes(s) ||
      (r.phone ?? "").toLowerCase().includes(s) ||
      (r.username ?? "").toLowerCase().includes(s)
    );
  });

  const toggleActive = async (u: Profile) => {
    const { error } = await supabase.from("profiles").update({ is_active: !u.is_active }).eq("id", u.id);
    if (error) return toast.error(error.message);
    setRows((rs) => rs.map((r) => (r.id === u.id ? { ...r, is_active: !u.is_active } : r)));
  };

  const removeUser = async (u: Profile) => {
    if (!confirm(`Delete ${u.full_name ?? u.email}? This cannot be undone.`)) return;
    try {
      await del({ data: { userId: u.id } });
      setRows((rs) => rs.filter((r) => r.id !== u.id));
      toast.success("User deleted");
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Failed to delete");
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Users</h1>
        <p className="text-sm text-muted-foreground">Manage registered customers.</p>
      </div>
      <Card className="glass">
        <CardHeader>
          <div className="flex items-center gap-2">
            <Search className="h-4 w-4 text-muted-foreground" />
            <Input placeholder="Search by name, email, phone or username" value={q} onChange={(e) => setQ(e.target.value)} />
          </div>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="text-left text-xs uppercase text-muted-foreground">
                <tr>
                  <th className="py-2 pr-4">Name</th>
                  <th className="py-2 pr-4">Email</th>
                  <th className="py-2 pr-4">Phone</th>
                  <th className="py-2 pr-4">Joined</th>
                  <th className="py-2 pr-4">Active</th>
                  <th className="py-2 pr-4"></th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((u) => (
                  <tr key={u.id} className="border-t">
                    <td className="py-2 pr-4">
                      <div className="font-medium">{u.full_name ?? "—"}</div>
                      <div className="text-xs text-muted-foreground">@{u.username ?? "—"}</div>
                    </td>
                    <td className="py-2 pr-4">{u.email ?? "—"}</td>
                    <td className="py-2 pr-4">{u.phone ?? "—"}</td>
                    <td className="py-2 pr-4">{new Date(u.created_at).toLocaleDateString()}</td>
                    <td className="py-2 pr-4">
                      <Switch checked={u.is_active} onCheckedChange={() => toggleActive(u)} />
                    </td>
                    <td className="py-2 pr-4 text-right">
                      <Button variant="ghost" size="icon" onClick={() => removeUser(u)}>
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 && (
                  <tr><td colSpan={6} className="py-8 text-center text-sm text-muted-foreground">No users.</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}