'use client';

import { useState } from 'react';
import { Button } from '@/ui/Button';
import { Input } from '@/ui/Input';
import { DollarSign, Calendar, User, TrendingUp } from 'lucide-react';

type FeeType = 'season' | 'monthly' | 'per_race';

interface MembershipFeeConfig {
  type: FeeType;
  amount: number;
  enabled: boolean;
}

interface LeagueMembershipFeesSectionProps {
  leagueId: string;
  seasonId?: string;
  readOnly?: boolean;
}

export function LeagueMembershipFeesSection({ 
  leagueId, 
  seasonId,
  readOnly = false 
}: LeagueMembershipFeesSectionProps) {
  const [feeConfig, setFeeConfig] = useState<MembershipFeeConfig>({
    type: 'season',
    amount: 0,
    enabled: false,
  });
  const [tempAmount, setTempAmount] = useState<string>('0');
  const [editing, setEditing] = useState(false);

  const handleEnableFees = () => {
    setFeeConfig({ ...feeConfig, enabled: true });
    setEditing(true);
    setTempAmount(feeConfig.amount.toString());
  };

  const handleSave = () => {
    const amount = parseFloat(tempAmount);
    if (!isNaN(amount) && amount > 0) {
      setFeeConfig({ ...feeConfig, amount });
    }
    setEditing(false);
  };

  const handleCancel = () => {
    setEditing(false);
    setTempAmount(feeConfig.amount.toString());
  };

  const handleTypeChange = (type: FeeType) => {
    setFeeConfig({ ...feeConfig, type });
  };

  const platformFee = feeConfig.amount * 0.10;
  const netAmount = feeConfig.amount - platformFee;

  const typeLabels: Record<FeeType, string> = {
    season: 'Season Fee',
    monthly: 'Monthly Subscription',
    per_race: 'Per-Race Fee',
  };

  const typeDescriptions: Record<FeeType, string> = {
    season: 'Single payment for entire season',
    monthly: 'Recurring monthly payment',
    per_race: 'Payment required per race entry',
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold text-white">Membership Fees</h3>
          <p className="text-sm text-gray-400 mt-1">
            Charge drivers for league participation
          </p>
        </div>
        {!feeConfig.enabled && !readOnly && (
          <Button
            variant="primary"
            onClick={handleEnableFees}
          >
            Enable Fees
          </Button>
        )}
      </div>

      {!feeConfig.enabled ? (
        <div className="text-center py-12 rounded-lg border border-charcoal-outline bg-iron-gray/30">
          <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-iron-gray/50 flex items-center justify-center">
            <DollarSign className="w-8 h-8 text-gray-500" />
          </div>
          <h4 className="text-lg font-medium text-white mb-2">No Membership Fees</h4>
          <p className="text-sm text-gray-400 max-w-md mx-auto">
            This league is free to join. Enable membership fees to charge drivers for participation.
          </p>
        </div>
      ) : (
        <>
          {/* Fee Type Selection */}
          <div className="space-y-3">
            <label className="block text-sm font-medium text-gray-300">
              Fee Type
            </label>
            <div className="grid grid-cols-3 gap-3">
              {(['season', 'monthly', 'per_race'] as FeeType[]).map((type) => {
                const Icon = type === 'season' ? Calendar : type === 'monthly' ? TrendingUp : User;
                const isSelected = feeConfig.type === type;
                
                return (
                  <button
                    key={type}
                    type="button"
                    onClick={() => handleTypeChange(type)}
                    disabled={readOnly}
                    className={`p-4 rounded-lg border transition-all ${
                      isSelected
                        ? 'border-primary-blue bg-primary-blue/10'
                        : 'border-charcoal-outline bg-iron-gray/30 hover:border-primary-blue/50'
                    }`}
                  >
                    <Icon className={`w-5 h-5 mx-auto mb-2 ${
                      isSelected ? 'text-primary-blue' : 'text-gray-400'
                    }`} />
                    <div className="text-sm font-medium text-white mb-1">
                      {typeLabels[type]}
                    </div>
                    <div className="text-xs text-gray-500">
                      {typeDescriptions[type]}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Amount Configuration */}
          <div className="space-y-3">
            <label className="block text-sm font-medium text-gray-300">
              Amount
            </label>
            
            {editing ? (
              <div className="flex items-center gap-3">
                <div className="flex-1">
                  <Input
                    type="number"
                    value={tempAmount}
                    onChange={(e) => setTempAmount(e.target.value)}
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                  />
                </div>
                <Button
                  variant="primary"
                  onClick={handleSave}
                  className="px-4"
                >
                  Save
                </Button>
                <Button
                  variant="secondary"
                  onClick={handleCancel}
                  className="px-4"
                >
                  Cancel
                </Button>
              </div>
            ) : (
              <div className="flex items-center justify-between p-4 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
                <div>
                  <div className="text-2xl font-bold text-white">
                    ${feeConfig.amount.toFixed(2)}
                  </div>
                  <div className="text-xs text-gray-500 mt-1">
                    {typeLabels[feeConfig.type]}
                  </div>
                </div>
                {!readOnly && (
                  <Button
                    variant="secondary"
                    onClick={() => setEditing(true)}
                    className="px-4"
                  >
                    Edit Amount
                  </Button>
                )}
              </div>
            )}
          </div>

          {/* Revenue Breakdown */}
          {feeConfig.amount > 0 && (
            <div className="grid grid-cols-2 gap-4">
              <div className="rounded-lg bg-iron-gray/50 border border-charcoal-outline p-4">
                <div className="text-xs text-gray-400 mb-1">Platform Fee (10%)</div>
                <div className="text-lg font-bold text-warning-amber">
                  -${platformFee.toFixed(2)}
                </div>
              </div>
              <div className="rounded-lg bg-iron-gray/50 border border-charcoal-outline p-4">
                <div className="text-xs text-gray-400 mb-1">Net per Driver</div>
                <div className="text-lg font-bold text-performance-green">
                  ${netAmount.toFixed(2)}
                </div>
              </div>
            </div>
          )}

          {/* Disable Fees */}
          {!readOnly && (
            <div className="pt-4 border-t border-charcoal-outline">
              <Button
                variant="danger"
                onClick={() => setFeeConfig({ type: 'season', amount: 0, enabled: false })}
              >
                Disable Membership Fees
              </Button>
            </div>
          )}
        </>
      )}

      {/* Alpha Notice */}
      <div className="rounded-lg bg-warning-amber/10 border border-warning-amber/30 p-4">
        <p className="text-xs text-gray-400">
          <strong className="text-warning-amber">Alpha Note:</strong> Membership fee collection is demonstration-only.
          In production, fees are collected via payment gateway and deposited to league wallet (minus platform fee).
        </p>
      </div>
    </div>
  );
}