'use client';

import { Badge } from '@/ui/Badge';
import { Button } from '@/ui/Button';
import { Heading } from '@/ui/Heading';
import { Icon } from '@/ui/Icon';
import { Input } from '@/ui/Input';
import { Stack } from '@/ui/Stack';
import { StatBox } from '@/ui/StatBox';
import { Text } from '@/ui/Text';
import { Award, DollarSign, Star, X } from 'lucide-react';
import { useState } from 'react';
import { PendingSponsorshipRequests } from '../sponsors/PendingSponsorshipRequests';

import { useLeagueSeasons } from "@/hooks/league/useLeagueSeasons";
import { useSponsorshipRequests } from "@/hooks/league/useSponsorshipRequests";
import { useEffectiveDriverId } from "@/hooks/useEffectiveDriverId";
import { useInject } from '@/lib/di/hooks/useInject';
import { SPONSOR_SERVICE_TOKEN } from '@/lib/di/tokens';

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 = useInject(SPONSOR_SERVICE_TOKEN);
  
  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>('');

  // Load season ID if not provided
  const { data: seasonsResult } = useLeagueSeasons(leagueId);
  const seasons = seasonsResult?.isOk() ? seasonsResult.unwrap() : [];
  const activeSeason = seasons.find((s: any) => s.status === 'active') ?? seasons[0];
  const seasonId = propSeasonId || activeSeason?.seasonId;

  // Load pending sponsorship requests
  const { data: pendingRequestsData, isLoading: requestsLoading, refetch: refetchRequests } = useSponsorshipRequests('season', seasonId || '');
  const pendingRequests = pendingRequestsData?.requests || [];

  const handleAcceptRequest = async (requestId: string) => {
    if (!currentDriverId) return;
    
    try {
      await (sponsorshipService as any).acceptSponsorshipRequest(requestId, currentDriverId);
      await refetchRequests();
    } 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) => {
    if (!currentDriverId) return;
    
    try {
      await (sponsorshipService as any).rejectSponsorshipRequest(requestId, currentDriverId, reason);
      await refetchRequests();
    } 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;

  return (
    <Stack gap={6}>
      {/* Header */}
      <Stack display="flex" alignItems="center" justifyContent="between">
        <Stack>
          <Heading level={3}>Sponsorships</Heading>
          <Text size="sm" color="text-gray-400" mt={1} block>
            Define pricing for sponsor slots in this league. Sponsors pay per season.
          </Text>
          <Text size="xs" color="text-gray-500" mt={1} block>
            These sponsors are attached to seasons in this league, so you can change partners from season to season.
          </Text>
        </Stack>
        {!readOnly && (
          <Stack display="flex" alignItems="center" gap={2} px={3} py={1.5} rounded="full" bg="bg-primary-blue/10" border borderColor="border-primary-blue/30">
            <Icon icon={DollarSign} size={4} color="var(--primary-blue)" />
            <Text size="xs" weight="medium" color="text-primary-blue">
              {availableSlots} slot{availableSlots !== 1 ? 's' : ''} available
            </Text>
          </Stack>
        )}
      </Stack>

      {/* Revenue Summary */}
      {totalRevenue > 0 && (
        <Stack display="grid" gridCols={3} gap={4}>
          <StatBox
            icon={DollarSign}
            label="Total Revenue"
            value={`$${totalRevenue.toFixed(2)}`}
            color="var(--primary-blue)"
          />
          <StatBox
            icon={DollarSign}
            label="Platform Fee (10%)"
            value={`-$${platformFee.toFixed(2)}`}
            color="var(--warning-amber)"
          />
          <StatBox
            icon={DollarSign}
            label="Net Revenue"
            value={`$${netRevenue.toFixed(2)}`}
            color="var(--performance-green)"
          />
        </Stack>
      )}

      {/* Sponsorship Slots */}
      <Stack gap={3}>
        {slots.map((slot, index) => {
          const isEditing = editingIndex === index;
          const IconComp = slot.tier === 'main' ? Star : Award;
          
          return (
            <Stack
              key={index}
              rounded="lg"
              border
              borderColor="border-charcoal-outline"
              bg="bg-deep-graphite/70"
              p={4}
            >
              <Stack display="flex" alignItems="center" justifyContent="between" gap={4}>
                <Stack display="flex" alignItems="center" gap={3} flexGrow={1}>
                  <Stack 
                    display="flex" 
                    h="10" 
                    w="10" 
                    alignItems="center" 
                    justifyContent="center" 
                    rounded="lg" 
                    bg={slot.tier === 'main' ? 'bg-primary-blue/10' : 'bg-gray-500/10'}
                  >
                    <Icon icon={IconComp} size={5} color={slot.tier === 'main' ? 'var(--primary-blue)' : 'var(--gray-400)'} />
                  </Stack>
                  
                  <Stack flexGrow={1}>
                    <Stack display="flex" alignItems="center" gap={2}>
                      <Heading level={4}>
                        {slot.tier === 'main' ? 'Main Sponsor' : 'Secondary Sponsor'}
                      </Heading>
                      {slot.isOccupied && (
                        <Badge variant="success">
                          Occupied
                        </Badge>
                      )}
                    </Stack>
                    <Text size="xs" color="text-gray-500" mt={0.5} block>
                      {slot.tier === 'main' 
                        ? 'Big livery slot • League page logo • Name in league title'
                        : 'Small livery slot • League page logo'}
                    </Text>
                  </Stack>
                </Stack>

                <Stack display="flex" alignItems="center" gap={3}>
                  {isEditing ? (
                    <Stack display="flex" alignItems="center" gap={2}>
                      <Input
                        type="number"
                        value={tempPrice}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTempPrice(e.target.value)}
                        placeholder="Price"
                        // eslint-disable-next-line gridpilot-rules/component-classification
                        className="w-32"
                        min="0"
                        step="0.01"
                      />
                      <Button
                        variant="primary"
                        onClick={() => handleSavePrice(index)}
                        size="sm"
                      >
                        Save
                      </Button>
                      <Button
                        variant="secondary"
                        onClick={handleCancelEdit}
                        size="sm"
                      >
                        <Icon icon={X} size={4} />
                      </Button>
                    </Stack>
                  ) : (
                    <>
                      <Stack textAlign="right">
                        <Text size="lg" weight="bold" color="text-white" block>
                          ${slot.price.toFixed(2)}
                        </Text>
                        <Text size="xs" color="text-gray-500" block>per season</Text>
                      </Stack>
                      {!readOnly && !slot.isOccupied && (
                        <Button
                          variant="secondary"
                          onClick={() => handleEditPrice(index)}
                          size="sm"
                        >
                          Edit Price
                        </Button>
                      )}
                    </>
                  )}
                </Stack>
              </Stack>
            </Stack>
          );
        })}
      </Stack>

      {/* Pending Sponsorship Requests */}
      {!readOnly && (pendingRequests.length > 0 || requestsLoading) && (
        <Stack mt={8} pt={6} borderTop borderColor="border-charcoal-outline">
          <PendingSponsorshipRequests
            entityType="season"
            entityId={seasonId || ''}
            entityName="this league"
            requests={pendingRequests}
            onAccept={handleAcceptRequest}
            onReject={handleRejectRequest}
            isLoading={requestsLoading}
          />
        </Stack>
      )}

      {/* Alpha Notice */}
      <Stack rounded="lg" bg="bg-warning-amber/10" border borderColor="border-warning-amber/30" p={4}>
        <Text size="xs" color="text-gray-400" block>
          <Text weight="bold" color="text-warning-amber">Alpha Note:</Text> Sponsorship management is demonstration-only.
          In production, sponsors can browse leagues, select slots, and complete payment integration.
        </Text>
      </Stack>
    </Stack>
  );
}
