import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";

export const Route = createFileRoute("/admin/deposits")({ component: AdminDeposits });

type Deposit = {
  id: string;
  user_id: string;
  amount: number;
  mpesa_reference: string;
  status: "pending" | "approved" | "rejected";
  note: string | null;
  admin_notes: string | null;
  created_at: string;
  reviewed_at: string | null;
  profile?: { full_name: string | null; email: string | null; phone: string | null } | null;
};

const STATUSES = ["pending", "approved", "rejected"] as const;

function AdminDeposits() {
  const [rows, setRows] = useState<Deposit[]>([]);
  const [filter, setFilter] = useState<"all" | Deposit["status"]>("pending");
  const [notes, setNotes] = useState<Record<string, string>>({});

  const load = async () => {
    const { data, error } = await supabase
      .from("deposits")
      .select("id, user_id, amount, mpesa_reference, status, note, admin_notes, created_at, reviewed_at")
      .order("created_at", { ascending: false });
    if (error) return toast.error(error.message);
    const ids = Array.from(new Set((data ?? []).map((d) => d.user_id)));
    let profiles: Record<string, Deposit["profile"]> = {};
    if (ids.length) {
      const { data: p } = await supabase.from("profiles").select("id, full_name, email, phone").in("id", ids);
      profiles = Object.fromEntries((p ?? []).map((x) => [x.id, { full_name: x.full_name, email: x.email, phone: x.phone }]));
    }
    setRows(((data ?? []) as Deposit[]).map((d) => ({ ...d, profile: profiles[d.user_id] ?? null })));
  };
  useEffect(() => { load(); }, []);

  const approve = async (id: string) => {
    const { error } = await supabase.rpc("approve_deposit", { _deposit_id: id, _note: notes[id] || undefined });
    if (error) return toast.error(error.message);
    toast.success("Approved and balance credited");
    load();
  };
  const reject = async (id: string) => {
    const { error } = await supabase.rpc("reject_deposit", { _deposit_id: id, _note: notes[id] || undefined });
    if (error) return toast.error(error.message);
    toast.success("Rejected");
    load();
  };

  const filtered = filter === "all" ? rows : rows.filter((r) => r.status === filter);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Deposits</h1>
        <p className="text-sm text-muted-foreground">Review and credit customer top-ups.</p>
      </div>
      <div className="flex flex-wrap gap-2">
        {(["all", ...STATUSES] as const).map((s) => (
          <Button key={s} size="sm" variant={filter === s ? "default" : "outline"} onClick={() => setFilter(s)} className="capitalize">{s}</Button>
        ))}
      </div>
      <div className="grid gap-3">
        {filtered.length === 0 && <p className="text-sm text-muted-foreground">No deposits.</p>}
        {filtered.map((d) => (
          <Card key={d.id} className="glass">
            <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0">
              <div>
                <div className="text-lg font-semibold">KSh {Number(d.amount).toFixed(2)}</div>
                <div className="text-xs text-muted-foreground">Ref <span className="font-mono">{d.mpesa_reference}</span> · {new Date(d.created_at).toLocaleString()}</div>
                <div className="mt-1 text-xs text-muted-foreground">{d.profile?.full_name ?? "Unknown"} · {d.profile?.email ?? "—"} · {d.profile?.phone ?? "—"}</div>
                {d.note && <div className="mt-1 text-xs">Customer note: {d.note}</div>}
              </div>
              <Badge variant={d.status === "approved" ? "default" : d.status === "rejected" ? "destructive" : "secondary"} className="capitalize">{d.status}</Badge>
            </CardHeader>
            <CardContent className="space-y-2">
              {d.status === "pending" ? (
                <>
                  <Input placeholder="Optional note to user" value={notes[d.id] ?? ""} onChange={(e) => setNotes((n) => ({ ...n, [d.id]: e.target.value }))} />
                  <div className="flex gap-2">
                    <Button size="sm" onClick={() => approve(d.id)}>Approve & credit</Button>
                    <Button size="sm" variant="outline" onClick={() => reject(d.id)}>Reject</Button>
                  </div>
                </>
              ) : d.admin_notes ? (
                <div className="text-xs text-muted-foreground">Note: {d.admin_notes}</div>
              ) : null}
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}