"use client";

import { useState, useEffect, useRef } from "react";
import Image from "next/image";
import { Button } from "@heroui/react";
import { useApp } from "@/contexts/AppContext";
import { buttonStyles } from "@/lib/buttonStyles";
import { useUSDCBalance } from '@/hooks/useBalance';
import { useLendingWithdraw } from '@/hooks/useLendingWithdraw';
import { useSuppliedBalance } from '@/hooks/useLendingSupply';
import { getTxUrl } from '@/lib/contracts';
import { useTokenDecimalsFromAddress } from '@/hooks/useTokenDecimals';
import { useTokenBySymbol } from '@/hooks/useTokenBySymbol';
import { useHealthFactor, useSupplyAPY, useBorrowBalance } from '@/hooks/useHealthFactor';
import { toast } from 'sonner';
import { useWalletStatus } from '@/hooks/useWalletStatus';

export default function WithdrawPanel() {
  const { t } = useApp();
  const [amount, setAmount] = useState("");

  // 使用统一的钱包状态 Hook
  const { isConnected, mounted } = useWalletStatus();
  const { formattedBalance: usdcBalance, isLoading: isBalanceLoading, refetch: refetchBalance } = useUSDCBalance();
  const { formattedBalance: suppliedBalance, refetch: refetchSupplied } = useSuppliedBalance();
  const {
    status: withdrawStatus,
    error: withdrawError,
    isLoading: isWithdrawLoading,
    withdrawHash,
    executeWithdraw,
    reset: resetWithdraw,
  } = useLendingWithdraw();

  // 健康因子和 APY
  const {
    formattedHealthFactor,
    status: healthStatus,
    utilization,
    isLoading: isHealthLoading
  } = useHealthFactor();
  const { apy } = useSupplyAPY();
  const { formattedBalance: borrowBalance } = useBorrowBalance();
  const hasShownBorrowWarning = useRef(false);

  // 从产品 API 获取 USDC token 信息，优先从合约地址读取精度
  const usdcToken = useTokenBySymbol('USDC');
  const usdcInputDecimals = useTokenDecimalsFromAddress(usdcToken?.contractAddress, usdcToken?.decimals ?? 18);
  const usdcDisplayDecimals = Math.min(usdcInputDecimals, 6);
  const truncateDecimals = (s: string, d: number) => { const p = s.split('.'); return p.length > 1 ? `${p[0]}.${p[1].slice(0, d)}` : s; };
  const isValidAmount = (v: string) => v !== '' && !isNaN(parseFloat(v)) && parseFloat(v) > 0;

  const handleAmountChange = (value: string) => {
    if (value === '') { setAmount(value); return; }
    if (!/^\d*\.?\d*$/.test(value)) return;
    const parts = value.split('.');
    if (parts.length > 1 && parts[1].length > usdcDisplayDecimals) return;
    if (parseFloat(value) > parseFloat(suppliedBalance)) { setAmount(truncateDecimals(suppliedBalance, usdcDisplayDecimals)); return; }
    setAmount(value);
  };

  // 有借款时，挂载后弹出一次提示
  useEffect(() => {
    if (!mounted || hasShownBorrowWarning.current) return;
    if (parseFloat(borrowBalance) > 0) {
      toast.warning(t("supply.toast.borrowWarning"), {
        description: t("supply.toast.borrowWarningDesc"),
        duration: 5000,
      });
      hasShownBorrowWarning.current = true;
    }
  }, [mounted, borrowBalance]);

  const WITHDRAW_TOAST_ID = 'lending-withdraw-tx';

  // Withdraw 交易提交
  useEffect(() => {
    if (withdrawHash && withdrawStatus === 'withdrawing') {
      toast.loading(t("supply.toast.withdrawSubmitted"), {
        id: WITHDRAW_TOAST_ID,
        description: t("supply.toast.processingWithdrawal"),
        action: {
          label: t("supply.toast.viewTx"),
          onClick: () => window.open(getTxUrl(withdrawHash), '_blank'),
        },
      });
    }
  }, [withdrawHash, withdrawStatus]);

  // 成功后刷新余额
  useEffect(() => {
    if (withdrawStatus === 'success') {
      toast.success(t("supply.toast.withdrawnSuccess"), {
        id: WITHDRAW_TOAST_ID,
        description: t("supply.toast.withdrawnSuccessDesc"),
        duration: 5000,
      });
      refetchBalance();
      refetchSupplied();
      const timer = setTimeout(() => { resetWithdraw(); setAmount(''); }, 3000);
      return () => clearTimeout(timer);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [withdrawStatus]);

  // 错误提示
  useEffect(() => {
    if (withdrawError) {
      if (withdrawError === 'Transaction cancelled') {
        toast.dismiss(WITHDRAW_TOAST_ID);
      } else {
        toast.error(t("supply.toast.withdrawFailed"), {
          id: WITHDRAW_TOAST_ID,
          duration: 5000,
        });
      }
    }
  }, [withdrawError]);

  return (
    <div className="p-6 flex flex-col gap-6 flex-1">
      {/* Token Balance & Supplied */}
      <div className="flex flex-col gap-4">
        {/* Token Balance */}
        <div className="bg-bg-subtle dark:bg-gray-700 rounded-xl border border-border-gray dark:border-gray-600 p-3 flex flex-col gap-1">
          <span className="text-[10px] font-medium text-text-tertiary dark:text-gray-400 leading-[150%] tracking-[0.01em]">
            {t("supply.tokenBalance")}
          </span>
          <div className="flex items-center justify-between">
            <span className="text-body-large font-bold text-text-primary dark:text-white leading-[150%]">
              {!mounted ? '0' : isBalanceLoading ? '...' : parseFloat(truncateDecimals(usdcBalance, usdcDisplayDecimals)).toLocaleString('en-US', { maximumFractionDigits: usdcDisplayDecimals })}
            </span>
            <span className="text-caption-tiny font-medium text-text-tertiary dark:text-gray-400 leading-[150%] tracking-[0.01em]">
              USDC
            </span>
          </div>
          <span className="text-[10px] font-medium text-text-tertiary dark:text-gray-400 leading-[150%] tracking-[0.01em]">
            ${!mounted ? '0' : isBalanceLoading ? '...' : parseFloat(truncateDecimals(usdcBalance, usdcDisplayDecimals)).toLocaleString('en-US', { maximumFractionDigits: usdcDisplayDecimals })}
          </span>
        </div>

        {/* Supplied */}
        <div className="bg-bg-subtle dark:bg-gray-700 rounded-xl border border-border-gray dark:border-gray-600 p-3 flex flex-col gap-1">
          <span className="text-[10px] font-medium text-text-tertiary dark:text-gray-400 leading-[150%] tracking-[0.01em]">
            {t("supply.supplied")}
          </span>
          <div className="flex items-center justify-between">
            <span className="text-body-large font-bold text-text-primary dark:text-white leading-[150%]">
              {!mounted ? '0' : parseFloat(truncateDecimals(suppliedBalance, usdcDisplayDecimals)).toLocaleString('en-US', { maximumFractionDigits: usdcDisplayDecimals })}
            </span>
            <span className="text-caption-tiny font-medium text-text-tertiary dark:text-gray-400 leading-[150%] tracking-[0.01em]">
              USDC
            </span>
          </div>
          <span className="text-[10px] font-medium text-text-tertiary dark:text-gray-400 leading-[150%] tracking-[0.01em]">
            ${!mounted ? '0' : parseFloat(truncateDecimals(suppliedBalance, usdcDisplayDecimals)).toLocaleString('en-US', { maximumFractionDigits: usdcDisplayDecimals })}
          </span>
        </div>
      </div>

      {/* Withdraw Section */}
      <div className="bg-bg-subtle dark:bg-gray-700 rounded-xl border border-border-gray dark:border-gray-600 p-4 flex flex-col gap-4">
        {/* Withdraw Label and Available */}
        <div className="flex items-center gap-2">
          <span className="text-caption-tiny font-medium text-text-secondary dark:text-gray-300 leading-[150%] tracking-[0.01em]">
            {t("supply.withdraw")}
          </span>
          <div className="flex items-center gap-2 ml-auto">
            <Image src="/icons/ui/wallet-icon.svg" alt="" width={12} height={12} />
            <span className="text-caption-tiny font-medium text-text-secondary dark:text-gray-300 leading-[150%] tracking-[0.01em]">
              {!mounted ? '0 USDC' : `${parseFloat(truncateDecimals(suppliedBalance, usdcDisplayDecimals)).toLocaleString('en-US', { maximumFractionDigits: usdcDisplayDecimals })} USDC`}
            </span>
          </div>
          <Button
            size="sm"
            className={buttonStyles({ intent: "max" })}
            onPress={() => setAmount(truncateDecimals(suppliedBalance, usdcDisplayDecimals))}
          >
            {t("supply.max")}
          </Button>
        </div>

        {/* Input Row */}
        <div className="flex items-center justify-between h-12">
          {/* USDC Token Button */}
          <div className="bg-bg-surface dark:bg-gray-800 rounded-full border border-border-normal dark:border-gray-600 p-2 flex items-center gap-2 h-12">
            <Image
              src="/assets/tokens/usd-coin-usdc-logo-10.svg"
              alt="USDC"
              width={32}
              height={32}
            />
            <span className="text-body-default font-bold text-text-primary dark:text-white leading-[150%]">
              USDC
            </span>
          </div>

          {/* Amount Input */}
          <div className="flex flex-col items-end">
            <input
              type="text" inputMode="decimal"
              value={amount}
              onChange={(e) => handleAmountChange(e.target.value)}
              placeholder="0"
              className="text-heading-h3 font-bold text-text-primary dark:text-white leading-[130%] tracking-[-0.005em] text-right bg-transparent outline-none w-24"
            />
            <span className="text-caption-tiny font-regular text-text-tertiary dark:text-gray-400 leading-[150%] tracking-[0.01em]">
              {amount ? `≈ $${amount}` : "--"}
            </span>
          </div>
        </div>
      </div>

      {/* Health Factor */}
      <div className="flex flex-col gap-3">
        <div className="flex items-center justify-between">
          <div className="flex flex-col gap-1">
            <span className="text-[10px] font-medium text-text-tertiary dark:text-gray-400 leading-[150%] tracking-[0.01em]">
              {t("supply.healthFactor")}: {isHealthLoading ? '...' : formattedHealthFactor}
            </span>
            <span className="text-body-small font-bold text-text-primary dark:text-white leading-[150%]">
              {utilization.toFixed(1)}% {t("supply.utilization")}
            </span>
          </div>
          <span className={`text-caption-tiny font-bold leading-[150%] tracking-[0.01em] ${
            healthStatus === 'safe' ? 'text-[#10b981] dark:text-green-400' :
            healthStatus === 'warning' ? 'text-[#ffb933] dark:text-yellow-400' :
            healthStatus === 'danger' ? 'text-[#ff6900] dark:text-orange-400' :
            'text-[#ef4444] dark:text-red-400'
          }`}>
            {healthStatus === 'safe' ? t("supply.safe") :
             healthStatus === 'warning' ? t("supply.warning") :
             healthStatus === 'danger' ? t("supply.danger") :
             t("supply.critical")}
          </span>
        </div>

        {/* Progress Bar */}
        <div className="relative w-full h-2.5 rounded-full overflow-hidden">
          <div
            className="absolute inset-0 opacity-30"
            style={{
              background: 'linear-gradient(90deg, #10b981 0%, #3b82f6 20%, #8b5cf6 40%, #ec4899 60%, #f59e0b 80%, #ef4444 100%)',
            }}
          />
          <div
            className="absolute left-0 top-0 h-full rounded-full transition-all duration-500 ease-out"
            style={{
              background: 'linear-gradient(90deg, #10b981 0%, #3b82f6 20%, #8b5cf6 40%, #ec4899 60%, #f59e0b 80%, #ef4444 100%)',
              width: `${Math.min(utilization, 100)}%`,
              boxShadow: utilization > 0 ? '0 0 8px rgba(59, 130, 246, 0.5)' : 'none',
            }}
          />
        </div>
      </div>

      {/* Current APY */}
      <div className="bg-bg-subtle dark:bg-gray-700 rounded-2xl p-4 flex flex-col gap-2">
        <span className="text-body-small font-medium text-text-secondary dark:text-gray-300 leading-[150%]">
          {t("supply.currentReturns")}
        </span>
        <div className="flex items-center justify-between">
          <span className="text-body-small font-regular text-text-tertiary dark:text-gray-400 leading-[150%]">
            {t("supply.supplyApy")}
          </span>
          <span className="text-body-small font-bold text-[#ff6900] dark:text-orange-400 leading-[150%]">
            {apy > 0 ? `${apy.toFixed(2)}%` : '--'}
          </span>
        </div>
        <div className="flex items-center justify-between">
          <span className="text-body-small font-regular text-text-tertiary dark:text-gray-400 leading-[150%]">
            {t("supply.yearlyEarnings")}
          </span>
          <span className="text-body-small font-bold text-[#10b981] dark:text-green-400 leading-[150%]">
            {apy > 0 && parseFloat(suppliedBalance) > 0
              ? `~ $${(parseFloat(suppliedBalance) * apy / 100).toFixed(2)}`
              : '~ $0.00'}
          </span>
        </div>
      </div>

      {/* Withdraw Button */}
      <Button
        isDisabled={
          !mounted ||
          !isConnected ||
          !isValidAmount(amount) ||
          parseFloat(amount) > parseFloat(suppliedBalance) ||
          isWithdrawLoading
        }
        className={`${buttonStyles({ intent: "theme" })} mt-auto`}
        endContent={<Image src="/icons/actions/arrow-right-icon.svg" alt="" width={20} height={20} />}
        onPress={() => {
          if (amount && parseFloat(amount) > 0) {
            resetWithdraw();
            executeWithdraw(amount);
          }
        }}
      >
        {!mounted && t("common.loading")}
        {mounted && !isConnected && t("common.connectWallet")}
        {mounted && isConnected && !!amount && !isValidAmount(amount) && t("common.invalidAmount")}
        {mounted && isConnected && isValidAmount(amount) && parseFloat(amount) > parseFloat(suppliedBalance) && t("supply.insufficientBalance")}
        {mounted && isConnected && withdrawStatus === 'idle' && (!amount || isValidAmount(amount)) && parseFloat(amount) <= parseFloat(suppliedBalance) && t("supply.withdraw")}
        {mounted && withdrawStatus === 'withdrawing' && t("supply.withdrawing")}
        {mounted && withdrawStatus === 'success' && t("common.success")}
        {mounted && withdrawStatus === 'error' && t("common.failed")}
      </Button>
    </div>
  );
}
