import { Link, useNavigate } from "@tanstack/react-router";
import { ArrowLeft } from "lucide-react";
import { useState, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";

export function ActionScreen({
  title,
  subtitle,
  color = "primary",
  children,
}: {
  title: string;
  subtitle?: string;
  color?: "primary" | "destructive" | "success";
  children: ReactNode;
}) {
  const bg =
    color === "destructive"
      ? "linear-gradient(135deg, oklch(0.5 0.22 25), oklch(0.6 0.22 30))"
      : color === "success"
      ? "linear-gradient(135deg, oklch(0.45 0.16 155), oklch(0.6 0.16 155))"
      : "var(--gradient-balance)";
  return (
    <div className="min-h-screen bg-background max-w-[480px] mx-auto">
      <header className="px-4 pt-4 pb-8 text-primary-foreground" style={{ background: bg }}>
        <div className="flex items-center gap-3">
          <Link to="/" className="h-10 w-10 rounded-full bg-white/15 backdrop-blur flex items-center justify-center">
            <ArrowLeft className="h-5 w-5" />
          </Link>
          <div>
            <h1 className="text-lg font-bold leading-tight">{title}</h1>
            {subtitle && <p className="text-xs opacity-80 mt-0.5">{subtitle}</p>}
          </div>
        </div>
      </header>
      <main className="px-4 -mt-4">{children}</main>
    </div>
  );
}

export function FormCard({ children }: { children: ReactNode }) {
  return <div className="bg-card rounded-2xl shadow-[var(--shadow-elevated)] p-5 space-y-4">{children}</div>;
}

export function TextField({
  label, value, onChange, placeholder, inputMode, maxLength, type = "text", prefix,
}: {
  label: string; value: string; onChange: (v: string) => void; placeholder?: string;
  inputMode?: "numeric" | "decimal" | "text" | "tel"; maxLength?: number; type?: string; prefix?: string;
}) {
  return (
    <label className="block">
      <span className="text-xs font-semibold text-muted-foreground">{label}</span>
      <div className="mt-1 flex items-center gap-2 px-4 h-12 rounded-xl border border-input bg-background focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20 transition">
        {prefix && <span className="text-muted-foreground text-base">{prefix}</span>}
        <input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          inputMode={inputMode}
          maxLength={maxLength}
          type={type}
          className="w-full bg-transparent outline-none text-base"
        />
      </div>
    </label>
  );
}

export function SubmitButton({
  disabled, loading, label, color = "primary", onClick,
}: { disabled?: boolean; loading?: boolean; label: string; color?: "primary" | "destructive" | "success"; onClick?: () => void }) {
  const bg =
    color === "destructive"
      ? "linear-gradient(135deg, oklch(0.5 0.22 25), oklch(0.6 0.22 30))"
      : color === "success"
      ? "linear-gradient(135deg, oklch(0.45 0.16 155), oklch(0.6 0.16 155))"
      : "var(--gradient-primary)";
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled || loading}
      className="w-full h-12 rounded-full font-bold text-primary-foreground disabled:opacity-40 active:scale-[0.98] transition"
      style={{ background: bg }}
    >
      {loading ? "প্রক্রিয়াধীন..." : label}
    </button>
  );
}

// Convenient helper for screens that submit and want a success toast + cache refetch + redirect home.
export function useActionRunner() {
  const qc = useQueryClient();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const run = async (fn: () => Promise<{ ok?: boolean; new_balance?: number }>, msg: string) => {
    setLoading(true);
    try {
      const res = await fn();
      qc.invalidateQueries({ queryKey: ["profile"] });
      qc.invalidateQueries({ queryKey: ["transactions"] });
      toast.success(`${msg} • নতুন ব্যালেন্স ৳${Number(res.new_balance ?? 0).toLocaleString()}`);
      navigate({ to: "/" });
    } catch (err: any) {
      toast.error(err?.message ?? "লেনদেন ব্যর্থ");
    } finally {
      setLoading(false);
    }
  };
  return { loading, run };
}
