import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { supabase } from "@/integrations/supabase/client";
import type { Tables } from "@/integrations/supabase/types";
import { dt, errMsg, inr, TX_LABEL } from "@/lib/app";

type P = Tables<"profiles">;

export function AdminUsers() {
  const qc = useQueryClient();
  const [q, setQ] = useState("");
  const [sel, setSel] = useState<P | null>(null);
  const { data: users } = useQuery({ queryKey: ["admin-users"], queryFn: async () => (await supabase.from("profiles").select("*").order("created_at", { ascending: false })).data ?? [] });
  const list = (users ?? []).filter((u) => !q || [u.full_name, u.mobile, u.user_code].some((v) => v.toLowerCase().includes(q.toLowerCase())));
  return (
    <div>
      <h1 className="mb-4 text-2xl font-bold">Users</h1>
      <Input placeholder="Search name, mobile or ID" value={q} onChange={(e) => setQ(e.target.value)} className="mb-4 max-w-sm" />
      <div className="glass-card overflow-x-auto">
        <table className="w-full text-sm">
          <thead className="text-left text-xs text-muted-foreground"><tr>{["Name", "ID", "Mobile", "Balance", "Status", "Joined", ""].map((h) => <th key={h} className="p-3">{h}</th>)}</tr></thead>
          <tbody className="divide-y divide-border">
            {list.map((u) => (
              <tr key={u.id}>
                <td className="p-3 font-semibold">{u.full_name}</td><td className="p-3">{u.user_code}</td><td className="p-3">{u.mobile}</td><td className="p-3 text-primary">{inr(u.balance)}</td>
                <td className="p-3">{u.is_blocked ? <span className="text-destructive">Blocked</span> : !u.is_active ? <span className="text-warning">Inactive</span> : <span className="text-success">Active</span>}</td>
                <td className="p-3 text-xs text-muted-foreground">{dt(u.created_at)}</td>
                <td className="p-3"><Button size="sm" variant="secondary" onClick={() => setSel(u)}>Manage</Button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {sel && <UserDialog user={sel} onClose={() => { setSel(null); qc.invalidateQueries(); }} />}
    </div>
  );
}

function UserDialog({ user, onClose }: { user: P; onClose: () => void }) {
  const [name, setName] = useState(user.full_name);
  const [mobile, setMobile] = useState(user.mobile);
  const [blocked, setBlocked] = useState(user.is_blocked);
  const [active, setActive] = useState(user.is_active);
  const [amt, setAmt] = useState("");
  const [kind, setKind] = useState("admin_credit");
  const [reason, setReason] = useState("");
  const { data: tx, refetch } = useQuery({ queryKey: ["admin-user-tx", user.id], queryFn: async () => (await supabase.from("transactions").select("*").eq("user_id", user.id).order("created_at", { ascending: false }).limit(50)).data ?? [] });

  async function save() {
    const { error } = await supabase.rpc("admin_update_user", { _user: user.id, _name: name, _mobile: mobile, _blocked: blocked, _active: active });
    if (error) return void toast.error(errMsg(error));
    toast.success("User updated");
  }
  async function adjust() {
    let a = Number(amt);
    if (!a) return void toast.error("Enter amount");
    if (!reason.trim()) return void toast.error("Reason is required");
    if (kind === "admin_debit") a = -Math.abs(a);
    const { error } = await supabase.rpc("admin_adjust_balance", { _user: user.id, _amount: a, _kind: kind, _reason: reason });
    if (error) return void toast.error(errMsg(error));
    toast.success("Balance updated");
    setAmt(""); setReason(""); refetch();
  }
  return (
    <Dialog open onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-h-[90vh] max-w-lg overflow-y-auto">
        <DialogHeader><DialogTitle>Manage {user.full_name}</DialogTitle></DialogHeader>
        <div className="space-y-3">
          <div className="grid grid-cols-2 gap-3"><div className="space-y-1"><Label>Name</Label><Input value={name} onChange={(e) => setName(e.target.value)} /></div><div className="space-y-1"><Label>Mobile</Label><Input value={mobile} onChange={(e) => setMobile(e.target.value)} /></div></div>
          <div className="flex gap-6"><label className="flex items-center gap-2 text-sm"><Switch checked={blocked} onCheckedChange={setBlocked} /> Blocked</label><label className="flex items-center gap-2 text-sm"><Switch checked={active} onCheckedChange={setActive} /> Active</label></div>
          <Button onClick={save} className="w-full">Save user</Button>
          <p className="text-xs text-muted-foreground">Note: changing mobile here updates the profile only; the user still logs in with their original number.</p>
          <hr className="border-border" />
          <p className="font-semibold">Wallet: <span className="text-primary">{inr(user.balance)}</span></p>
          <select value={kind} onChange={(e) => setKind(e.target.value)} className="h-9 w-full rounded-md border border-input bg-background px-2 text-sm">
            <option value="admin_credit">Add balance</option><option value="admin_debit">Deduct balance</option><option value="task_adjust">Task reward adjust (+/-)</option><option value="referral_adjust">Referral bonus adjust (+/-)</option>
          </select>
          <Input type="number" placeholder="Amount" value={amt} onChange={(e) => setAmt(e.target.value)} />
          <Input placeholder="Reason (required)" value={reason} onChange={(e) => setReason(e.target.value)} />
          <Button variant="hero" onClick={adjust} className="w-full">Apply</Button>
          <p className="pt-2 font-semibold">Recent history</p>
          <div className="max-h-48 divide-y divide-border overflow-y-auto text-xs">
            {tx?.map((t) => <div key={t.id} className="flex justify-between py-1.5"><span>{TX_LABEL[t.type] ?? t.type} · {t.description}<br /><span className="text-muted-foreground">{dt(t.created_at)}</span></span><span className={Number(t.amount) < 0 ? "text-destructive" : "text-primary"}>{inr(t.amount)}</span></div>)}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
