import {useMemo, useState} from 'react'
import {AccountClient, GmxClaimableSummary} from '../../../generated/ManagingApi'
import useApiUrlStore from '../../../app/store/apiStore'
import {Table} from '../../../components/mollecules'

function AccountFee() {
  const [accountName, setAccountName] = useState('')
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState<GmxClaimableSummary | null>(null)
  const [error, setError] = useState<string | null>(null)
  const { apiUrl } = useApiUrlStore()

  const handleFetch = async () => {
    if (!accountName.trim()) {
      setError('Please enter an account name')
      return
    }

    setLoading(true)
    setError(null)
    
    try {
      const accountClient = new AccountClient({}, apiUrl)
      const result = await accountClient.account_GetGmxClaimableSummary(accountName.trim())
      setData(result)
    } catch (err: any) {
      setError(err.message || 'Failed to fetch GMX claimable summary')
      setData(null)
    } finally {
      setLoading(false)
    }
  }

  // Table columns for all sections
  const dataColumns = useMemo(
    () => [
      {
        Header: 'Type',
        accessor: 'type',
      },
      {
        Header: 'Amount (USDC)',
        accessor: 'amount',
      },
    ],
    []
  )

  // Funding fees table data
  const fundingFeesData = useMemo(() => {
    if (!data?.claimableFundingFees) return []
    
    return [
      {
        type: 'Total Funding Fees',
        amount: `$${data.claimableFundingFees.totalUsdc?.toFixed(2) || '0.00'}`,
      },
    ]
  }, [data])

  // UI fees table data
  const uiFeesData = useMemo(() => {
    if (!data?.claimableUiFees) return []
    
    return [
      {
        type: 'Total UI Fees',
        amount: `$${data.claimableUiFees.totalUsdc?.toFixed(2) || '0.00'}`,
      },
    ]
  }, [data])

  // Rebate stats table data
  const rebateStatsData = useMemo(() => {
    if (!data?.rebateStats) return []
    
    return [
      {
        type: 'Total Rebate USDC',
        amount: `$${data.rebateStats.totalRebateUsdc?.toFixed(2) || '0.00'}`,
      },
      {
        type: 'Discount USDC',
        amount: `$${data.rebateStats.discountUsdc?.toFixed(2) || '0.00'}`,
      },
      {
        type: 'Rebate Factor',
        amount: (data.rebateStats.rebateFactor || 0).toFixed(4),
      },
      {
        type: 'Discount Factor',
        amount: (data.rebateStats.discountFactor || 0).toFixed(4),
      },
    ]
  }, [data])

  // Calculate total claimable for display
  const totalClaimable = useMemo(() => {
    if (!data) return 0
    const fundingTotal = data.claimableFundingFees?.totalUsdc || 0
    const uiTotal = data.claimableUiFees?.totalUsdc || 0
    return fundingTotal + uiTotal
  }, [data])

  return (
    <div className="p-6">
      <h2 className="text-2xl font-bold mb-6">GMX Account Fees</h2>
      
      {/* Input Section */}
      <div className="mb-6 flex gap-4 items-end">
        <div className="form-control">
          <label className="label">
            <span className="label-text">Account Name</span>
          </label>
          <input
            type="text"
            placeholder="Enter account name"
            className="input input-bordered w-full max-w-xs"
            value={accountName}
            onChange={(e) => setAccountName(e.target.value)}
            disabled={loading}
          />
        </div>
        <button
          className={`btn btn-primary ${loading ? 'loading' : ''}`}
          onClick={handleFetch}
          disabled={loading}
        >
          {loading ? 'Fetching...' : 'Fetch'}
        </button>
      </div>

      {/* Error Display */}
      {error && (
        <div className="alert alert-error mb-6">
          <div>
            <svg xmlns="http://www.w3.org/2000/svg" className="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m-2 2" />
            </svg>
            <span>{error}</span>
          </div>
        </div>
      )}

      {/* Results Section */}
      {data && (
        <div className="space-y-8">
          {/* Total Summary */}
          <div className="stats shadow">
            <div className="stat">
              <div className="stat-title">Total Claimable</div>
              <div className="stat-value text-primary">${totalClaimable.toFixed(2)}</div>
              <div className="stat-desc">Combined funding fees and UI fees</div>
            </div>
          </div>

          {/* Funding Fees Section */}
          {data.claimableFundingFees && (data.claimableFundingFees.totalUsdc ?? 0) > 0 && (
            <div>
              <h3 className="text-xl font-semibold mb-4">Funding Fees</h3>
              <Table
                columns={dataColumns}
                data={fundingFeesData}
                showPagination={false}
              />
            </div>
          )}

          {/* UI Fees Section */}
          {data.claimableUiFees && (data.claimableUiFees.totalUsdc ?? 0) > 0 && (
            <div>
              <h3 className="text-xl font-semibold mb-4">UI Fees</h3>
              <Table
                columns={dataColumns}
                data={uiFeesData}
                showPagination={false}
              />
            </div>
          )}

          {/* Rebate Stats Section */}
          {data.rebateStats && ((data.rebateStats.totalRebateUsdc ?? 0) > 0 || (data.rebateStats.discountUsdc ?? 0) > 0) && (
            <div>
              <h3 className="text-xl font-semibold mb-4">Rebate Statistics</h3>
              <Table
                columns={dataColumns}
                data={rebateStatsData}
                showPagination={false}
              />
            </div>
          )}
        </div>
      )}
    </div>
  )
}

export default AccountFee 