import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { useState, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Plus, CheckCircle2, XCircle, Wallet, Search } from "lucide-react";

export const Route = createFileRoute("/_authenticated/withdrawals")({
  head: () => ({ meta: [{ title: "Wallet Cash Out — Niyamah ERP" }] }),
  component: WithdrawalsPage,
});

type Customer = { id: string; name: string; name_bn: string | null; mobile: string };
type WReq = {
  id: string;
  customer_id: string;
  amount: number;
  method: string;
  account_number: string;
  note: string | null;
  status: string;
  processed_by: string | null;
  processed_at: string | null;
  created_at: string;
};

function WithdrawalsPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const { user } = useAuth();
  const qc = useQueryClient();

  const { data: isAdmin = false } = useQuery({
    queryKey: ["is-admin", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const { data } = await supabase.from("user_roles").select("role").eq("user_id", user!.id).eq("role", "admin").maybeSingle();
      return !!data;
    },
  });

  const [tab, setTab] = useState("pending");
  const [showAdd, setShowAdd] = useState(false);
  const [actOn, setActOn] = useState<{ tx: WReq; mode: "approve" | "reject" } | null>(null);
  const [actNote, setActNote] = useState("");

  const { data: requests = [], refetch } = useQuery({
    queryKey: ["withdrawal-requests"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("withdrawal_requests")
        .select("*")
        .order("created_at", { ascending: false })
        .limit(500);
      if (error) throw error;
      return (data || []) as WReq[];
    },
  });

  const customerIds = useMemo(() => Array.from(new Set(requests.map(r => r.customer_id))), [requests]);
  const { data: customerMap = {} } = useQuery({
    queryKey: ["withdraw-customers", customerIds.join(",")],
    enabled: customerIds.length > 0,
    queryFn: async () => {
      const { data } = await supabase.from("customers").select("id,name,name_bn,mobile").in("id", customerIds);
      const m: Record<string, Customer> = {};
      (data || []).forEach((c: any) => { m[c.id] = c; });
      return m;
    },
  });

  const filtered = requests.filter(r => tab === "all" || r.status === tab);

  const actMut = useMutation({
    mutationFn: async () => {
      if (!actOn) return;
      const { tx, mode } = actOn;
      if (mode === "approve") {
        // Insert wallet debit transaction
        const { error: wErr } = await supabase.from("wallet_transactions").insert({
          customer_id: tx.customer_id,
          type: "withdrawal_debit",
          amount: tx.amount,
          balance_after: 0,
          note: `Withdraw ${tx.method}${tx.account_number ? " · " + tx.account_number : ""}${actNote ? " · " + actNote : ""}`,
          reference_id: tx.id,
          transaction_date: new Date().toISOString(),
          created_by: user?.id,
        });
        if (wErr) throw wErr;
        // Recalc wallet
        await supabase.rpc("recalc_referral_wallet", { _customer_id: tx.customer_id });
      }
      const { error } = await supabase.from("withdrawal_requests").update({
        status: mode === "approve" ? "approved" : "rejected",
        processed_by: user?.id,
        processed_at: new Date().toISOString(),
        note: actNote ? `${tx.note || ""}${tx.note ? " | " : ""}${actNote}` : tx.note,
      }).eq("id", tx.id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "সম্পন্ন" : "Done");
      setActOn(null); setActNote("");
      qc.invalidateQueries({ queryKey: ["withdrawal-requests"] });
      qc.invalidateQueries({ queryKey: ["wm-wallet"] });
      qc.invalidateQueries({ queryKey: ["wm-tx"] });
      refetch();
    },
    onError: (e: any) => toast.error(e.message),
  });

  return (
    <PageLayout>
      <div className="mb-6 flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2"><Wallet className="h-6 w-6 text-primary" />{isBn ? "ওয়ালেট ক্যাশ আউট" : "Wallet Cash Out"}</h1>
          <p className="text-sm text-muted-foreground">{isBn ? "কাস্টমার ক্যাশ আউট রিকোয়েস্ট ও পেআউট লগ" : "Customer cash out requests and payout log"}</p>
        </div>
        <Button onClick={() => setShowAdd(true)}><Plus className="h-4 w-4 mr-1" />{isBn ? "নতুন ক্যাশ আউট" : "New Cash Out"}</Button>
      </div>

      <Tabs value={tab} onValueChange={setTab}>
        <TabsList>
          <TabsTrigger value="pending">{isBn ? "পেন্ডিং" : "Pending"}</TabsTrigger>
          <TabsTrigger value="approved">{isBn ? "অনুমোদিত" : "Approved"}</TabsTrigger>
          <TabsTrigger value="rejected">{isBn ? "প্রত্যাখ্যাত" : "Rejected"}</TabsTrigger>
          <TabsTrigger value="all">{isBn ? "সব" : "All"}</TabsTrigger>
        </TabsList>
        <TabsContent value={tab} className="mt-4">
          <div className="rounded-lg border bg-card">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{isBn ? "তারিখ" : "Date"}</TableHead>
                  <TableHead>{isBn ? "কাস্টমার" : "Customer"}</TableHead>
                  <TableHead>{isBn ? "মাধ্যম" : "Method"}</TableHead>
                  <TableHead>{isBn ? "অ্যাকাউন্ট" : "Account"}</TableHead>
                  <TableHead className="text-right">{isBn ? "পরিমাণ" : "Amount"}</TableHead>
                  <TableHead>{isBn ? "স্ট্যাটাস" : "Status"}</TableHead>
                  <TableHead className="text-right">{isBn ? "অ্যাকশন" : "Action"}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filtered.length === 0 ? (
                  <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground">{isBn ? "কোনো রিকোয়েস্ট নেই" : "No requests"}</TableCell></TableRow>
                ) : filtered.map((r) => {
                  const c = customerMap[r.customer_id];
                  return (
                    <TableRow key={r.id}>
                      <TableCell className="text-xs">{new Date(r.created_at).toLocaleString()}</TableCell>
                      <TableCell>
                        <div className="font-medium text-sm">{c ? (isBn ? c.name_bn || c.name : c.name) : "—"}</div>
                        <div className="text-xs text-muted-foreground">{c?.mobile}</div>
                      </TableCell>
                      <TableCell className="capitalize text-sm">{r.method}</TableCell>
                      <TableCell className="text-xs font-mono">{r.account_number || "—"}</TableCell>
                      <TableCell className="text-right font-semibold">৳{Number(r.amount).toFixed(2)}</TableCell>
                      <TableCell>
                        <Badge variant={r.status === "approved" ? "default" : r.status === "rejected" ? "destructive" : "secondary"}>
                          {r.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        {r.status === "pending" && isAdmin ? (
                          <div className="inline-flex gap-1">
                            <Button size="sm" variant="outline" className="text-green-600" onClick={() => { setActOn({ tx: r, mode: "approve" }); setActNote(""); }}>
                              <CheckCircle2 className="h-3.5 w-3.5 mr-1" />{isBn ? "অনুমোদন" : "Approve"}
                            </Button>
                            <Button size="sm" variant="outline" className="text-destructive" onClick={() => { setActOn({ tx: r, mode: "reject" }); setActNote(""); }}>
                              <XCircle className="h-3.5 w-3.5 mr-1" />{isBn ? "প্রত্যাখ্যান" : "Reject"}
                            </Button>
                          </div>
                        ) : (
                          <span className="text-xs text-muted-foreground">{r.processed_at ? new Date(r.processed_at).toLocaleDateString() : "—"}</span>
                        )}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>
        </TabsContent>
      </Tabs>

      <NewRequestDialog open={showAdd} onClose={() => setShowAdd(false)} userId={user?.id} isBn={isBn} onCreated={() => refetch()} />

      <Dialog open={!!actOn} onOpenChange={(o) => !o && setActOn(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{actOn?.mode === "approve" ? (isBn ? "ক্যাশ আউট অনুমোদন" : "Approve Cash Out") : (isBn ? "ক্যাশ আউট প্রত্যাখ্যান" : "Reject Cash Out")}</DialogTitle>
          </DialogHeader>
          {actOn && (
            <div className="space-y-3 text-sm">
              <div className="bg-muted/30 p-3 rounded-lg space-y-1">
                <div><span className="text-muted-foreground">{isBn ? "পরিমাণ" : "Amount"}:</span> <span className="font-semibold">৳{Number(actOn.tx.amount).toFixed(2)}</span></div>
                <div><span className="text-muted-foreground">{isBn ? "মাধ্যম" : "Method"}:</span> {actOn.tx.method} · {actOn.tx.account_number}</div>
              </div>
              <div>
                <Label>{isBn ? "নোট" : "Note"}</Label>
                <Textarea value={actNote} onChange={(e) => setActNote(e.target.value)} rows={2} placeholder={actOn.mode === "approve" ? (isBn ? "ট্রানজ্যাকশন আইডি, ব্যাংক রেফ" : "Transaction ID, bank ref") : (isBn ? "প্রত্যাখ্যানের কারণ" : "Rejection reason")} />
              </div>
              {actOn.mode === "approve" && (
                <p className="text-xs text-amber-600">{isBn ? "অনুমোদন করলে কাস্টমারের ওয়ালেট থেকে এই পরিমাণ ডেবিট হবে।" : "On approval, this amount will be debited from the customer's wallet."}</p>
              )}
            </div>
          )}
          <DialogFooter>
            <Button variant="ghost" onClick={() => setActOn(null)}>{isBn ? "বাতিল" : "Cancel"}</Button>
            <Button onClick={() => actMut.mutate()} disabled={actMut.isPending} variant={actOn?.mode === "reject" ? "destructive" : "default"}>
              {actMut.isPending ? "..." : actOn?.mode === "approve" ? (isBn ? "অনুমোদন করুন" : "Approve") : (isBn ? "প্রত্যাখ্যান করুন" : "Reject")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}

function NewRequestDialog({ open, onClose, userId, isBn, onCreated }: { open: boolean; onClose: () => void; userId?: string; isBn: boolean; onCreated: () => void }) {
  const [search, setSearch] = useState("");
  const [results, setResults] = useState<Customer[]>([]);
  const [selected, setSelected] = useState<Customer | null>(null);
  const [form, setForm] = useState({ amount: "", method: "bkash", account_number: "", note: "" });

  const { data: wallet } = useQuery({
    queryKey: ["wd-wallet", selected?.id],
    enabled: !!selected,
    queryFn: async () => {
      const { data } = await supabase.from("referral_wallets").select("balance").eq("customer_id", selected!.id).maybeSingle();
      return data;
    },
  });
  const balance = Number(wallet?.balance || 0);

  const handleSearch = async (q: string) => {
    setSearch(q);
    if (q.length < 2) { setResults([]); return; }
    const { data } = await supabase.from("customers").select("id,name,name_bn,mobile")
      .or(`name.ilike.%${q}%,name_bn.ilike.%${q}%,mobile.ilike.%${q}%`).limit(8);
    setResults(data || []);
  };

  const reset = () => { setSearch(""); setResults([]); setSelected(null); setForm({ amount: "", method: "bkash", account_number: "", note: "" }); };

  const submit = useMutation({
    mutationFn: async () => {
      if (!selected) throw new Error(isBn ? "কাস্টমার নির্বাচন করুন" : "Select customer");
      const amt = Number(form.amount);
      if (!amt || amt <= 0) throw new Error(isBn ? "সঠিক পরিমাণ দিন" : "Enter valid amount");
      if (amt > balance) throw new Error(isBn ? "ওয়ালেট ব্যালেন্স অপর্যাপ্ত" : "Insufficient wallet balance");
      if (!form.account_number.trim()) throw new Error(isBn ? "অ্যাকাউন্ট নম্বর লাগবে" : "Account number required");
      const { error } = await supabase.from("withdrawal_requests").insert({
        customer_id: selected.id,
        amount: amt,
        method: form.method,
        account_number: form.account_number.trim(),
        note: form.note,
        status: "pending",
      });
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(isBn ? "রিকোয়েস্ট জমা হয়েছে" : "Request submitted");
      reset(); onClose(); onCreated();
    },
    onError: (e: any) => toast.error(e.message),
  });

  return (
    <Dialog open={open} onOpenChange={(o) => { if (!o) { reset(); onClose(); } }}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{isBn ? "নতুন ক্যাশ আউট রিকোয়েস্ট" : "New Cash Out Request"}</DialogTitle>
        </DialogHeader>
        <div className="space-y-3">
          <div>
            <Label>{isBn ? "কাস্টমার" : "Customer"} *</Label>
            {!selected ? (
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input className="pl-9" value={search} onChange={(e) => handleSearch(e.target.value)} placeholder={isBn ? "নাম বা মোবাইল" : "Name or mobile"} />
                {results.length > 0 && (
                  <div className="absolute z-10 mt-1 w-full rounded-lg border bg-popover shadow-lg">
                    {results.map((c) => (
                      <button key={c.id} type="button" onClick={() => { setSelected(c); setSearch(""); setResults([]); }} className="block w-full text-left px-3 py-2 text-sm hover:bg-accent">
                        {isBn ? c.name_bn || c.name : c.name} <span className="text-muted-foreground">({c.mobile})</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            ) : (
              <div className="flex items-center justify-between bg-muted/30 rounded-lg p-2.5">
                <div className="text-sm">
                  <div className="font-medium">{isBn ? selected.name_bn || selected.name : selected.name}</div>
                  <div className="text-xs text-muted-foreground">{selected.mobile} · {isBn ? "ব্যালেন্স" : "Balance"}: ৳{balance.toFixed(2)}</div>
                </div>
                <Button size="sm" variant="ghost" onClick={() => setSelected(null)}>{isBn ? "পরিবর্তন" : "Change"}</Button>
              </div>
            )}
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <Label>{isBn ? "পরিমাণ" : "Amount"} *</Label>
              <Input type="number" value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} max={balance || undefined} />
            </div>
            <div>
              <Label>{isBn ? "মাধ্যম" : "Method"} *</Label>
              <Select value={form.method} onValueChange={(v) => setForm({ ...form, method: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="bkash">bKash</SelectItem>
                  <SelectItem value="nagad">Nagad</SelectItem>
                  <SelectItem value="rocket">Rocket</SelectItem>
                  <SelectItem value="bank">Bank</SelectItem>
                  <SelectItem value="cash">Cash</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div>
            <Label>{isBn ? "অ্যাকাউন্ট নম্বর" : "Account Number"} *</Label>
            <Input value={form.account_number} onChange={(e) => setForm({ ...form, account_number: e.target.value })} />
          </div>
          <div>
            <Label>{isBn ? "নোট" : "Note"}</Label>
            <Textarea rows={2} value={form.note} onChange={(e) => setForm({ ...form, note: e.target.value })} />
          </div>
        </div>
        <DialogFooter>
          <Button variant="ghost" onClick={() => { reset(); onClose(); }}>{isBn ? "বাতিল" : "Cancel"}</Button>
          <Button onClick={() => submit.mutate()} disabled={submit.isPending || !selected}>
            {submit.isPending ? "..." : (isBn ? "জমা দিন" : "Submit")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
