'use client';

import { ReadonlyLeagueInfo } from '@/components/leagues/ReadonlyLeagueInfo';
import LeagueOwnershipTransfer from '@/components/leagues/LeagueOwnershipTransfer';
import Card from '@/components/ui/Card';
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { useParams, useRouter } from 'next/navigation';

// Shared state components
import { StateContainer } from '@/components/shared/state/StateContainer';
import { LoadingWrapper } from '@/components/shared/state/LoadingWrapper';
import { useLeagueAdminStatus } from '@/hooks/league/useLeagueAdminStatus';
import { useLeagueSettings } from '@/hooks/league/useLeagueSettings';
import { useInject } from '@/lib/di/hooks/useInject';
import { LEAGUE_SETTINGS_SERVICE_TOKEN } from '@/lib/di/tokens';
import { AlertTriangle, Settings } from 'lucide-react';

export default function LeagueSettingsPage() {
  const params = useParams();
  const leagueId = params.id as string;
  const currentDriverId = useEffectiveDriverId();
  const leagueSettingsService = useInject(LEAGUE_SETTINGS_SERVICE_TOKEN);
  const router = useRouter();

  // Check admin status using DI + React-Query
  const { data: isAdmin, isLoading: adminLoading } = useLeagueAdminStatus(leagueId, currentDriverId ?? '');

  // Load settings (only if admin) using DI + React-Query
  const { data: settings, isLoading: settingsLoading, error, retry } = useLeagueSettings(leagueId, { enabled: !!isAdmin });

  const handleTransferOwnership = async (newOwnerId: string) => {
    try {
      await leagueSettingsService.transferOwnership(leagueId, currentDriverId ?? '', newOwnerId);
      router.refresh();
    } catch (err) {
      throw err; // Let the component handle the error
    }
  };

  // Show loading for admin check
  if (adminLoading) {
    return <LoadingWrapper variant="full-screen" message="Checking permissions..." />;
  }

  // Show access denied if not admin
  if (!isAdmin) {
    return (
      <Card>
        <div className="text-center py-12">
          <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-iron-gray/50 flex items-center justify-center">
            <AlertTriangle className="w-8 h-8 text-warning-amber" />
          </div>
          <h3 className="text-lg font-medium text-white mb-2">Admin Access Required</h3>
          <p className="text-sm text-gray-400">
            Only league admins can access settings.
          </p>
        </div>
      </Card>
    );
  }

  return (
    <StateContainer
      data={settings}
      isLoading={settingsLoading}
      error={error}
      retry={retry}
      config={{
        loading: { variant: 'spinner', message: 'Loading settings...' },
        error: { variant: 'full-screen' },
        empty: {
          icon: Settings,
          title: 'No settings available',
          description: 'Unable to load league configuration.',
        }
      }}
    >
      {(settingsData) => (
        <div className="space-y-6">
          {/* Header */}
          <div className="flex items-center gap-3">
            <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary-blue/10">
              <Settings className="w-6 h-6 text-primary-blue" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">League Settings</h1>
              <p className="text-sm text-gray-400">Manage your league configuration</p>
            </div>
          </div>

          {/* READONLY INFORMATION SECTION - Compact */}
          <div className="space-y-4">
            <ReadonlyLeagueInfo league={settingsData!.league} configForm={settingsData!.config} />

            <LeagueOwnershipTransfer
              settings={settingsData!}
              currentDriverId={currentDriverId ?? ''}
              onTransferOwnership={handleTransferOwnership}
            />
          </div>
        </div>
      )}
    </StateContainer>
  );
}
