"use client";

import { useEffect, useState } from "react";
import { getWallets, createWallet } from "@/api/customerApi";
import { useAppSelector } from "@/store/hooks";

export default function Wallet() {
  const [wallet, setWallet] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  const { access_token } = useAppSelector((state) => state.auth);

  useEffect(() => {
    if (access_token) {
      fetchWallet();
    }
  }, [access_token]);

  const fetchWallet = async () => {
    try {
      setLoading(true);

      const res = await getWallets();
      const walletData = res?.wallets?.[0];

      // 👉 If wallet doesn't exist → create one
      if (!walletData) {
        const newWallet = await createWallet();
        setWallet(newWallet);
        return;
      }

      setWallet(walletData);
    } catch (err: any) {
      console.error("Wallet error:", err);
    } finally {
      setLoading(false);
    }
  };

  if (loading) return <p className="p-5">Loading wallet...</p>;

  return (
    <div className="max-w-md mx-auto bg-white shadow-md rounded-xl p-5 space-y-4">

      <h2 className="text-xl font-bold">💰 My Wallet</h2>

      {/* Balance */}
      <div className="bg-green-50 p-4 rounded-lg text-center">
        <p className="text-sm text-gray-500">Available Balance</p>
        <p className="text-2xl font-bold text-green-600">
          ₹ {wallet?.balance ?? 0}
        </p>
      </div>

      {/* Status */}
      <div className="flex justify-between text-sm">
        <span>Status</span>
        <span
          className={`font-semibold ${
            wallet?.is_active ? "text-green-600" : "text-red-500"
          }`}
        >
          {wallet?.is_active ? "Active" : "Inactive"}
        </span>
      </div>

      {/* Created */}
      <div className="text-xs text-gray-400">
        Created on{" "}
        {wallet?.created_at
          ? new Date(wallet.created_at).toLocaleDateString("en-IN")
          : "-"}
      </div>

      {/* Refresh */}
      <button
        onClick={fetchWallet}
        className="w-full bg-primary text-white py-2 rounded-md"
      >
        Refresh
      </button>
    </div>
  );
}