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

export const Route = createFileRoute("/_authenticated/payment")({
  component: PaymentPage,
});

function PaymentPage() {
  const [merchant, setMerchant] = useState("");
  const [amount, setAmount] = useState("");
  const [pin, setPin] = useState("");
  const fn = useServerFn(makePayment);
  const { loading, run } = useActionRunner();

  const amt = parseFloat(amount);
  const valid = merchant.trim().length > 2 && amt > 0 && /^\d{5}$/.test(pin);

  return (
    <ActionScreen title="পেমেন্ট" subtitle="দোকান বা মার্চেন্টে পরিশোধ" color="success">
      <FormCard>
        <TextField label="মার্চেন্ট নাম বা নম্বর" value={merchant} onChange={setMerchant} placeholder="যেমন: Aarong Dhanmondi" />
        <TextField label="পরিমাণ" prefix="৳" value={amount}
          onChange={(v) => setAmount(v.replace(/[^\d.]/g, ""))} placeholder="0.00" inputMode="decimal" />
        <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} color="success" label="পরিশোধ করুন"
          onClick={() => run(() => fn({ data: { type: "payment", amount: amt, reference: merchant, counterpartyName: merchant, pin } }), "পেমেন্ট সফল")}
        />
      </FormCard>
    </ActionScreen>
  );
}
