'use client';

import { Award, DollarSign, Star, X } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import PendingSponsorshipRequests, { type PendingRequestDTO } from '../sponsors/PendingSponsorshipRequests';
import Button from '../ui/Button';
import Input from '../ui/Input';

import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { useServices } from '@/lib/services/ServiceProvider';

interface SponsorshipSlot {
  tier: 'main' | 'secondary';
  sponsorName?: string;
  logoUrl?: string;
  price: number;
  isOccupied: boolean;
}

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

export function LeagueSponsorshipsSection({
  leagueId,
  seasonId: propSeasonId,
  readOnly = false
}: LeagueSponsorshipsSectionProps) {
  const currentDriverId = useEffectiveDriverId();
  const { sponsorshipService, leagueService } = useServices();
  const [slots, setSlots] = useState<SponsorshipSlot[]>([
    { tier: 'main', price: 500, isOccupied: false },
    { tier: 'secondary', price: 200, isOccupied: false },
    { tier: 'secondary', price: 200, isOccupied: false },
  ]);
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [tempPrice, setTempPrice] = useState<string>('');
  const [pendingRequests, setPendingRequests] = useState<PendingRequestDTO[]>([]);
  const [requestsLoading, setRequestsLoading] = useState(false);
  const [seasonId, setSeasonId] = useState<string | undefined>(propSeasonId);

  // Load season ID if not provided
  useEffect(() => {
    async function loadSeasonId() {
      if (propSeasonId) {
        setSeasonId(propSeasonId);
        return;
      }
      try {
        const seasons = await leagueService.getLeagueSeasons(leagueId);
        const activeSeason = seasons.find((s) => s.status === 'active') ?? seasons[0];
        if (activeSeason) setSeasonId(activeSeason.seasonId);
      } catch (err) {
        console.error('Failed to load season:', err);
      }
    }
    loadSeasonId();
  }, [leagueId, propSeasonId, leagueService]);

  // Load pending sponsorship requests
  const loadPendingRequests = useCallback(async () => {
    if (!seasonId) return;
    
    setRequestsLoading(true);
    try {
      const requests = await sponsorshipService.getPendingSponsorshipRequests({
        entityType: 'season',
        entityId: seasonId,
      });

      // Convert service view-models to component DTO type (UI-only)
      setPendingRequests(
        requests.map(
          (r): PendingRequestDTO => ({
            id: r.id,
            sponsorId: r.sponsorId,
            sponsorName: r.sponsorName,
            sponsorLogo: r.sponsorLogo,
            tier: r.tier,
            offeredAmount: r.offeredAmount,
            currency: r.currency,
            formattedAmount: r.formattedAmount,
            message: r.message,
            createdAt: r.createdAt,
            platformFee: r.platformFee,
            netAmount: r.netAmount,
          }),
        ),
      );
    } catch (err) {
      console.error('Failed to load pending requests:', err);
    } finally {
      setRequestsLoading(false);
    }
  }, [seasonId, sponsorshipService]);

  useEffect(() => {
    loadPendingRequests();
  }, [loadPendingRequests]);

  const handleAcceptRequest = async (requestId: string) => {
    try {
      await sponsorshipService.acceptSponsorshipRequest(requestId, currentDriverId);
      await loadPendingRequests();
    } catch (err) {
      console.error('Failed to accept request:', err);
      alert(err instanceof Error ? err.message : 'Failed to accept request');
    }
  };

  const handleRejectRequest = async (requestId: string, reason?: string) => {
    try {
      await sponsorshipService.rejectSponsorshipRequest(requestId, currentDriverId, reason);
      await loadPendingRequests();
    } catch (err) {
      console.error('Failed to reject request:', err);
      alert(err instanceof Error ? err.message : 'Failed to reject request');
    }
  };

  const handleEditPrice = (index: number) => {
    const slot = slots[index];
    if (!slot) return;
    setEditingIndex(index);
    setTempPrice(slot.price.toString());
  };

  const handleSavePrice = (index: number) => {
    const price = parseFloat(tempPrice);
    if (!isNaN(price) && price > 0) {
      const updated = [...slots];
      const slot = updated[index];
      if (slot) {
        slot.price = price;
        setSlots(updated);
      }
    }
    setEditingIndex(null);
    setTempPrice('');
  };

  const handleCancelEdit = () => {
    setEditingIndex(null);
    setTempPrice('');
  };

  const totalRevenue = slots.reduce((sum, slot) => 
    slot.isOccupied ? sum + slot.price : sum, 0
  );
  const platformFee = totalRevenue * 0.10;
  const netRevenue = totalRevenue - platformFee;

  const availableSlots = slots.filter(s => !s.isOccupied).length;
  const occupiedSlots = slots.filter(s => s.isOccupied).length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold text-white">Sponsorships</h3>
          <p className="text-sm text-gray-400 mt-1">
            Define pricing for sponsor slots in this league. Sponsors pay per season.
          </p>
          <p className="text-xs text-gray-500 mt-1">
            These sponsors are attached to seasons in this league, so you can change partners from season to season.
          </p>
        </div>
        {!readOnly && (
          <div className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-primary-blue/10 border border-primary-blue/30">
            <DollarSign className="w-4 h-4 text-primary-blue" />
            <span className="text-xs font-medium text-primary-blue">
              {availableSlots} slot{availableSlots !== 1 ? 's' : ''} available
            </span>
          </div>
        )}
      </div>

      {/* Revenue Summary */}
      {totalRevenue > 0 && (
        <div className="grid grid-cols-3 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">Total Revenue</div>
            <div className="text-xl font-bold text-white">
              ${totalRevenue.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">Platform Fee (10%)</div>
            <div className="text-xl 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 Revenue</div>
            <div className="text-xl font-bold text-performance-green">
              ${netRevenue.toFixed(2)}
            </div>
          </div>
        </div>
      )}

      {/* Sponsorship Slots */}
      <div className="space-y-3">
        {slots.map((slot, index) => {
          const isEditing = editingIndex === index;
          const Icon = slot.tier === 'main' ? Star : Award;
          
          return (
            <div
              key={index}
              className="rounded-lg border border-charcoal-outline bg-deep-graphite/70 p-4"
            >
              <div className="flex items-center justify-between gap-4">
                <div className="flex items-center gap-3 flex-1">
                  <div className={`flex h-10 w-10 items-center justify-center rounded-lg ${
                    slot.tier === 'main' 
                      ? 'bg-primary-blue/10' 
                      : 'bg-gray-500/10'
                  }`}>
                    <Icon className={`w-5 h-5 ${
                      slot.tier === 'main' 
                        ? 'text-primary-blue' 
                        : 'text-gray-400'
                    }`} />
                  </div>
                  
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <h4 className="text-sm font-semibold text-white">
                        {slot.tier === 'main' ? 'Main Sponsor' : 'Secondary Sponsor'}
                      </h4>
                      {slot.isOccupied && (
                        <span className="px-2 py-0.5 text-xs bg-performance-green/10 text-performance-green border border-performance-green/30 rounded-full">
                          Occupied
                        </span>
                      )}
                    </div>
                    <p className="text-xs text-gray-500 mt-0.5">
                      {slot.tier === 'main' 
                        ? 'Big livery slot • League page logo • Name in league title'
                        : 'Small livery slot • League page logo'}
                    </p>
                  </div>
                </div>

                <div className="flex items-center gap-3">
                  {isEditing ? (
                    <div className="flex items-center gap-2">
                      <Input
                        type="number"
                        value={tempPrice}
                        onChange={(e) => setTempPrice(e.target.value)}
                        placeholder="Price"
                        className="w-32"
                        min="0"
                        step="0.01"
                      />
                      <Button
                        variant="primary"
                        onClick={() => handleSavePrice(index)}
                        className="px-3 py-1"
                      >
                        Save
                      </Button>
                      <Button
                        variant="secondary"
                        onClick={handleCancelEdit}
                        className="px-3 py-1"
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    </div>
                  ) : (
                    <>
                      <div className="text-right">
                        <div className="text-lg font-bold text-white">
                          ${slot.price.toFixed(2)}
                        </div>
                        <div className="text-xs text-gray-500">per season</div>
                      </div>
                      {!readOnly && !slot.isOccupied && (
                        <Button
                          variant="secondary"
                          onClick={() => handleEditPrice(index)}
                          className="px-3 py-1"
                        >
                          Edit Price
                        </Button>
                      )}
                    </>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Pending Sponsorship Requests */}
      {!readOnly && (pendingRequests.length > 0 || requestsLoading) && (
        <div className="mt-8 pt-6 border-t border-charcoal-outline">
          <PendingSponsorshipRequests
            entityType="season"
            entityId={seasonId || ''}
            entityName="this league"
            requests={pendingRequests}
            onAccept={handleAcceptRequest}
            onReject={handleRejectRequest}
            isLoading={requestsLoading}
          />
        </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> Sponsorship management is demonstration-only.
          In production, sponsors can browse leagues, select slots, and complete payment integration.
        </p>
      </div>
    </div>
  );
}
