import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { sendMoney } from "@/lib/bkash.functions";
import { ActionScreen, FormCard, TextField, SubmitButton, useActionRunner } from "@/components/bkash/ActionScreen";

export const Route = createFileRoute("/_authenticated/send")({
  validateSearch: (s: Record<string, unknown>) => ({ to: typeof s.to === "string" ? s.to : undefined }),
  component: SendPage,
});

function SendPage() {
  const search = Route.useSearch();
  const [phone, setPhone] = useState(search.to ?? "");
  const [amount, setAmount] = useState("");
  const [pin, setPin] = useState("");
  const [note, setNote] = useState("");
  const fn = useServerFn(sendMoney);
  const { loading, run } = useActionRunner();

  const amt = parseFloat(amount);
  const valid = /^01\d{9}$/.test(phone) && amt > 0 && /^\d{5}$/.test(pin);

  return (
    <ActionScreen title="সেন্ড মানি" subtitle="বিকাশ থেকে বিকাশে টাকা পাঠান">
      <FormCard>
        <TextField label="প্রাপকের ফোন নম্বর" value={phone}
          onChange={(v) => setPhone(v.replace(/\D/g, "").slice(0, 11))}
          placeholder="01XXXXXXXXX" inputMode="numeric" maxLength={11} />
        <TextField label="পরিমাণ" prefix="৳" value={amount}
          onChange={(v) => setAmount(v.replace(/[^\d.]/g, ""))}
          placeholder="0.00" inputMode="decimal" />
        <TextField label="রেফারেন্স (ঐচ্ছিক)" value={note} onChange={setNote} placeholder="যেমন: ভাড়া" maxLength={120} />
        <TextField label="৫ ডিজিটের পিন" value={pin}
          onChange={(v) => setPin(v.replace(/\D/g, "").slice(0, 5))}
          placeholder="• • • • •" inputMode="numeric" maxLength={5} type="password" />
        <SubmitButton
          disabled={!valid}
          loading={loading}
          label="সেন্ড মানি"
          onClick={() => run(() => fn({ data: { receiverPhone: phone, amount: amt, pin, note: note || undefined } }), "টাকা পাঠানো হয়েছে")}
        />
      </FormCard>
      <p className="text-center text-xs text-muted-foreground mt-4">সেন্ড মানি ফি নেই</p>
    </ActionScreen>
  );
}
