import {useState} from 'react'

const FeeCalculator: React.FC = () => {
  const [volumeUsd, setVolumeUsd] = useState<number>(1400000)
  const [uiFeePercent, setUiFeePercent] = useState<number>(0.02)
  const [rebatePercent, setRebatePercent] = useState<number>(20)
  const [fundingFeeRate, setFundingFeeRate] = useState<number>(0.00371) // Based on example: ~0.065 USD for 1751 USD volume
  
  // Based on the specific example: 10% rebate on $1751 = $0.0983
  // This means at 10% rebate, $1 of volume = $0.0000561393 rebated
  // So the base rebate rate per $1 at 100% would be $0.000561393
  const BASE_REBATE_PER_DOLLAR = 0.0000561393
  
  const calculateFees = () => {
    // UI Fee is applied directly as a percentage of volume
    const dailyUiFees = volumeUsd * (uiFeePercent / 100)
    
    // Calculate rebate based on the exact ratio provided
    // For 10% rebate on $1751 resulting in $0.0983 rebate
    const dailyRebate = volumeUsd * BASE_REBATE_PER_DOLLAR * (rebatePercent / 10) // Normalize to 10% base
    
    // Calculate funding fees based on the provided example (0.065 USD for 1751 USD)
    const dailyFundingFees = volumeUsd * (fundingFeeRate / 100)
    
    // Total revenue is UI fees + rebates + funding fees
    const dailyTotalRevenue = dailyUiFees + dailyRebate + dailyFundingFees
    
    return {
      daily: {
        volume: volumeUsd,
        uiFees: dailyUiFees,
        rebate: dailyRebate,
        fundingFees: dailyFundingFees,
        totalRevenue: dailyTotalRevenue
      },
      weekly: {
        volume: volumeUsd * 7,
        uiFees: dailyUiFees * 7,
        rebate: dailyRebate * 7,
        fundingFees: dailyFundingFees * 7,
        totalRevenue: dailyTotalRevenue * 7
      },
      monthly: {
        volume: volumeUsd * 30,
        uiFees: dailyUiFees * 30,
        rebate: dailyRebate * 30,
        fundingFees: dailyFundingFees * 30,
        totalRevenue: dailyTotalRevenue * 30
      },
      yearly: {
        volume: volumeUsd * 365,
        uiFees: dailyUiFees * 365,
        rebate: dailyRebate * 365,
        fundingFees: dailyFundingFees * 365,
        totalRevenue: dailyTotalRevenue * 365
      }
    }
  }
  
  const fees = calculateFees()
  
  // Test calculations
  const testVolume = 1751
  const testRebate = testVolume * BASE_REBATE_PER_DOLLAR * (rebatePercent / 10)
  const testFundingFee = testVolume * (fundingFeeRate / 100)
  
  return (
    <div className="container p-4">
      <h2 className="text-2xl font-bold mb-4">Platform Revenue Calculator</h2>
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div className="form-control">
          <label className="label">
            <span className="label-text">Daily Volume (USD)</span>
          </label>
          <input 
            type="number" 
            value={volumeUsd}
            onChange={(e) => setVolumeUsd(Number(e.target.value))}
            className="input input-bordered" 
          />
        </div>
        
        <div className="form-control">
          <label className="label">
            <span className="label-text">UI Fee (%)</span>
            <span className="label-text-alt">Fee charged on transactions</span>
          </label>
          <input 
            type="number" 
            value={uiFeePercent}
            onChange={(e) => setUiFeePercent(Number(e.target.value))}
            className="input input-bordered" 
            step="0.001"
          />
        </div>
        
        <div className="form-control">
          <label className="label">
            <span className="label-text">Rebate (%)</span>
            <span className="label-text-alt">Rebate received from transactions</span>
          </label>
          <input 
            type="number" 
            value={rebatePercent}
            onChange={(e) => setRebatePercent(Number(e.target.value))}
            className="input input-bordered"
          />
        </div>
        
        <div className="form-control">
          <label className="label">
            <span className="label-text">Funding Fee Rate (%)</span>
            <span className="label-text-alt">Funding fees from agents</span>
          </label>
          <input 
            type="number" 
            value={fundingFeeRate}
            onChange={(e) => setFundingFeeRate(Number(e.target.value))}
            className="input input-bordered"
            step="0.0001"
          />
        </div>
      </div>
      
      <div className="overflow-x-auto">
        <table className="table w-full">
          <thead>
            <tr>
              <th>Period</th>
              <th>Volume (USD)</th>
              <th>UI Fees (USD)</th>
              <th>Rebates (USD)</th>
              <th>Funding Fees (USD)</th>
              <th>Total Revenue (USD)</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Daily</td>
              <td>${fees.daily.volume.toLocaleString(undefined, {maximumFractionDigits: 0})}</td>
              <td>${fees.daily.uiFees.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
              <td>${fees.daily.rebate.toLocaleString(undefined, {minimumFractionDigits: 4, maximumFractionDigits: 4})}</td>
              <td>${fees.daily.fundingFees.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
              <td className="font-bold">${fees.daily.totalRevenue.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
            </tr>
            <tr>
              <td>Weekly</td>
              <td>${fees.weekly.volume.toLocaleString(undefined, {maximumFractionDigits: 0})}</td>
              <td>${fees.weekly.uiFees.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
              <td>${fees.weekly.rebate.toLocaleString(undefined, {minimumFractionDigits: 4, maximumFractionDigits: 4})}</td>
              <td>${fees.weekly.fundingFees.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
              <td className="font-bold">${fees.weekly.totalRevenue.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
            </tr>
            <tr>
              <td>Monthly</td>
              <td>${fees.monthly.volume.toLocaleString(undefined, {maximumFractionDigits: 0})}</td>
              <td>${fees.monthly.uiFees.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
              <td>${fees.monthly.rebate.toLocaleString(undefined, {minimumFractionDigits: 4, maximumFractionDigits: 4})}</td>
              <td>${fees.monthly.fundingFees.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
              <td className="font-bold">${fees.monthly.totalRevenue.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
            </tr>
            <tr>
              <td>Yearly</td>
              <td>${fees.yearly.volume.toLocaleString(undefined, {maximumFractionDigits: 0})}</td>
              <td>${fees.yearly.uiFees.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
              <td>${fees.yearly.rebate.toLocaleString(undefined, {minimumFractionDigits: 4, maximumFractionDigits: 4})}</td>
              <td>${fees.yearly.fundingFees.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
              <td className="font-bold">${fees.yearly.totalRevenue.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div className="alert alert-info mt-4">
        <div className="flex flex-col gap-1">
          <div>
            <span className="font-semibold">Verification:</span> For a volume of $1751:
          </div>
          <div className="pl-4">- With 10% rebate, the calculated rebate is ${testRebate.toFixed(4)} USD</div>
          <div className="pl-4">- The funding fee is ${testFundingFee.toFixed(2)} USD</div>
        </div>
      </div>
      
      <div className="mt-8 bg-base-200 p-4 rounded-lg">
        <h3 className="text-lg font-semibold mb-2">How platform revenue is calculated</h3>
        <ul className="list-disc pl-5 space-y-2">
          <li><strong>UI Fee:</strong> Charged on top of the base fee for transactions. For position operations, it's a percentage of the increase/decrease size.</li>
          <li><strong>Rebate:</strong> Based on a ratio where $1 of volume with a 10% rebate generates $0.0000561393 of rebate. The actual rebate scales with both volume and rebate percentage.</li>
          <li><strong>Funding Fee:</strong> Fees generated by agents based on the trading volume. This is a percentage of the total volume.</li>
          <li><strong>Total Revenue:</strong> The combined income from UI fees, rebates, and funding fees.</li>
        </ul>
        
        <h4 className="text-md font-semibold mt-4 mb-2">Fee Details</h4>
        <p className="text-sm">
          UI fees are charged on top of the base fee. The percentage amount is based on the amount configured for the uiFeeReceiver address.
          The uiFeeFactor is a percentage value over 10^30. For example, if the uiFeeFactor is 2 * 10^25, the percentage charged would be 0.002%.
        </p>
        <p className="text-sm mt-2">
          Both UI fees, rebates, and funding fees contribute to the platform's revenue stream and can be used to cover on-chain transaction costs and other operational expenses.
        </p>
      </div>
    </div>
  )
}

export default FeeCalculator
